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 |
|---|---|---|---|---|
progress.rs | use num_enum::IntoPrimitive;
use once_cell::sync::Lazy;
use std::sync::mpsc::Sender;
use std::{mem, pin::Pin, ptr};
use wchar::*;
use widestring::*;
use winapi::shared::basetsd;
use winapi::shared::minwindef as win;
use winapi::shared::windef::*;
use winapi::um::commctrl;
use winapi::um::errhandlingapi;
use winapi::um:... | () -> bool {
unsafe {
let instance = libloaderapi::GetModuleHandleW(ptr::null_mut());
let mut wc: winuser::WNDCLASSEXW = mem::zeroed();
winuser::GetClassInfoExW(instance, WND_CLASS.as_ptr(), &mut wc)!= 0
}
}
/// Register window class.
pub fn register_wind... | is_window_class_registered | identifier_name |
progress.rs | use num_enum::IntoPrimitive;
use once_cell::sync::Lazy;
use std::sync::mpsc::Sender;
use std::{mem, pin::Pin, ptr};
use wchar::*;
use widestring::*;
use winapi::shared::basetsd;
use winapi::shared::minwindef as win;
use winapi::shared::windef::*;
use winapi::um::commctrl;
use winapi::um::errhandlingapi;
use winapi::um:... |
let hwnd = self.get_control_handle(Control::ProgressBar);
unsafe { SendMessageW(hwnd, PBM_SETPOS, current, 0) };
// if done, close cancellation channel
if current == max {
self.cancel_sender.take();
}
}
/// Check whether progress bar is in marquee mode.
... | {
self.set_progress_to_range_mode();
} | conditional_block |
typescript.rs | //! Generation of Typescript types from Stencila Schema
use std::{
collections::HashSet,
fs::read_dir,
path::{Path, PathBuf},
};
use common::{
async_recursion::async_recursion,
eyre::{bail, Context, Report, Result},
futures::future::try_join_all,
inflector::Inflector,
itertools::Iterto... | (dest: &Path, title: &String, schema: &Schema) -> Result<String> {
let path = dest.join(format!("{}.ts", title));
if path.exists() {
return Ok(title.to_string());
}
let description = schema
.description
.as_ref()
.unwrap_or(title)
... | typescript_object | identifier_name |
typescript.rs | //! Generation of Typescript types from Stencila Schema
use std::{
collections::HashSet,
fs::read_dir,
path::{Path, PathBuf},
};
use common::{
async_recursion::async_recursion,
eyre::{bail, Context, Report, Result},
futures::future::try_join_all,
inflector::Inflector,
itertools::Iterto... |
/// Generate a TypeScript type for a schema
///
/// Returns the name of the type and whether:
/// - it is an array
/// - it is a type (rather than an enum variant)
#[async_recursion]
async fn typescript_type(dest: &Path, schema: &Schema) -> Result<(String, bool, bool)> {
use Type... | {
let Some(title) = &schema.title else {
bail!("Schema has no title");
};
if NO_GENERATE_MODULE.contains(&title.as_str()) || schema.r#abstract {
return Ok(());
}
if schema.any_of.is_some() {
Self::typescript_any_of(dest, schema).await?;
... | identifier_body |
typescript.rs | //! Generation of Typescript types from Stencila Schema
use std::{
collections::HashSet,
fs::read_dir,
path::{Path, PathBuf},
};
use common::{
async_recursion::async_recursion,
eyre::{bail, Context, Report, Result},
futures::future::try_join_all,
inflector::Inflector,
itertools::Iterto... | "Object",
"Primitive",
"String",
"TextValue",
"UnsignedInteger",
];
/// Types for which native to TypesScript types are used directly
/// Note that this excludes `Integer`, `UnsignedInteger` and `Object`
/// which although they are implemented as native types have different semantics.
const NATIVE_... | "Null",
"Number", | random_line_split |
version_info.rs | /*!
Version Information.
See [Microsoft's documentation](https://docs.microsoft.com/en-us/windows/desktop/menurc/version-information) for more information.
*/
use std::{char, cmp, fmt, mem, slice};
use std::collections::HashMap;
use crate::image::VS_FIXEDFILEINFO;
use crate::{Error, Result, _Pod as Pod};
use crate:... |
/// Gets the strings in a hash map.
pub fn to_hash_map(self) -> HashMap<String, String> {
let mut hash_map = HashMap::new();
self.visit(&mut hash_map);
hash_map
}
/// Parse the version information.
///
/// Because of the super convoluted format, the visitor pattern is used.
/// Implement the [`Visit` tra... | {
self.visit(&mut ForEachString(&mut f));
} | identifier_body |
version_info.rs | /*!
Version Information.
See [Microsoft's documentation](https://docs.microsoft.com/en-us/windows/desktop/menurc/version-information) for more information.
*/
use std::{char, cmp, fmt, mem, slice};
use std::collections::HashMap;
use crate::image::VS_FIXEDFILEINFO;
use crate::{Error, Result, _Pod as Pod};
use crate:... | (&mut self, _lang: &'a [u16], key: &'a [u16], value: &'a [u16]) {
if Iterator::eq(self.key.chars().map(Ok), char::decode_utf16(key.iter().cloned())) {
self.value = Some(value);
}
}
}
//----------------------------------------------------------------
/*
"version_info": {
"fixed": {.. },
"strings": {.. },
... | string | identifier_name |
version_info.rs | /*!
Version Information.
See [Microsoft's documentation](https://docs.microsoft.com/en-us/windows/desktop/menurc/version-information) for more information.
*/
use std::{char, cmp, fmt, mem, slice};
use std::collections::HashMap;
use crate::image::VS_FIXEDFILEINFO;
use crate::{Error, Result, _Pod as Pod};
use crate:... | // TLV length field larger than the data
parser = Parser::new_zero(&[12, 0, 0, 0]);
assert_eq!(parser.next(), Some(Err(Error::Invalid)));
assert_eq!(parser.next(), None);
// TLV key not nul terminated
parser = Parser::new_zero(&[16, 0, 1, 20, 20, 20, 20, 20]);
assert_eq!(parser.next(), Some(Err(Error::Invalid))... | parser = Parser::new_zero(&[0, 0]);
assert_eq!(parser.next(), Some(Err(Error::Invalid)));
assert_eq!(parser.next(), None);
| random_line_split |
version_info.rs | /*!
Version Information.
See [Microsoft's documentation](https://docs.microsoft.com/en-us/windows/desktop/menurc/version-information) for more information.
*/
use std::{char, cmp, fmt, mem, slice};
use std::collections::HashMap;
use crate::image::VS_FIXEDFILEINFO;
use crate::{Error, Result, _Pod as Pod};
use crate:... |
}
let mut digits = [0u16; 8];
for i in 0..8 {
digits[i] = digit(lang[i]);
}
let lang_id = (digits[0] << 12) | (digits[1] << 8) | (digits[2] << 4) | digits[3];
let charset_id = (digits[4] << 12) | (digits[5] << 8) | (digits[6] << 4) | digits[7];
Ok(Language { lang_id, charset_id })
}
}
impl fmt::Displ... | { num } | conditional_block |
texture.rs | // texture.rs
// Creation and handling of images and textures.
// (c) 2019, Ryan McGowan <ryan@internally-combusted.net>
//! Loading and management of textures.
use gfx_backend_metal as backend;
use nalgebra_glm as glm;
use gfx_hal::{
command::{BufferImageCopy, CommandBuffer, OneShot},
format::{Aspects, Form... | let row_pitch = (row_size + row_alignment_mask) &!row_alignment_mask; // what wizardry is this
let mut writer = device.acquire_mapping_writer::<u8>(buffer_memory, data_range)?;
// Write the data row by row.
for row in 0..image.height() {
let image_offset = (row * row_size) ... | // TODO: Not sure why I have a function to do this but then write it out twice.
let row_size = pixel_size * image.width();
let row_alignment_mask = limits.min_buffer_copy_pitch_alignment as u32 - 1; | random_line_split |
texture.rs | // texture.rs
// Creation and handling of images and textures.
// (c) 2019, Ryan McGowan <ryan@internally-combusted.net>
//! Loading and management of textures.
use gfx_backend_metal as backend;
use nalgebra_glm as glm;
use gfx_hal::{
command::{BufferImageCopy, CommandBuffer, OneShot},
format::{Aspects, Form... | (
&mut self,
device: &<Backend as GfxBackend>::Device,
image_memory: &<Backend as GfxBackend>::Memory,
image_memory_offset: u64,
command_pool: &mut gfx_hal::CommandPool<Backend, Graphics>,
command_queue: &mut gfx_hal::CommandQueue<Backend, Graphics>,
staging_buffe... | copy_image_to_memory | identifier_name |
texture.rs | // texture.rs
// Creation and handling of images and textures.
// (c) 2019, Ryan McGowan <ryan@internally-combusted.net>
//! Loading and management of textures.
use gfx_backend_metal as backend;
use nalgebra_glm as glm;
use gfx_hal::{
command::{BufferImageCopy, CommandBuffer, OneShot},
format::{Aspects, Form... | PipelineStage::TOP_OF_PIPE,
PipelineStage::TRANSFER,
);
// Figure out the size of the texture data.
let pixel_size = mem::size_of::<Rgba<u8>>() as u32;
let row_size = pixel_size * self.size.x as u32;
let row_alignment_mask = limits.min_buffer_copy_pitch_a... | {
device.bind_image_memory(
&image_memory,
image_memory_offset,
&mut self.image.as_mut().unwrap(),
)?;
// Creating an Image is basically like drawing a regular frame except
// the data gets rendered to memory instead of the screen, so we go
//... | identifier_body |
objects.rs | use ggez::input::keyboard;
use ggez::{graphics, Context, GameResult};
use graphics::{Mesh, MeshBuilder, DrawParam};
use crate::game;
use game::movement::Movement;
use game::Draw;
//#region Ship
/// The Ship.\
/// Width and Height is sort of switched here.\
/// This is because the mesh is made to face the right but th... | }
/// Handle keyboard inputs and update the location of the Ship accordingly
pub fn update_movement(&mut self, ctx: &Context) {
/* The current implementation does not allow external forces
This could be easily achieved by having this call take additional params which set
some forc... | {
let (ctx_width, ctx_height) = graphics::drawable_size(ctx);
let ship_width = 18.0;
let ship_height = 20.0;
Ship {
width: ship_width,
height: ship_height,
x: (ctx_width - ship_width)/ 2.0,
y: (ctx_height- ship_height) / 2.0,
... | identifier_body |
objects.rs | use ggez::input::keyboard;
use ggez::{graphics, Context, GameResult};
use graphics::{Mesh, MeshBuilder, DrawParam};
use crate::game;
use game::movement::Movement;
use game::Draw;
//#region Ship
/// The Ship.\
/// Width and Height is sort of switched here.\
/// This is because the mesh is made to face the right but th... | (&mut self) {
self.x += self.speed_x;
self.y += self.speed_y;
self.rotation += self.rotation_speed;
}
/// Returns a boolean that states if someone is within the hitbox of this asteroid
pub fn in_hitbox(&self, (x, y): (f32, f32)) -> bool {
let size;
match &... | update | identifier_name |
objects.rs | use ggez::input::keyboard;
use ggez::{graphics, Context, GameResult};
use graphics::{Mesh, MeshBuilder, DrawParam};
use crate::game;
use game::movement::Movement;
use game::Draw;
//#region Ship
/// The Ship.\
/// Width and Height is sort of switched here.\
/// This is because the mesh is made to face the right but th... | self.mov.force_y,
self.mov.acceleration_x,
self.mov.acceleration_y,
self.mov.speed_x,
self.mov.speed_y,
self.rotation_speed
)
}
}
impl game::Draw for Ship {
fn mesh(&self, ctx: &mut Context) -> GameResult<Mesh> {
let mut m... | Rotation speed: {}\n",
self.mov.force_x, | random_line_split |
fs.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 std::io;
use std::os::unix::io::AsRawFd;
use std::os::unix::net::UnixListener;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use anyhow::{an... |
fn jail_and_fork(
mut keep_rds: Vec<RawDescriptor>,
dir_path: PathBuf,
uid_map: Option<String>,
gid_map: Option<String>,
) -> anyhow::Result<i32> {
// Create new minijail sandbox
let mut j = Minijail::new()?;
j.namespace_pids();
j.namespace_user();
j.namespace_user_disable_setgrou... | {
let egid = unsafe { libc::getegid() };
format!("{} {} 1", egid, egid)
} | identifier_body |
fs.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 std::io;
use std::os::unix::io::AsRawFd;
use std::os::unix::net::UnixListener;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use anyhow::{an... | {
#[argh(option, description = "path to a socket", arg_name = "PATH")]
socket: String,
#[argh(option, description = "the virtio-fs tag", arg_name = "TAG")]
tag: String,
#[argh(option, description = "path to a directory to share", arg_name = "DIR")]
shared_dir: PathBuf,
#[argh(option, descri... | Options | identifier_name |
fs.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 std::io;
use std::os::unix::io::AsRawFd;
use std::os::unix::net::UnixListener;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use anyhow::{an... |
if pid < 0 {
bail!("Fork error! {}", std::io::Error::last_os_error());
}
Ok(pid)
}
struct FsBackend {
server: Arc<fuse::Server<PassthroughFs>>,
tag: [u8; FS_MAX_TAG_LEN],
avail_features: u64,
acked_features: u64,
acked_protocol_features: VhostUserProtocolFeatures,
workers... | {
unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) };
} | conditional_block |
fs.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 std::io;
use std::os::unix::io::AsRawFd;
use std::os::unix::net::UnixListener;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use anyhow::{an... |
/// Starts a vhost-user fs device.
/// Returns an error if the given `args` is invalid or the device fails to run.
pub fn run_fs_device(program_name: &str, args: &[&str]) -> anyhow::Result<()> {
let opts = match Options::from_args(&[program_name], args) {
Ok(opts) => opts,
Err(e) => {
i... | #[argh(option, description = "uid map to use", arg_name = "UIDMAP")]
uid_map: Option<String>,
#[argh(option, description = "gid map to use", arg_name = "GIDMAP")]
gid_map: Option<String>,
} | random_line_split |
clob.rs | //! Содержит типы для работы с большими символьными объектами.
use std::io;
use {Connection, Result, DbResult};
use types::Charset;
use ffi::native::lob::{Lob, LobImpl, LobOpenMode, CharsetForm};
use ffi::types::Piece;
use super::{Bytes, Chars, LobPrivate};
//---------------------------------------------------------... | m, buf);
self.piece = piece;
res
}
}
impl<'lob, 'conn: 'lob> Drop for ClobReader<'lob, 'conn> {
fn drop(&mut self) {
// Невозможно делать панику отсюда, т.к. приложение из-за этого крашится
let _ = self.lob.close(self.piece);//.expect("Error when close CLOB reader");
}
} | res, piece) = self.lob.impl_.read(self.piece, self.charset, self.lob.for | conditional_block |
clob.rs | //! Содержит типы для работы с большими символьными объектами.
use std::io;
use {Connection, Result, DbResult};
use types::Charset;
use ffi::native::lob::{Lob, LobImpl, LobOpenMode, CharsetForm};
use ffi::types::Piece;
use super::{Bytes, Chars, LobPrivate};
//---------------------------------------------------------... | iece;
res
}
}
impl<'lob, 'conn: 'lob> Drop for ClobReader<'lob, 'conn> {
fn drop(&mut self) {
// Невозможно делать панику отсюда, т.к. приложение из-за этого крашится
let _ = self.lob.close(self.piece);//.expect("Error when close CLOB reader");
}
} | читателем.
pub fn lob(&mut self) -> &mut Clob<'conn> {
self.lob
}
}
impl<'lob, 'conn: 'lob> io::Read for ClobReader<'lob, 'conn> {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let (res, piece) = self.lob.impl_.read(self.piece, self.charset, self.lob.form, buf);
self.piece = p | identifier_body |
clob.rs | //! Содержит типы для работы с большими символьными объектами.
use std::io;
use {Connection, Result, DbResult};
use types::Charset;
use ffi::native::lob::{Lob, LobImpl, LobOpenMode, CharsetForm};
use ffi::types::Piece;
use super::{Bytes, Chars, LobPrivate};
//---------------------------------------------------------... | }
/// Создает читателя данного символьного объекта. Каждый вызов метода `read` читателя читает очередную порцию данных.
/// Данные читаются из CLOB-а в указанной кодировке.
///
/// Каждый вызов `read` будет заполнять массив байтами в запрошенной кодировке. Так как стандартные методы Rust для
/// работы чита... | /// Данные читаются из CLOB-а в кодировке `UTF-8`.
#[inline]
pub fn new_reader<'lob>(&'lob mut self) -> Result<ClobReader<'lob, 'conn>> {
self.new_reader_with_charset(Charset::AL32UTF8) | random_line_split |
clob.rs | //! Содержит типы для работы с большими символьными объектами.
use std::io;
use {Connection, Result, DbResult};
use types::Charset;
use ffi::native::lob::{Lob, LobImpl, LobOpenMode, CharsetForm};
use ffi::types::Piece;
use super::{Bytes, Chars, LobPrivate};
//---------------------------------------------------------... | identifier_name | ||
lib.rs | //! See the `Bitmap` type.
/// A dense bitmap, intended to store small bitslices (<= width of usize).
pub struct Bitmap {
entries: usize,
width: usize,
// Avoid a vector here because we have our own bounds checking, and
// don't want to duplicate the length, or panic.
data: *mut u8,
}
#[inline(alw... | (&mut self) {
let p = self.data;
if p!= 0 as *mut _ {
self.data = 0 as *mut _;
let _ = unsafe { Vec::from_raw_parts(p as *mut u8, 0, self.byte_len()) };
}
}
}
impl Bitmap {
/// Create a new bitmap, returning None if the data can't be allocated or
/// if the w... | drop | identifier_name |
lib.rs | //! See the `Bitmap` type.
/// A dense bitmap, intended to store small bitslices (<= width of usize).
pub struct Bitmap {
entries: usize,
width: usize,
// Avoid a vector here because we have our own bounds checking, and
// don't want to duplicate the length, or panic.
data: *mut u8,
}
#[inline(alw... | else {
let mut bit_offset = i * self.width;
let mut in_byte_offset = bit_offset % 8;
let mut byte_offset = (bit_offset - in_byte_offset) / 8;
let mut bits_left = self.width;
let mut value: usize = 0;
while bits_left > 0 {
// ho... | {
None
} | conditional_block |
lib.rs | //! See the `Bitmap` type.
/// A dense bitmap, intended to store small bitslices (<= width of usize).
pub struct Bitmap {
entries: usize,
width: usize,
// Avoid a vector here because we have our own bounds checking, and
// don't want to duplicate the length, or panic.
data: *mut u8,
}
#[inline(alw... |
while bits_left > 0 {
let can_set = std::cmp::min(8 - in_byte_offset, bits_left);
// pull out the highest can_set bits from value
let mut to_set: usize = value >> (usize - can_set);
// move them into where they will live
to_se... | let mut bits_left = self.width; | random_line_split |
lib.rs | //! See the `Bitmap` type.
/// A dense bitmap, intended to store small bitslices (<= width of usize).
pub struct Bitmap {
entries: usize,
width: usize,
// Avoid a vector here because we have our own bounds checking, and
// don't want to duplicate the length, or panic.
data: *mut u8,
}
#[inline(alw... |
pub fn iter(&self) -> Slices {
Slices { idx: 0, bm: self }
}
/// Get the raw pointer to this Bitmap's data.
pub unsafe fn get_ptr(&self) -> *mut u8 {
self.data
}
/// Set the raw pointer to this Bitmap's data, returning the old one. It needs to be free'd
/// with `Vec`'s d... | {
// can't overflow, since creation asserts that it doesn't.
let w = self.entries * self.width;
let r = w % 8;
(w + r) / 8
} | identifier_body |
prec_climber.rs | // pest. The Elegant Parser
// Copyright (c) 2018 Dragoș Tiselice
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such no... | ///
/// # Examples
///
/// ```
/// # use pest::prec_climber::{Assoc, Operator};
/// # #[allow(non_camel_case_types)]
/// # #[allow(dead_code)]
/// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
/// # enum Rule {
/// # plus,
/// # minus
/// #... | random_line_split | |
prec_climber.rs | // pest. The Elegant Parser
// Copyright (c) 2018 Dragoș Tiselice
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such no... | }
/// List of operators and precedences, which can perform [precedence climbing][1] on infix
/// expressions contained in a [`Pairs`]. The token pairs contained in the `Pairs` should start
/// with a *primary* pair and then alternate between an *operator* and a *primary*.
///
/// [1]: https://en.wikipedia.org/wiki/Ope... |
fn assign_next<R: RuleType>(op: &mut Operator<R>, next: Operator<R>) {
if let Some(ref mut child) = op.next {
assign_next(child, next);
} else {
op.next = Some(Box::new(next));
}
}
assign_next(&mut self, rhs);
self
... | identifier_body |
prec_climber.rs | // pest. The Elegant Parser
// Copyright (c) 2018 Dragoș Tiselice
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such no... | 'i, P, F, G, T>(&self, mut pairs: P, mut primary: F, mut infix: G) -> T
where
P: Iterator<Item = Pair<'i, R>>,
F: FnMut(Pair<'i, R>) -> T,
G: FnMut(T, Pair<'i, R>, T) -> T,
{
let lhs = primary(
pairs
.next()
.expect("precedence climbing r... | limb< | identifier_name |
prec_climber.rs | // pest. The Elegant Parser
// Copyright (c) 2018 Dragoș Tiselice
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such no... | } else {
break;
}
}
lhs
}
}
|
break;
}
| conditional_block |
subscriber.rs | use super::error::{ErrorKind, Result, ResultExt};
use super::header::{decode, encode, match_field};
use super::{Message, Topic};
use crate::rosmsg::RosMsg;
use crate::util::lossy_channel::{lossy_channel, LossyReceiver, LossySender};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use crossbeam::channel::{bo... |
}
| {
let input = [7, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 4, 0, 0, 0, 11, 12, 13, 14];
let mut cursor = std::io::Cursor::new(input);
let data = package_to_vector(&mut cursor).expect(FAILED_TO_READ_WRITE_VECTOR);
assert_eq!(data, [7, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7]);
let data = package_to_vec... | identifier_body |
subscriber.rs | use super::error::{ErrorKind, Result, ResultExt};
use super::header::{decode, encode, match_field};
use super::{Message, Topic};
use crate::rosmsg::RosMsg;
use crate::util::lossy_channel::{lossy_channel, LossyReceiver, LossySender};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use crossbeam::channel::{bo... | assert_eq!(data, [4, 0, 0, 0, 11, 12, 13, 14]);
}
} | let data = package_to_vector(&mut cursor).expect(FAILED_TO_READ_WRITE_VECTOR);
assert_eq!(data, [7, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7]);
let data = package_to_vector(&mut cursor).expect(FAILED_TO_READ_WRITE_VECTOR); | random_line_split |
subscriber.rs | use super::error::{ErrorKind, Result, ResultExt};
use super::header::{decode, encode, match_field};
use super::{Message, Topic};
use crate::rosmsg::RosMsg;
use crate::util::lossy_channel::{lossy_channel, LossyReceiver, LossySender};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use crossbeam::channel::{bo... | (&self) -> Vec<String> {
self.connected_publishers.iter().cloned().collect()
}
#[allow(clippy::useless_conversion)]
pub fn connect_to<U: ToSocketAddrs>(
&mut self,
publisher: &str,
addresses: U,
) -> std::io::Result<()> {
for address in addresses.to_socket_addrs(... | publisher_uris | identifier_name |
subscriber.rs | use super::error::{ErrorKind, Result, ResultExt};
use super::header::{decode, encode, match_field};
use super::{Message, Topic};
use crate::rosmsg::RosMsg;
use crate::util::lossy_channel::{lossy_channel, LossyReceiver, LossySender};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use crossbeam::channel::{bo... |
}
});
Ok(headers)
}
fn write_request<U: std::io::Write>(
mut stream: &mut U,
caller_id: &str,
topic: &str,
msg_definition: &str,
md5sum: &str,
msg_type: &str,
) -> Result<()> {
let mut fields = HashMap::<String, String>::new();
fields.insert(String::from("message_defini... | {
// Data receiver has been destroyed after
// Subscriber destructor's kill signal
break;
} | conditional_block |
lib.rs | //! The `io_uring` library for Rust.
//!
//! The crate only provides a summary of the parameters.
//! For more detailed documentation, see manpage.
#![cfg_attr(sgx, no_std)]
#[cfg(sgx)]
extern crate sgx_types;
#[cfg(sgx)]
#[macro_use]
extern crate sgx_tstd as std;
#[cfg(sgx)]
extern crate sgx_trts;
#[cfg(sgx)]
use st... | }
#[inline]
pub fn params(&self) -> &Parameters {
&self.params
}
pub fn start_enter_syscall_thread(&self) {
sys::start_enter_syscall_thread(self.fd.as_raw_fd());
}
/// Initiate and/or complete asynchronous I/O
///
/// # Safety
///
/// This provides a ra... | #[inline]
pub fn submitter(&self) -> Submitter<'_> {
Submitter::new(&self.fd, self.params.0.flags, &self.sq) | random_line_split |
lib.rs | //! The `io_uring` library for Rust.
//!
//! The crate only provides a summary of the parameters.
//! For more detailed documentation, see manpage.
#![cfg_attr(sgx, no_std)]
#[cfg(sgx)]
extern crate sgx_types;
#[cfg(sgx)]
#[macro_use]
extern crate sgx_tstd as std;
#[cfg(sgx)]
extern crate sgx_trts;
#[cfg(sgx)]
use st... | #[cfg(feature = "unstable")]
pub fn is_feature_poll_32bits(&self) -> bool {
self.0.features & sys::IORING_FEAT_POLL_32BITS!= 0
}
pub fn sq_entries(&self) -> u32 {
self.0.sq_entries
}
pub fn cq_entries(&self) -> u32 {
self.0.cq_entries
}
}
impl AsRawFd for IoUring {
... | self.0.features & sys::IORING_FEAT_FAST_POLL != 0
}
| identifier_body |
lib.rs | //! The `io_uring` library for Rust.
//!
//! The crate only provides a summary of the parameters.
//! For more detailed documentation, see manpage.
#![cfg_attr(sgx, no_std)]
#[cfg(sgx)]
extern crate sgx_types;
#[cfg(sgx)]
#[macro_use]
extern crate sgx_tstd as std;
#[cfg(sgx)]
extern crate sgx_trts;
#[cfg(sgx)]
use st... | (&self) -> bool {
self.0.features & sys::IORING_FEAT_SINGLE_MMAP!= 0
}
/// If this flag is set, io_uring supports never dropping completion events. If a completion
/// event occurs and the CQ ring is full, the kernel stores the event internally until such a
/// time that the CQ ring has room fo... | is_feature_single_mmap | identifier_name |
lib.rs | //! The `io_uring` library for Rust.
//!
//! The crate only provides a summary of the parameters.
//! For more detailed documentation, see manpage.
#![cfg_attr(sgx, no_std)]
#[cfg(sgx)]
extern crate sgx_types;
#[cfg(sgx)]
#[macro_use]
extern crate sgx_tstd as std;
#[cfg(sgx)]
extern crate sgx_trts;
#[cfg(sgx)]
use st... | else {
let sq_mmap = Mmap::new(fd, sys::IORING_OFF_SQ_RING as _, sq_len)?;
let cq_mmap = Mmap::new(fd, sys::IORING_OFF_CQ_RING as _, cq_len)?;
let sq = SubmissionQueue::new(&sq_mmap, &sqe_mmap, p);
let cq = CompletionQueue::new(&cq_mmap, p);
... | {
let scq_mmap =
Mmap::new(fd, sys::IORING_OFF_SQ_RING as _, cmp::max(sq_len, cq_len))?;
let sq = SubmissionQueue::new(&scq_mmap, &sqe_mmap, p);
let cq = CompletionQueue::new(&scq_mmap, p);
let mm = MemoryMap {
sq_m... | conditional_block |
error.rs | /*
* Copyright (C) 2020 The Android Open Source Project
*
* 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 app... |
fn as_native_mut(&mut self) -> *mut sys::AStatus {
self.0
}
}
| {
self.0
} | identifier_body |
error.rs | /*
* Copyright (C) 2020 The Android Open Source Project
*
* 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 app... | (&self, f: &mut Formatter) -> FmtResult {
f.write_str(&self.get_description())
}
}
impl Debug for Status {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
f.write_str(&self.get_description())
}
}
impl PartialEq for Status {
fn eq(&self, other: &Status) -> bool {
let self_code =... | fmt | identifier_name |
error.rs | /*
* Copyright (C) 2020 The Android Open Source Project
*
* 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 app... | }
}
impl Debug for Status {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
f.write_str(&self.get_description())
}
}
impl PartialEq for Status {
fn eq(&self, other: &Status) -> bool {
let self_code = self.exception_code();
let other_code = other.exception_code();
match... | impl Display for Status {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
f.write_str(&self.get_description()) | random_line_split |
setup.rs | // Copyright 2020 Zachary Stewart
//
// 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... | (&self, id: I) -> Option<ShipEntry<I, D, S>> {
let grid = &self.grid;
self.ships
.get(&id)
.map(move |ship| ShipEntry { id, grid, ship })
}
/// Get the [`ShipEntryMut`] for the ship with the specified ID if such a ship exists.
pub fn get_ship_mut(&mut self, id: I) -> O... | get_ship | identifier_name |
setup.rs | // Copyright 2020 Zachary Stewart
//
// 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... | placement,
));
}
_ => {}
}
}
// Already ensured that every position is valid and not occupied.
for coord in placement.iter() {
self.grid[coord].ship = Some(self... | ));
}
Some(cell) if cell.ship.is_some() => {
return Err(PlaceError::new(
CannotPlaceReason::AlreadyOccupied, | random_line_split |
buffered.rs | the same file or network socket. It does not
/// help when reading very large amounts at once, or reading just one or a few
/// times. It also provides no advantage when reading from a source that is
/// already in memory, like a `Vec<u8>`.
///
/// When the `BufReader<R>` is dropped, the contents of its buffer will be... | self) -> &W {
self.inner.get_ref()
}
/// Gets a mutable reference to the underlying writer.
///
/// Caution must be taken when calling methods on the mutable reference
/// returned as extra writes could corrupt the output stream.
///
pub fn get_mut(&mut self) -> &mut W {
sel... | t_ref(& | identifier_name |
buffered.rs | the same file or network socket. It does not
/// help when reading very large amounts at once, or reading just one or a few
/// times. It also provides no advantage when reading from a source that is
/// already in memory, like a `Vec<u8>`.
///
/// When the `BufReader<R>` is dropped, the contents of its buffer will be... |
if total_len >= self.buf.capacity() {
self.panicked = true;
let r = self.get_mut().write_vectored(bufs);
self.panicked = false;
r
} else {
self.buf.write_vectored(bufs)
}
}
fn flush(&mut self) -> io::Result<()> {
self.... | {
self.flush_buf()?;
} | conditional_block |
buffered.rs | to the same file or network socket. It does not
/// help when reading very large amounts at once, or reading just one or a few
/// times. It also provides no advantage when reading from a source that is
/// already in memory, like a `Vec<u8>`.
///
/// When the `BufReader<R>` is dropped, the contents of its buffer will... |
impl<W: Write> Write for LineWriter<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
if self.need_flush {
self.flush()?;
}
// Find the last newline character in the buffer provided. If found then
// we're going to write all the data up to that point and then... | self.inner.into_inner().map_err(|IntoInnerError(buf, e)| {
IntoInnerError(LineWriter { inner: buf, need_flush: false }, e)
})
}
} | identifier_body |
buffered.rs | calls to the same file or network socket. It does not
/// help when reading very large amounts at once, or reading just one or a few
/// times. It also provides no advantage when reading from a source that is
/// already in memory, like a `Vec<u8>`.
///
/// When the `BufReader<R>` is dropped, the contents of its buffe... | }
impl<W: Write> LineWriter<W> {
/// Creates a new `LineWriter`.
///
pub fn new(inner: W) -> LineWriter<W> {
// Lines typically aren't that long, don't use a giant buffer
LineWriter::with_capacity(1024, inner)
}
/// Creates a new `LineWriter` with a specified capacity for the inter... | pub struct LineWriter<W: Write> {
inner: BufWriter<W>,
need_flush: bool, | random_line_split |
skim.rs | ///! The fuzzy matching algorithm used by skim
///! It focus more on path matching
///
///! # Example:
///! ```edition2018
///! use fuzzy_matcher::skim::{fuzzy_match, fuzzy_indices};
///!
///! assert_eq!(None, fuzzy_match("abc", "abx"));
///! assert!(fuzzy_match("axbycz", "abc").is_some());
///! assert!(fuzzy_match("ax... |
pub fn fuzzy_indices(choice: &str, pattern: &str) -> Option<(i64, Vec<usize>)> {
if pattern.is_empty() {
return Some((0, Vec::new()));
}
let mut picked = vec![];
let scores = build_graph(choice, pattern)?;
let last_row = &scores[scores.len() - 1];
let (mut next_col, &MatchingStatus {... | {
if pattern.is_empty() {
return Some(0);
}
let scores = build_graph(choice, pattern)?;
let last_row = &scores[scores.len() - 1];
let (_, &MatchingStatus { final_score, .. }) = last_row
.iter()
.enumerate()
.max_by_key(|&(_, x)| x.final_score)
.expect("fuzzy... | identifier_body |
skim.rs | ///! The fuzzy matching algorithm used by skim
///! It focus more on path matching
///
///! # Example:
///! ```edition2018
///! use fuzzy_matcher::skim::{fuzzy_match, fuzzy_indices};
///!
///! assert_eq!(None, fuzzy_match("abc", "abx"));
///! assert!(fuzzy_match("axbycz", "abc").is_some());
///! assert!(fuzzy_match("ax... | &[
"camel case",
"camelCase",
"camelcase",
"CamelCase",
"camel ace",
],
);
assert_order(
"Da.Te",
&["Data.Text", "Data.Text.Lazy", "Data.Aeson.Encoding.text"],
);
... | random_line_split | |
skim.rs | ///! The fuzzy matching algorithm used by skim
///! It focus more on path matching
///
///! # Example:
///! ```edition2018
///! use fuzzy_matcher::skim::{fuzzy_match, fuzzy_indices};
///!
///! assert_eq!(None, fuzzy_match("abc", "abx"));
///! assert!(fuzzy_match("axbycz", "abc").is_some());
///! assert!(fuzzy_match("ax... | else {
score += PENALTY_CASE_UNMATCHED;
}
// apply bonus for camelCases
if choice_role == CharRole::Head {
score += BONUS_CAMEL;
}
// apply bonus for matches after a separator
if choice_prev_ch_type == CharType::Separ {
score += BONUS_SEPARATOR;
}
if pat_idx =... | {
if pat_ch.is_uppercase() {
score += BONUS_UPPER_MATCH;
} else {
score += BONUS_CASE_MATCH;
}
} | conditional_block |
skim.rs | ///! The fuzzy matching algorithm used by skim
///! It focus more on path matching
///
///! # Example:
///! ```edition2018
///! use fuzzy_matcher::skim::{fuzzy_match, fuzzy_indices};
///!
///! assert_eq!(None, fuzzy_match("abc", "abx"));
///! assert!(fuzzy_match("axbycz", "abc").is_some());
///! assert!(fuzzy_match("ax... | (line: &str, pattern: &str) -> Option<String> {
let (_score, indices) = fuzzy_indices(line, pattern)?;
Some(wrap_matches(line, &indices))
}
fn assert_order(pattern: &str, choices: &[&'static str]) {
let result = filter_and_sort(pattern, choices);
if result!= choices {
... | wrap_fuzzy_match | identifier_name |
dataflows.rs | sink, description of sink)
pub sink_exports: BTreeMap<GlobalId, ComputeSinkDesc<S, T>>,
/// An optional frontier to which inputs should be advanced.
///
/// If this is set, it should override the default setting determined by
/// the upper bound of `since` frontiers contributing to the dataflow.
... | (&self) -> impl Iterator<Item = GlobalId> + '_ {
self.index_exports
.keys()
.chain(self.sink_exports.keys())
.cloned()
}
/// Identifiers of exported subscribe sinks.
pub fn subscribe_ids(&self) -> impl Iterator<Item = GlobalId> + '_ {
self.sink_exports
... | export_ids | identifier_name |
dataflows.rs | sink, description of sink)
pub sink_exports: BTreeMap<GlobalId, ComputeSinkDesc<S, T>>,
/// An optional frontier to which inputs should be advanced.
///
/// If this is set, it should override the default setting determined by
/// the upper bound of `since` frontiers contributing to the dataflow.
... |
/// Calls r and s on any sub-members of those types in self. Halts at the first error return.
pub fn visit_children<R, S, E>(&mut self, r: R, s: S) -> Result<(), E>
where
R: Fn(&mut OptimizedMirRelationExpr) -> Result<(), E>,
S: Fn(&mut MirScalarExpr) -> Result<(), E>,
{
for Bu... | {
for (source_id, (source, _monotonic)) in self.source_imports.iter() {
if source_id == id {
return source.typ.arity();
}
}
for IndexImport { desc, typ, .. } in self.index_imports.values() {
if &desc.on_id == id {
return typ.ari... | identifier_body |
dataflows.rs | sink, description of sink)
pub sink_exports: BTreeMap<GlobalId, ComputeSinkDesc<S, T>>,
/// An optional frontier to which inputs should be advanced.
///
/// If this is set, it should override the default setting determined by
/// the upper bound of `since` frontiers contributing to the dataflow.
... | /// Returns true iff `id` is already imported.
pub fn is_imported(&self, id: &GlobalId) -> bool {
self.objects_to_build.iter().any(|bd| &bd.id == id)
|| self.source_imports.keys().any(|i| i == id)
}
/// Assigns the `as_of` frontier to the supplied argument.
///
/// This meth... | random_line_split | |
rpc.rs | time::timeout;
use crate::comm::{ConnectionRegistration, RegisterWorker};
use crate::hwstats::WorkerHwStateMessage;
use crate::internal::common::resources::map::ResourceMap;
use crate::internal::common::resources::{Allocation, AllocationValue};
use crate::internal::common::WrappedRcRefCell;
use crate::internal::messag... |
pub(crate) fn process_worker_message(state: &mut WorkerState, message: ToWorkerMessage) -> bool {
match message {
ToWorkerMessage::ComputeTask(msg) => {
log::debug!("Task assigned: {}", msg.id);
let task = Task::new(msg);
state.add_task(task);
}
ToWorker... | {
let mut interval = tokio::time::interval(Duration::from_secs(1));
loop {
interval.tick().await;
let state = state_ref.get();
if !state.has_tasks() && !state.reservation {
let elapsed = state.last_task_finish_time.elapsed();
if elapsed > idle_timeout {
... | identifier_body |
rpc.rs | ::time::timeout;
use crate::comm::{ConnectionRegistration, RegisterWorker};
use crate::hwstats::WorkerHwStateMessage; | use crate::internal::common::WrappedRcRefCell;
use crate::internal::messages::worker::{
FromWorkerMessage, StealResponseMsg, TaskResourceAllocation, TaskResourceAllocationValue,
ToWorkerMessage, WorkerOverview, WorkerRegistrationResponse, WorkerStopReason,
};
use crate::internal::server::rpc::ConnectionDescript... | use crate::internal::common::resources::map::ResourceMap;
use crate::internal::common::resources::{Allocation, AllocationValue}; | random_line_split |
rpc.rs | time::timeout;
use crate::comm::{ConnectionRegistration, RegisterWorker};
use crate::hwstats::WorkerHwStateMessage;
use crate::internal::common::resources::map::ResourceMap;
use crate::internal::common::resources::{Allocation, AllocationValue};
use crate::internal::common::WrappedRcRefCell;
use crate::internal::messag... |
}
ToWorkerMessage::Stop => {
log::info!("Received stop command");
return true;
}
}
false
}
/// Runs until there are messages coming from the server.
async fn worker_message_loop(
state_ref: WorkerStateRef,
mut stream: impl Stream<Item = Result<BytesMut, ... | {
state.reset_idle_timer();
} | conditional_block |
rpc.rs | time::timeout;
use crate::comm::{ConnectionRegistration, RegisterWorker};
use crate::hwstats::WorkerHwStateMessage;
use crate::internal::common::resources::map::ResourceMap;
use crate::internal::common::resources::{Allocation, AllocationValue};
use crate::internal::common::WrappedRcRefCell;
use crate::internal::messag... | (idle_timeout: Duration, state_ref: WrappedRcRefCell<WorkerState>) {
let mut interval = tokio::time::interval(Duration::from_secs(1));
loop {
interval.tick().await;
let state = state_ref.get();
if!state.has_tasks() &&!state.reservation {
let elapsed = state.last_task_finish... | idle_timeout_process | identifier_name |
srt.rs | Salt |
/// | ... |
/// +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+
/// | Wrap |
/// | ... | (&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("KeyingMaterialMessage")
.field("pt", &self.pt)
.field("key_flags", &self.key_flags)
.field("keki", &self.keki)
.field("cipher", &self.cipher)
.field("auth", &self.auth)
.finish()
... | fmt | identifier_name |
srt.rs | 8_error()))
}
fn string_to_le_bytes(str: &str, into: &mut impl BufMut) {
let mut chunks = str.as_bytes().chunks_exact(4);
while let Some(&[a, b, c, d]) = chunks.next() {
into.put(&[d, c, b, a][..]);
}
// add padding bytes for the final word if needed
match *chunks.remainder() {
[a... | {
let salt = b"\x00\x00\x00\x00\x00\x00\x00\x00\x85\x2c\x3c\xcd\x02\x65\x1a\x22";
let wrapped = b"U\x06\xe9\xfd\xdfd\xf1'nr\xf4\xe9f\x81#(\xb7\xb5D\x19{\x9b\xcdx";
let km = KeyingMaterialMessage {
pt: PacketType::KeyingMaterial,
key_flags: KeyFlags::EVEN,
kek... | identifier_body | |
srt.rs | Salt |
/// | ... |
/// +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+
/// | Wrap |
/// | ... |
/// from https://github.com/Haivision/srt/blob/2ef4ef003c2006df1458de6d47fbe3d2338edf69/haicrypt/hcrypt_msg.h#L121-L124
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum CipherType {
None = 0,
Ecb = 1,
Ctr = 2,
Cbc = 3,
}
/// The SRT handshake object
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pu... | }
} | random_line_split |
mod.rs | //! # Day 19: Go With The Flow
//!
//! With the Elves well on their way constructing the North Pole base, you turn
//! your attention back to understanding the inner workings of programming the
//! device.
//!
//! You can't help but notice that the device's opcodes don't contain any flow
//! control like jump instructi... | (reg: &mut Register) -> Addr {
if reg[4] % reg[5] == 0 {
reg[0] = reg[5] + reg[0];
}
reg[2] = reg[4];
reg[1] = 0;
12
}
#[cfg(test)]
mod tests;
| optimized | identifier_name |
mod.rs | //! # Day 19: Go With The Flow
//!
//! With the Elves well on their way constructing the North Pole base, you turn
//! your attention back to understanding the inner workings of programming the
//! device.
//!
//! You can't help but notice that the device's opcodes don't contain any flow
//! control like jump instructi... | //! bound to register 0 in this program. This is not an instruction, and so
//! the value of the instruction pointer does not change during the processing
//! of this line.
//! * The instruction pointer contains 0, and so the first instruction is
//! executed (seti 5 0 1). It updates register 0 to the current i... | //! In detail, when running this program, the following events occur:
//!
//! * The first line (#ip 0) indicates that the instruction pointer should be | random_line_split |
mod.rs | //! # Day 19: Go With The Flow
//!
//! With the Elves well on their way constructing the North Pole base, you turn
//! your attention back to understanding the inner workings of programming the
//! device.
//!
//! You can't help but notice that the device's opcodes don't contain any flow
//! control like jump instructi... | ,
}
}
#[inline]
fn _trace(ip: Addr, Instruction { opcode, a, b, c }: Instruction, reg: &Register) {
match opcode {
AddR => println!("{:02}: {} {} {} {} : {} ", ip, opcode, a, b, c, reg),
AddI => println!("{:02}: {} {} {} {} : {} ", ip, opcode, a, b, c, reg),
MulR => println!("{:02}: {} ... | { 0 } | conditional_block |
ym.rs | use core::time::Duration;
use core::num::NonZeroU32;
use core::fmt;
use core::ops::Range;
use chrono::NaiveDateTime;
pub mod flags;
pub mod effects;
mod parse;
mod player;
use flags::*;
use effects::*;
pub const MAX_DD_SAMPLES: usize = 32;
pub const MFP_TIMER_FREQUENCY: u32 = 2_457_600;
const DEFAULT_CHIPSET_FREQUE... |
/// Returns the song duration.
pub fn song_duration(&self) -> Duration {
let seconds = self.frames.len() as f64 / self.frame_frequency as f64;
Duration::from_secs_f64(seconds)
}
/// Returns the AY/YM chipset clock frequency.
#[inline]
pub fn clock_frequency(&self) -> f32 {
... | {
self.chipset_frequency = chipset_frequency;
self.frame_frequency = frame_frequency;
self
} | identifier_body |
ym.rs | use core::time::Duration;
use core::num::NonZeroU32;
use core::fmt;
use core::ops::Range;
use chrono::NaiveDateTime;
pub mod flags;
pub mod effects;
mod parse;
mod player;
use flags::*;
use effects::*;
pub const MAX_DD_SAMPLES: usize = 32;
pub const MFP_TIMER_FREQUENCY: u32 = 2_457_600;
const DEFAULT_CHIPSET_FREQUE... | (&self) -> Duration {
let seconds = self.frames.len() as f64 / self.frame_frequency as f64;
Duration::from_secs_f64(seconds)
}
/// Returns the AY/YM chipset clock frequency.
#[inline]
pub fn clock_frequency(&self) -> f32 {
self.chipset_frequency as f32
}
/// Returns the... | song_duration | identifier_name |
ym.rs | use core::time::Duration;
use core::num::NonZeroU32;
use core::fmt;
use core::ops::Range;
use chrono::NaiveDateTime;
pub mod flags;
pub mod effects;
mod parse;
mod player;
use flags::*;
use effects::*;
pub const MAX_DD_SAMPLES: usize = 32;
pub const MFP_TIMER_FREQUENCY: u32 = 2_457_600;
const DEFAULT_CHIPSET_FREQUE... | /// uses one of the 40 predefined samples.
///
/// * The effect starts when the highest bit (7) of the `Volume voice C` register (10) is 1.
/// * The sample number is taken from the lowest 7 bits of the `Volume voice C` register (10).
/// * The effect frequency is calculated by `(2457600 / 4) / X`, where `X` is the uns... | random_line_split | |
coprocessor.rs | // Copyright 2016 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | Datum::I64(h)
};
let data = box_try!(datum::encode_value(&datums));
let handle_data = box_try!(datum::encode_value(&[handle]));
let mut row = Row::new();
row.set_handle(handle_data);
row.set_data(data);
rows.push(row);
seek_key = prefix_next(&k... | {
let mut rows = vec![];
let mut seek_key = r.take_start();
loop {
trace!("seek {:?}", seek_key);
let mut nk = try!(snap.scan(Key::from_raw(seek_key.clone()), 1));
if nk.is_empty() {
debug!("no more data to scan");
return Ok(rows);
}
let (key, ... | identifier_body |
coprocessor.rs | // Copyright 2016 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | } else {
let h = box_try!((&*value).read_i64::<BigEndian>());
Datum::I64(h)
};
let data = box_try!(datum::encode_value(&datums));
let handle_data = box_try!(datum::encode_value(&[handle]));
let mut row = Row::new();
row.set_handle(handle_data);
... | return Ok(rows);
}
let mut datums = box_try!(table::decode_index_key(&key));
let handle = if datums.len() > info.get_columns().len() {
datums.pop().unwrap() | random_line_split |
coprocessor.rs | // Copyright 2016 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | (req: Request,
ch: SendCh,
token: Token,
msg_id: u64,
end_point: &SnapshotEndPoint) {
let cb = box move |r| {
let mut resp_msg = Message::new();
resp_msg.set_msg_type(MessageType::CopResp);
resp_msg.set_cop_resp(r);
... | handle_request | identifier_name |
server.rs | // Copyright 2021 The Grin 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 agree... | (&self) -> Result<(), Error> {
let head = self.chain.head()?;
self.p2p.peers.check_all(head.total_difficulty, head.height);
Ok(())
}
/// Number of peers
pub fn peer_count(&self) -> u32 {
self.p2p
.peers
.iter()
.connected()
.count()
.try_into()
.unwrap()
}
/// Start a minimal "stratum" ... | ping_peers | identifier_name |
server.rs | // Copyright 2021 The Grin 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 agree... |
/// The head of the block header chain
pub fn header_head(&self) -> Result<chain::Tip, Error> {
self.chain.header_head().map_err(|e| e.into())
}
/// The p2p layer protocol version for this node.
pub fn protocol_version() -> ProtocolVersion {
ProtocolVersion::local()
}
/// Returns a set of stats about thi... | {
self.chain.head().map_err(|e| e.into())
} | identifier_body |
server.rs | // Copyright 2021 The Grin 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 agree... | };
let disk_usage_bytes = WalkDir::new(&self.config.db_root)
.min_depth(1)
.max_depth(3)
.into_iter()
.filter_map(|entry| entry.ok())
.filter_map(|entry| entry.metadata().ok())
.filter(|metadata| metadata.is_file())
.fold(0, |acc, m| acc + m.len());
let disk_usage_gb = format!("{:.*}", 3, (... | let header_stats = ChainStats {
latest_timestamp: header.timestamp,
height: header.height,
last_block_h: header.hash(),
total_difficulty: header.total_difficulty(), | random_line_split |
server.rs | // Copyright 2021 The Grin 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 agree... |
},
p2p::Seeding::DNSSeed => seed::default_dns_seeds(),
_ => unreachable!(),
};
connect_thread = Some(seed::connect_and_monitor(
p2p_server.clone(),
seed_list,
config.p2p_config.clone(),
stop_state.clone(),
)?);
}
// Defaults to None (optional) in config file.
// This transl... | {
return Err(Error::Configuration(
"Seeds must be configured for seeding type List".to_owned(),
));
} | conditional_block |
hkdf_test.rs | // Copyright 2020 The Tink-Rust Authors
//
// 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... | &[0xaf, 0xfe, 0xc0, 0xff, 0xee]
)
.is_ok(),
"Expected HkdfPrf::new to work with salt"
);
}
#[test]
fn test_hkdf_prf_output_length() {
let testdata = hashmap! {
HashType::Sha1 => 20,
HashType::Sha256 => 32,
HashType::Sha512 => 64,
};
for (hash,... | {
assert!(
HkdfPrf::new(
HashType::Sha256,
&[
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
0x0f, 0x10
],
&[]
)
.is_ok(),
"Expected HkdfPrf::new to work empty salt"
... | identifier_body |
hkdf_test.rs | // Copyright 2020 The Tink-Rust Authors
//
// 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... | &[]
)
.is_ok(),
"Expected HkdfPrf::new to work with SHA512"
);
assert!(
HkdfPrf::new(
HashType::Sha1,
&[
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
0x0f, 0x10
... | 0x0f, 0x10
], | random_line_split |
hkdf_test.rs | // Copyright 2020 The Tink-Rust Authors
//
// 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 {
assert_ne!(
res, tc.okm,
"Computed HKDF {:?} PRF and invalid expected for test case {} ({}) match",
hash, tc.case.case_id, tc.case.comment
);
}
}
}
}
}
#[test]... | {
assert_eq!(
res, tc.okm,
"Computed HKDF {:?} PRF and expected for test case {} ({}) do not match",
hash, tc.case.case_id, tc.case.comment
);
} | conditional_block |
hkdf_test.rs | // Copyright 2020 The Tink-Rust Authors
//
// 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... | () {
for hash in &[HashType::Sha1, HashType::Sha256, HashType::Sha512] {
let hash_name = format!("{:?}", hash);
let filename = format!("testvectors/hkdf_{}_test.json", hash_name.to_lowercase());
println!("wycheproof file '{}' hash {}", filename, hash_name);
let bytes = tink_tests::wy... | test_hkdf_prf_wycheproof_cases | identifier_name |
config.rs | //! Tendermint configuration file types (with serde parsers/serializers)
//!
//! This module contains types which correspond to the following config files:
//!
//! - `config.toml`: `config::TendermintConfig`
//! - `node_key.rs`: `config::node_key::NodeKey`
//! - `priv_validator_key.rs`: `config::priv_validator_key::Pri... | (String);
impl AsRef<str> for CorsMethod {
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
impl fmt::Display for CorsMethod {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", &self.0)
}
}
/// HTTP headers allowed to be sent via CORS to the RPC API
// TODO(tarc... | CorsMethod | identifier_name |
config.rs | //! Tendermint configuration file types (with serde parsers/serializers)
//!
//! This module contains types which correspond to the following config files:
//!
//! - `config.toml`: `config::TendermintConfig`
//! - `node_key.rs`: `config::node_key::NodeKey`
//! - `priv_validator_key.rs`: `config::priv_validator_key::Pri... |
let key = parts[0].to_owned();
let value = parts[1].to_owned();
if levels.insert(key, value).is_some() {
return Err(err!(
ErrorKind::Parse,
"duplicate log level setting for: {}",
level
));
... | {
return Err(err!(ErrorKind::Parse, "error parsing log level: {}", level));
} | conditional_block |
config.rs | //! Tendermint configuration file types (with serde parsers/serializers)
//!
//! This module contains types which correspond to the following config files:
//!
//! - `config.toml`: `config::TendermintConfig`
//! - `node_key.rs`: `config::node_key::NodeKey`
//! - `priv_validator_key.rs`: `config::priv_validator_key::Pri... | }
/// Mechanism to connect to the ABCI application: socket | grpc
#[derive(Copy, Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum AbciMode {
/// Socket
#[serde(rename = "socket")]
Socket,
/// GRPC
#[serde(rename = "grpc")]
Grpc,
}
/// Tendermint `config.toml` file's `[rpc]... | Plain,
/// JSON
#[serde(rename = "json")]
Json, | random_line_split |
instream.rs | extern crate libsoundio_sys as raw;
use super::error::*;
use super::format::*;
use super::sample::*;
use super::util::*;
use std::marker::PhantomData;
use std::os::raw::{c_double, c_int};
use std::ptr;
use std::slice;
/// This is called when an instream has been read. The `InStreamUserData` struct is obtained
/// fr... | }
// TODO: Can pause() be called from the read callback?
/// If the underlying backend and device support pausing, this pauses the
/// stream. The `write_callback()` may be called a few more times if
/// the buffer is not full.
///
/// Pausing might put the hardware into a low power state ... | } | random_line_split |
instream.rs | extern crate libsoundio_sys as raw;
use super::error::*;
use super::format::*;
use super::sample::*;
use super::util::*;
use std::marker::PhantomData;
use std::os::raw::{c_double, c_int};
use std::ptr;
use std::slice;
/// This is called when an instream has been read. The `InStreamUserData` struct is obtained
/// fr... |
/// Get latency in seconds due to software only, not including hardware.
pub fn software_latency(&self) -> f64 {
unsafe { (*self.instream).software_latency as _ }
}
/// Return the number of channels in this stream. Guaranteed to be at least 1.
pub fn channel_count(&self) -> usize {
... | {
assert!(self.read_started);
self.frame_count
} | identifier_body |
instream.rs | extern crate libsoundio_sys as raw;
use super::error::*;
use super::format::*;
use super::sample::*;
use super::util::*;
use std::marker::PhantomData;
use std::os::raw::{c_double, c_int};
use std::ptr;
use std::slice;
/// This is called when an instream has been read. The `InStreamUserData` struct is obtained
/// fr... | (&mut self) -> Result<()> {
match unsafe { raw::soundio_instream_start(self.userdata.instream) } {
0 => Ok(()),
x => Err(x.into()),
}
}
// TODO: Can pause() be called from the read callback?
/// If the underlying backend and device support pausing, this pauses the
... | start | identifier_name |
mod.rs | /// Toy x86_64 JIT
use libc;
use std::alloc::{alloc, dealloc, Layout};
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::ffi::c_void;
use std::io::{Read, Write};
use std::mem::transmute;
use std::ptr::write_bytes;
use std::slice;
mod x86;
use crate::ir::Instruction;
const PAGE_SIZE: usize = 4096;
... | (instructions: &[Instruction]) -> Program {
// we'll emit something that respects x86_64 system-v:
// rdi (1st parameter): pointer to cell array
// rsi (2nd parameter): pointer to output function
// rdx (3rd parameter): pointer to WriteWrapper
// rcx (4th parameter): pointer to input function
//... | transform | identifier_name |
mod.rs | /// Toy x86_64 JIT
use libc;
use std::alloc::{alloc, dealloc, Layout};
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::ffi::c_void;
use std::io::{Read, Write};
use std::mem::transmute;
use std::ptr::write_bytes;
use std::slice;
mod x86;
use crate::ir::Instruction;
const PAGE_SIZE: usize = 4096;
... |
pub fn as_mut_slice(&mut self) -> &mut [u8] {
unsafe { slice::from_raw_parts_mut(self.program.contents, self.program.size) }
}
pub fn lock(self) -> Program {
unsafe {
libc::mprotect(
self.program.contents as *mut libc::c_void,
self.program.size,... | {
unsafe { slice::from_raw_parts(self.program.contents, self.program.size) }
} | identifier_body |
mod.rs | /// Toy x86_64 JIT
use libc;
use std::alloc::{alloc, dealloc, Layout};
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::ffi::c_void;
use std::io::{Read, Write};
use std::mem::transmute;
use std::ptr::write_bytes;
use std::slice;
mod x86;
use crate::ir::Instruction;
const PAGE_SIZE: usize = 4096;
... | unsafe { slice::from_raw_parts_mut(self.program.contents, self.program.size) }
}
pub fn lock(self) -> Program {
unsafe {
libc::mprotect(
self.program.contents as *mut libc::c_void,
self.program.size,
libc::PROT_NONE,
);
... | }
pub fn as_mut_slice(&mut self) -> &mut [u8] { | random_line_split |
file_system.rs | // Copyright 2021 The Fuchsia 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 once_cell::sync::OnceCell;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std:... |
Ok(stat)
}
pub fn did_create_dir_entry(&self, entry: &DirEntryHandle) {
if self.permanent_entries {
self.entries.lock().insert(Arc::as_ptr(entry) as usize, entry.clone());
}
}
pub fn will_destroy_dir_entry(&self, entry: &DirEntryHandle) {
if self.permanent_... | {
stat.f_frsize = stat.f_bsize as i64;
} | conditional_block |
file_system.rs | // Copyright 2021 The Fuchsia 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 once_cell::sync::OnceCell;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std:... | /// Returns `ENOSYS` if the `FileSystemOps` don't implement `stat`.
pub fn statfs(&self) -> Result<statfs, Errno> {
let mut stat = self.ops.statfs(self)?;
if stat.f_frsize == 0 {
stat.f_frsize = stat.f_bsize as i64;
}
Ok(stat)
}
pub fn did_create_dir_entry(&s... | ///
/// Each `FileSystemOps` impl is expected to override this to return the specific statfs for
/// the filesystem.
/// | random_line_split |
file_system.rs | // Copyright 2021 The Fuchsia 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 once_cell::sync::OnceCell;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std:... | (&self) -> &DirEntryHandle {
self.root.get().unwrap()
}
/// Get or create an FsNode for this file system.
///
/// If inode_num is Some, then this function checks the node cache to
/// determine whether this node is already open. If so, the function
/// returns the existing FsNode. If no... | root | identifier_name |
file_system.rs | // Copyright 2021 The Fuchsia 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 once_cell::sync::OnceCell;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std:... |
fn new_internal(
kernel: &Kernel,
ops: impl FileSystemOps,
permanent_entries: bool,
) -> FileSystemHandle {
Arc::new(FileSystem {
root: OnceCell::new(),
next_inode: AtomicU64::new(1),
ops: Box::new(ops),
dev_id: kernel.device_regi... | {
if root.inode_num == 0 {
root.inode_num = self.next_inode_num();
}
root.set_fs(self);
let root_node = Arc::new(root);
self.nodes.lock().insert(root_node.inode_num, Arc::downgrade(&root_node));
let root = DirEntry::new(root_node, None, FsString::new());
... | identifier_body |
arena.rs | use core::convert::TryFrom;
use core::mem::{self, ManuallyDrop};
use core::ops::Deref;
use core::pin::Pin;
use pin_project::pin_project;
use crate::list::*;
use crate::lock::{Spinlock, SpinlockGuard};
use crate::pinned_array::IterPinMut;
use crate::rc_cell::{RcCell, Ref, RefMut};
/// A homogeneous memory allocator, ... |
}
impl<T, const CAPACITY: usize> MruArena<T, CAPACITY> {
// TODO(https://github.com/kaist-cp/rv6/issues/371): unsafe...
pub const fn new(entries: [MruEntry<T>; CAPACITY]) -> Self {
Self {
entries,
list: unsafe { List::new() },
}
}
pub fn init(self: Pin<&mut Sel... | {
(list_entry as *const _ as usize - Self::LIST_ENTRY_OFFSET) as *const Self
} | identifier_body |
arena.rs | use core::convert::TryFrom;
use core::mem::{self, ManuallyDrop};
use core::ops::Deref;
use core::pin::Pin;
use pin_project::pin_project;
use crate::list::*;
use crate::lock::{Spinlock, SpinlockGuard};
use crate::pinned_array::IterPinMut;
use crate::rc_cell::{RcCell, Ref, RefMut};
/// A homogeneous memory allocator, ... |
}
}
empty.map(|cell_raw| {
// SAFETY: `cell` is not referenced or borrowed. Also, it is already pinned.
let mut cell = unsafe { Pin::new_unchecked(&mut *cell_raw) };
n(cell.as_mut().get_pin_mut().unwrap().get_mut());
cell.borrow()
})
... | {
return Some(r);
} | conditional_block |
arena.rs | use core::convert::TryFrom;
use core::mem::{self, ManuallyDrop};
use core::ops::Deref;
use core::pin::Pin;
use pin_project::pin_project;
use crate::list::*;
use crate::lock::{Spinlock, SpinlockGuard};
use crate::pinned_array::IterPinMut;
use crate::rc_cell::{RcCell, Ref, RefMut};
/// A homogeneous memory allocator, ... | <F: FnOnce(&mut Self::Data)>(&self, f: F) -> Option<Rc<Self>> {
let inner = self.alloc_handle(f)?;
// SAFETY: `inner` was allocated from `self`.
Some(unsafe { Rc::from_unchecked(self, inner) })
}
/// Duplicate a given handle, and increase the reference count.
///
/// # Safety
... | alloc | identifier_name |
arena.rs | use core::convert::TryFrom;
use core::mem::{self, ManuallyDrop};
use core::ops::Deref;
use core::pin::Pin;
use pin_project::pin_project;
use crate::list::*;
use crate::lock::{Spinlock, SpinlockGuard};
use crate::pinned_array::IterPinMut;
use crate::rc_cell::{RcCell, Ref, RefMut};
/// A homogeneous memory allocator, ... |
impl<T> MruEntry<T> {
// TODO(https://github.com/kaist-cp/rv6/issues/369)
// A workarond for https://github.com/Gilnaa/memoffset/issues/49.
// Assumes `list_entry` is located at the beginning of `MruEntry`
// and `data` is located at `mem::size_of::<ListEntry>()`.
const DATA_OFFSET: usize = mem::si... | {
guard.reacquire_after(f)
}
} | random_line_split |
driver.rs | use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::fs;
use catt_core::util::always_lock;
use catt_core::binding::Binding;
use catt_core::binding::Notification;
use catt_core::value::Value;
use catt_core::item::Item as CItem;
use openzwave as ozw;
use openzwave::manager::Manager;
use openzw... |
}
// The following should be removed, once we have all of the devices captured using the above
let default_devices = ["/dev/cu.usbserial", // MacOS X (presumably)
"/dev/cu.SLAB_USBtoUART", // MacOS X (Aeotech Z-Stick S2)
"/dev/cu.u... | {
error!("[OpenzwaveStateful] {:04x}:{:04x} {}",
info.vid,
info.pid,
port.device.display());
} | conditional_block |
driver.rs | use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::fs;
use catt_core::util::always_lock;
use catt_core::binding::Binding;
use catt_core::binding::Notification;
use catt_core::value::Value;
use catt_core::item::Item as CItem;
use openzwave as ozw;
use openzwave::manager::Manager;
use openzw... | (handle: &Handle, cfg: &Config) -> Result<(ZWave, Receiver<Notification<Item>>)> {
let cfg = cfg.clone();
let mut manager = {
let config_path = match cfg.sys_config {
Some(ref path) => path.as_ref(),
None => "/etc/openzwave",
};
let u... | new | identifier_name |
driver.rs | use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::fs;
use catt_core::util::always_lock;
use catt_core::binding::Binding;
use catt_core::binding::Notification;
use catt_core::value::Value;
use catt_core::item::Item as CItem;
use openzwave as ozw;
use openzwave::manager::Manager;
use openzw... |
}
impl Binding for ZWave {
type Config = Config;
type Error = Error;
type Item = Item;
fn new(handle: &Handle, cfg: &Self::Config) -> Result<(Self, Receiver<Notification<Item>>)> {
ZWave::new(handle, cfg)
}
fn get_value(&self, name: &str) -> Option<Item> {
always_lock(self.it... | {
always_lock(self.ozw_manager.lock())
} | identifier_body |
driver.rs | use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::fs;
use catt_core::util::always_lock;
use catt_core::binding::Binding;
use catt_core::binding::Notification;
use catt_core::value::Value;
use catt_core::item::Item as CItem;
use openzwave as ozw;
use openzwave::manager::Manager;
use openzw... | debug!("unknown controller state: {}",
zwave_notification.get_event().unwrap());
return;
}
};
match state {
ControllerState::Completed => {
let ... | Some(s) => s,
None => { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.