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 |
|---|---|---|---|---|
socket.rs | kernel
/// let n_sent = socket.send_to(&pkt[..], &kernel_addr, 0).unwrap();
/// assert_eq!(n_sent, pkt.len());
/// // buffer for receiving the response
/// let mut buf = vec![0; 4096];
/// loop {
/// // receive a datagram
/// let (n_received, sender_addr) = socket.recv_from(&mut &mut buf[..], 0).unwrap();
/// ... | (&self, non_blocking: bool) -> Result<()> {
let mut non_blocking = non_blocking as libc::c_int;
let res = unsafe { libc::ioctl(self.0, libc::FIONBIO, &mut non_blocking) };
if res < 0 {
return Err(Error::last_os_error());
}
Ok(())
}
/// Connect the socket to t... | set_non_blocking | identifier_name |
socket.rs | the kernel
/// let n_sent = socket.send_to(&pkt[..], &kernel_addr, 0).unwrap();
/// assert_eq!(n_sent, pkt.len());
/// // buffer for receiving the response
/// let mut buf = vec![0; 4096];
/// loop {
/// // receive a datagram
/// let (n_received, sender_addr) = socket.recv_from(&mut &mut buf[..], 0).unwrap();
... | // a pointer to it.
let addrlen_ptr = &mut addrlen as *mut usize as *mut libc::socklen_t;
let chunk = buf.chunk_mut();
// Cast the *mut u8 into *mut void.
// This is equivalent to casting a *char into *void
// ... | // also a sockaddr_in, a sockaddr_in6, or even the generic sockaddr_storage that can store
// any address.
let mut addrlen = mem::size_of_val(&addr);
// recvfrom does not take the address length by value (see [thread]), so we need to create | random_line_split |
socket.rs | kernel
/// let n_sent = socket.send_to(&pkt[..], &kernel_addr, 0).unwrap();
/// assert_eq!(n_sent, pkt.len());
/// // buffer for receiving the response
/// let mut buf = vec![0; 4096];
/// loop {
/// // receive a datagram
/// let (n_received, sender_addr) = socket.recv_from(&mut &mut buf[..], 0).unwrap();
/// ... | // almost never returns EINPROGRESS and so for now, we just return whatever libc::connect
// returns. If it returns EINPROGRESS, the caller will have to handle the error themself
//
// Refs:
//
// - https://stackoverflow.com/a/14046386/1836144
// - https://lists.i... | {
// FIXME:
//
// Event though for SOCK_DGRAM sockets there's no IO, if our socket is non-blocking,
// connect() might return EINPROGRESS. In theory, the right way to treat EINPROGRESS would
// be to ignore the error, and let the user poll the socket to check when it becomes
... | identifier_body |
socket.rs | kernel
/// let n_sent = socket.send_to(&pkt[..], &kernel_addr, 0).unwrap();
/// assert_eq!(n_sent, pkt.len());
/// // buffer for receiving the response
/// let mut buf = vec![0; 4096];
/// loop {
/// // receive a datagram
/// let (n_received, sender_addr) = socket.recv_from(&mut &mut buf[..], 0).unwrap();
/// ... | else { 0 };
setsockopt(self.0, libc::SOL_NETLINK, libc::NETLINK_NO_ENOBUFS, value)
}
pub fn get_no_enobufs(&self) -> Result<bool> {
let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_NO_ENOBUFS)?;
Ok(res == 1)
}
/// `NETLINK_LISTEN_ALL_NSID` (since Li... | { 1 } | conditional_block |
printer.rs | format_options: FormatOptions,
}
impl Printer {
pub fn new(
pretty: Pretty,
theme: Option<Theme>,
stream: bool,
buffer: Buffer,
format_options: FormatOptions,
) -> Self {
let theme = theme.unwrap_or(Theme::Auto);
Printer {
indent_json: pre... |
pub fn print_response_body(
&mut self,
response: &mut Response,
encoding: Option<&'static Encoding>,
mime: Option<&str>,
) -> anyhow::Result<()> {
let starting_time = Instant::now();
let url = response.url().clone();
let content_type =
mime.m... | {
let content_type = get_content_type(request.headers());
if let Some(body) = request.body_mut() {
let body = body.buffer()?;
if body.contains(&b'\0') {
self.buffer.print(BINARY_SUPPRESSOR)?;
} else {
self.print_body_text(content_type, ... | identifier_body |
printer.rs |
if!self.indent_json {
// We don't have to do anything specialized, so fall back to the generic version
return self.print_syntax_text(text, "json");
}
if check_valid &&!valid_json(text) {
// JSONXF may mess up the text, e.g. by removing whitespace
... | {
None
} | conditional_block | |
printer.rs | format_options: FormatOptions,
}
impl Printer {
pub fn new(
pretty: Pretty,
theme: Option<Theme>,
stream: bool,
buffer: Buffer,
format_options: FormatOptions,
) -> Self {
let theme = theme.unwrap_or(Theme::Auto);
Printer {
indent_json: pre... | (&self, headers: &HeaderMap, version: Version) -> String {
let as_titlecase = match version {
Version::HTTP_09 | Version::HTTP_10 | Version::HTTP_11 => true,
Version::HTTP_2 | Version::HTTP_3 => false,
_ => false,
};
let mut headers: Vec<(&HeaderName, &HeaderV... | headers_to_string | identifier_name |
printer.rs |
format_options: FormatOptions,
}
impl Printer {
pub fn new(
pretty: Pretty,
theme: Option<Theme>,
stream: bool,
buffer: Buffer,
format_options: FormatOptions,
) -> Self {
let theme = theme.unwrap_or(Theme::Auto);
Printer {
indent_json: p... | self.buffer.print("\n")?;
}
Err(err) if err.kind() == io::ErrorKind::InvalidData => {
self.buffer.print(BINARY_SUPPRESSOR)?;
}
Err(err) => return Err(err.into()),
}
} else {
let mut bu... | Ok(_) => { | random_line_split |
reading.rs | use crate::sector::{
sector_record_chunks_size, sector_size, RecordMetadata, SectorContentsMap,
SectorContentsMapFromBytesError, SectorMetadataChecksummed,
};
use parity_scale_codec::Decode;
use rayon::prelude::*;
use std::mem::ManuallyDrop;
use std::simd::Simd;
use subspace_core_primitives::crypto::{blake3_has... |
Ok(record_chunks)
}
/// Read metadata (commitment and witness) for record
pub(crate) fn read_record_metadata(
piece_offset: PieceOffset,
pieces_in_sector: u16,
sector: &[u8],
) -> Result<RecordMetadata, ReadingError> {
if sector.len()!= sector_size(pieces_in_sector) {
return Err(ReadingEr... | {
return Err(ReadingError::WrongRecordSizeAfterDecoding {
expected: Record::NUM_CHUNKS,
actual: record_chunks.len(),
});
} | conditional_block |
reading.rs | use crate::sector::{
sector_record_chunks_size, sector_size, RecordMetadata, SectorContentsMap,
SectorContentsMapFromBytesError, SectorMetadataChecksummed,
};
use parity_scale_codec::Decode;
use rayon::prelude::*;
use std::mem::ManuallyDrop;
use std::simd::Simd;
use subspace_core_primitives::crypto::{blake3_has... | ReadingError::InvalidChunk {
s_bucket,
encoded_chunk_used,
chunk_location,
error,
}
})?);
Ok::<_, ReadingError>(())
},
)?;
let... | );
}
maybe_record_chunk.replace(Scalar::try_from(record_chunk).map_err(|error| { | random_line_split |
reading.rs | use crate::sector::{
sector_record_chunks_size, sector_size, RecordMetadata, SectorContentsMap,
SectorContentsMapFromBytesError, SectorMetadataChecksummed,
};
use parity_scale_codec::Decode;
use rayon::prelude::*;
use std::mem::ManuallyDrop;
use std::simd::Simd;
use subspace_core_primitives::crypto::{blake3_has... | <PosTable>(
piece_offset: PieceOffset,
sector_id: &SectorId,
sector_metadata: &SectorMetadataChecksummed,
sector: &[u8],
erasure_coding: &ErasureCoding,
table_generator: &mut PosTable::Generator,
) -> Result<Piece, ReadingError>
where
PosTable: Table,
{
let pieces_in_sector = sector_meta... | read_piece | identifier_name |
reading.rs | use crate::sector::{
sector_record_chunks_size, sector_size, RecordMetadata, SectorContentsMap,
SectorContentsMapFromBytesError, SectorMetadataChecksummed,
};
use parity_scale_codec::Decode;
use rayon::prelude::*;
use std::mem::ManuallyDrop;
use std::simd::Simd;
use subspace_core_primitives::crypto::{blake3_has... |
/// Read metadata (commitment and witness) for record
pub(crate) fn read_record_metadata(
piece_offset: PieceOffset,
pieces_in_sector: u16,
sector: &[u8],
) -> Result<RecordMetadata, ReadingError> {
if sector.len()!= sector_size(pieces_in_sector) {
return Err(ReadingError::WrongSectorSize {
... | {
// Restore source record scalars
let record_chunks = erasure_coding
.recover_source(sector_record_chunks)
.map_err(|error| ReadingError::FailedToErasureDecodeRecord {
piece_offset,
error,
})?;
// Required for safety invariant below
if record_chunks.len(... | identifier_body |
graph.rs | use cairo;
use gtk::{self, BoxExt, ContainerExt, DrawingArea, ScrolledWindowExt, StateFlags, WidgetExt};
use std::cell::RefCell;
use gdk::{self, WindowExt};
use std::rc::Rc;
use std::time::Instant;
use color::Color;
use utils::RotateVec;
const LEFT_WIDTH: f64 = 31.;
pub struct Graph {
elapsed: Instant,
colo... | (&mut self, d: RotateVec<f64>, s: &str, override_color: Option<usize>) {
let c = if let Some(over) = override_color {
Color::generate(over)
} else {
Color::generate(self.data.len() + 11)
};
let l = gtk::Label::new(Some(s));
l.override_color(StateFlags::fro... | push | identifier_name |
graph.rs | use cairo;
use gtk::{self, BoxExt, ContainerExt, DrawingArea, ScrolledWindowExt, StateFlags, WidgetExt};
use std::cell::RefCell;
use gdk::{self, WindowExt};
use std::rc::Rc;
use std::time::Instant;
use color::Color;
use utils::RotateVec;
const LEFT_WIDTH: f64 = 31.;
pub struct Graph {
elapsed: Instant,
colo... | pub fn invalidate(&self) {
if let Some(t_win) = self.area.get_window() {
let (x, y) = self.area.translate_coordinates(&self.area, 0, 0)
.expect("translate_coordinates failed");
let rect = gdk::Rectangle { x: x, y: y,
width: self.area.g... | }
| random_line_split |
graph.rs | use cairo;
use gtk::{self, BoxExt, ContainerExt, DrawingArea, ScrolledWindowExt, StateFlags, WidgetExt};
use std::cell::RefCell;
use gdk::{self, WindowExt};
use std::rc::Rc;
use std::time::Instant;
use color::Color;
use utils::RotateVec;
const LEFT_WIDTH: f64 = 31.;
pub struct Graph {
elapsed: Instant,
colo... | }
}
}
| {
let s = self.clone();
if let Some(parent) = self.borrow().horizontal_layout.get_toplevel() {
// TODO: ugly way to resize drawing area, I should find a better way
parent.connect_configure_event(move |w, _| {
let need_diff = s.borrow().initial_diff.is_none();
... | identifier_body |
graph.rs | use cairo;
use gtk::{self, BoxExt, ContainerExt, DrawingArea, ScrolledWindowExt, StateFlags, WidgetExt};
use std::cell::RefCell;
use gdk::{self, WindowExt};
use std::rc::Rc;
use std::time::Instant;
use color::Color;
use utils::RotateVec;
const LEFT_WIDTH: f64 = 31.;
pub struct Graph {
elapsed: Instant,
colo... | else {
eprintln!("This method needs to be called *after* it has been put inside a window");
}
}
}
| {
// TODO: ugly way to resize drawing area, I should find a better way
parent.connect_configure_event(move |w, _| {
let need_diff = s.borrow().initial_diff.is_none();
if need_diff {
let mut s = s.borrow_mut();
let parent_wid... | conditional_block |
windows_aligned_file_reader.rs | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license.
*/
use std::sync::Arc;
use std::time::Duration;
use std::{ptr, thread};
use crossbeam::sync::ShardedLock;
use hashbrown::HashMap;
use once_cell::sync::Lazy;
use platform::file_handle::{AccessMode, ShareMode};
use platf... |
// Extract number of neighbors from the node_data
let neighbors_num = u32::from_le_bytes(
node_data[num_nbrs_start..nbrs_buf_start]
.try_into()
.unwrap(),
);
let nbors_buf_end =
... | .chunks_exact(std::mem::size_of::<f32>())
.map(|chunk| f32::from_le_bytes(chunk.try_into().unwrap()))
.collect(); | random_line_split |
windows_aligned_file_reader.rs | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license.
*/
use std::sync::Arc;
use std::time::Duration;
use std::{ptr, thread};
use crossbeam::sync::ShardedLock;
use hashbrown::HashMap;
use once_cell::sync::Lazy;
use platform::file_handle::{AccessMode, ShareMode};
use platf... | () {
let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap();
let result = reader.get_ctx();
assert!(result.is_ok());
}
#[test]
fn test_register_thread() {
let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap();
let result = reader.register... | test_get_ctx | identifier_name |
windows_aligned_file_reader.rs | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license.
*/
use std::sync::Arc;
use std::time::Duration;
use std::{ptr, thread};
use crossbeam::sync::ShardedLock;
use hashbrown::HashMap;
use once_cell::sync::Lazy;
use platform::file_handle::{AccessMode, ShareMode};
use platf... |
}
pub struct WindowsAlignedFileReader {
file_name: String,
// ctx_map is the mapping from thread id to io context. It is hashmap behind a sharded lock to allow concurrent access from multiple threads.
// ShardedLock: shardedlock provides an implementation of a reader-writer lock that offers concurrent re... | {
self.aligned_buf
} | identifier_body |
columnar.rs | rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.
//! A columnar rep... |
true
}
/// Finalize constructing a [ColumnarRecords].
pub fn finish(self) -> ColumnarRecords {
let ret = ColumnarRecords {
len: self.len,
key_data: Buffer::from(self.key_data),
key_offsets: OffsetsBuffer::try_from(self.key_offsets)
.expec... | {
let ((key, val), ts, diff) = record;
// Check size invariants ahead of time so we stay atomic when we can't
// add the record.
if !self.can_fit(key, val, KEY_VAL_DATA_MAX_LEN) {
return false;
}
// NB: We should never hit the following expects because we ch... | identifier_body |
columnar.rs | All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.
//! A columnar... | key_data: self.key_data.as_slice(),
key_offsets: self.key_offsets.as_slice(),
val_data: self.val_data.as_slice(),
val_offsets: self.val_offsets.as_slice(),
timestamps: self.timestamps.as_slice(),
diffs: self.diffs.as_slice(),
};
deb... | /// Borrow Self as a [ColumnarRecordsRef].
fn borrow<'a>(&'a self) -> ColumnarRecordsRef<'a> {
let ret = ColumnarRecordsRef {
len: self.len, | random_line_split |
columnar.rs | rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.
//! A columnar rep... | (self) -> ColumnarRecords {
let ret = ColumnarRecords {
len: self.len,
key_data: Buffer::from(self.key_data),
key_offsets: OffsetsBuffer::try_from(self.key_offsets)
.expect("constructed valid offsets"),
val_data: Buffer::from(self.val_data),
... | finish | identifier_name |
columnar.rs | rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.
//! A columnar rep... |
if let Some(first_val_offset) = self.val_offsets.first() {
if first_val_offset.to_usize()!= 0 {
return Err(format!(
"expected first val offset to be 0 got {}",
first_val_offset.to_usize()
));
}
}
if ... | {
return Err(format!(
"expected {} val_offsets got {}",
self.len + 1,
self.val_offsets.len()
));
} | conditional_block |
mod.rs | use std::{
alloc::Layout,
array::TryFromSliceError,
borrow::BorrowMut,
cell::{Cell, UnsafeCell},
collections::HashMap,
ffi::OsStr,
fs,
io::{self, Read, Write},
mem,
ops::{Deref, DerefMut},
path::Path,
sync::{Arc, Mutex, MutexGuard}, | use anyhow::{anyhow, Result};
use bevy_ecs::{
ComponentId, DynamicFetch, DynamicFetchResult, DynamicQuery, DynamicSystem, EntityBuilder,
QueryAccess, StatefulQuery, TypeAccess, TypeInfo, World,
};
use bincode::DefaultOptions;
use fs::OpenOptions;
use io::IoSlice;
use mem::ManuallyDrop;
use quill::ecs::TypeLayou... | todo, u32, vec,
};
| random_line_split |
mod.rs | use std::{
alloc::Layout,
array::TryFromSliceError,
borrow::BorrowMut,
cell::{Cell, UnsafeCell},
collections::HashMap,
ffi::OsStr,
fs,
io::{self, Read, Write},
mem,
ops::{Deref, DerefMut},
path::Path,
sync::{Arc, Mutex, MutexGuard},
todo, u32, vec,
};
use anyhow::{an... | (&mut self, buf: &[u8]) -> io::Result<usize> {
self.extend_from_slice(buf);
Ok(buf.len())
}
#[inline]
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
let len = bufs.iter().map(|b| b.len() as u32).sum();
self.reserve(len);
for buf in bufs {
... | write | identifier_name |
mod.rs | use std::{
alloc::Layout,
array::TryFromSliceError,
borrow::BorrowMut,
cell::{Cell, UnsafeCell},
collections::HashMap,
ffi::OsStr,
fs,
io::{self, Read, Write},
mem,
ops::{Deref, DerefMut},
path::Path,
sync::{Arc, Mutex, MutexGuard},
todo, u32, vec,
};
use anyhow::{an... |
}
struct Buffer<'a> {
memory: &'a Memory,
// fn reserve(ptr: WasmPtr<u8, Array>, cap: u32, len: u32, additional: u32)
reserve: &'a NativeFunc<(WasmPtr<RawBuffer>, u32)>,
raw: WasmPtr<RawBuffer>,
}
#[repr(C)]
#[derive(Debug, Clone, Copy)]
struct RawBuffer {
ptr: WasmPtr<u8, Array>,
cap: u32,
... | {
let mut query = DynamicQuery::default();
query.access = self.access(layouts)?;
// TODO: TypeInfo
Ok(query)
} | identifier_body |
scheduler.rs | extern crate clap;
extern crate esvm;
extern crate fern;
extern crate ethereum_newtypes;
extern crate rayon;
extern crate regex;
extern crate reqwest;
extern crate hexdecode;
extern crate serde_json;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate chrono;
use std::fs::{self, File};
... |
fn add_worker(&self, worker: Worker) {
self.queue.lock().unwrap().push(worker);
}
fn get_worker(&self) -> WorkerHandle {
let worker;
loop {
if let Some(w) = self.queue.lock().unwrap().pop() {
worker = Some(w);
break;
}
... | {
let s = Scheduler::new();
for url in &urls {
s.queue.lock().unwrap().push(Worker::new(url, timeout).unwrap()); // if the workers can not connect initially fail
}
s
} | identifier_body |
scheduler.rs | extern crate clap;
extern crate esvm;
extern crate fern;
extern crate ethereum_newtypes;
extern crate rayon;
extern crate regex;
extern crate reqwest;
extern crate hexdecode;
extern crate serde_json;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate chrono;
use std::fs::{self, File};
... | (path: &str) -> (Arc<Mutex<Vec<(usize, String)>>>, usize) {
let mut acc_list = String::new();
File::open(path)
.expect("Could not open account list")
.read_to_string(&mut acc_list)
.expect("Could not read account list");
let acc_vec: Vec<(usize, String)> = acc_list
.lines()
... | parse_account_list | identifier_name |
scheduler.rs | extern crate clap;
extern crate esvm;
extern crate fern;
extern crate ethereum_newtypes;
extern crate rayon;
extern crate regex;
extern crate reqwest;
extern crate hexdecode;
extern crate serde_json;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate chrono;
use std::fs::{self, File};
... | }
res
}
}
impl<'a> Drop for WorkerHandle<'a> {
fn drop(&mut self) {
if!self.kill {
let worker = self
.worker
.take()
.expect("Worker replaced before adding back");
self.scheduler.add_worker(worker)
} else {
... | } | random_line_split |
scheduler.rs | extern crate clap;
extern crate esvm;
extern crate fern;
extern crate ethereum_newtypes;
extern crate rayon;
extern crate regex;
extern crate reqwest;
extern crate hexdecode;
extern crate serde_json;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate chrono;
use std::fs::{self, File};
... |
if attack.attack_type == AttackType::DeleteContract {
res.1 = true;
}
if attack.attack_type == AttackType::HijackControlFlow {
res.... | {
res.0 = true;
} | conditional_block |
lib.rs | // Copyright 2020 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.
#![deny(missing_docs)]
//! This module provides a test HTTP(S) server that can be instantiated simply by a unit test, for
//! connecting components to whe... | <'a>(
listener: &'a mut fuchsia_async::net::TcpListener,
) -> impl Stream<Item = std::io::Result<fuchsia_async::net::TcpStream>> + 'a {
use std::task::{Context, Poll};
#[pin_project::pin_project]
struct AcceptStream<'a> {
#[pin]
listener: &'a mut fuchsia_async::net::TcpListener,
}
... | accept_stream | identifier_name |
lib.rs | // Copyright 2020 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.
#![deny(missing_docs)]
//! This module provides a test HTTP(S) server that can be instantiated simply by a unit test, for
//! connecting components to whe... | else {
(None, false)
};
let task = fasync::Task::spawn(async move {
let listener = accept_stream(&mut listener);
let listener = listener
.map_err(Error::from)
.map_ok(|conn| fuchsia_hyper::TcpStream { stream: conn });
let ... | {
// build a server configuration using a test CA and cert chain
let mut tls_config = rustls::ServerConfig::new(rustls::NoClientAuth::new());
tls_config.set_single_cert(cert_chain, private_key).unwrap();
let tls_acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(tls_conf... | conditional_block |
lib.rs | // Copyright 2020 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.
#![deny(missing_docs)]
//! This module provides a test HTTP(S) server that can be instantiated simply by a unit test, for
//! connecting components to whe... |
}
AcceptStream { listener }
}
#[cfg(not(target_os = "fuchsia"))]
fn accept_stream<'a>(
listener: &'a mut async_net::TcpListener,
) -> impl Stream<Item = std::io::Result<async_net::TcpStream>> + 'a {
listener.incoming()
}
fn parse_cert_chain(mut bytes: &[u8]) -> Vec<rustls::Certificate> {
rustls:... | {
let mut this = self.project();
match this.listener.async_accept(cx) {
Poll::Ready(Ok((conn, _addr))) => Poll::Ready(Some(Ok(conn))),
Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),
Poll::Pending => Poll::Pending,
}
} | identifier_body |
lib.rs | // Copyright 2020 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.
#![deny(missing_docs)]
//! This module provides a test HTTP(S) server that can be instantiated simply by a unit test, for
//! connecting components to whe... |
/// A builder to construct a `TestServer`.
#[derive(Default)]
pub struct TestServerBuilder {
handlers: Vec<Arc<dyn Handler>>,
https_certs: Option<(Vec<rustls::Certificate>, rustls::PrivateKey)>,
}
impl TestServerBuilder {
/// Create a new TestServerBuilder
pub fn new() -> Self {
Self::default(... | /// Create a Builder
pub fn builder() -> TestServerBuilder {
TestServerBuilder::new()
}
} | random_line_split |
spline.rs | use ordered_float::NotNan;
use crate::hitobject::SliderSplineKind;
use crate::math::{Math, Point};
/// Represents a spline, a set of points that represents the actual shape of a slider, generated
/// from the control points.
#[derive(Clone, Debug)]
pub struct Spline {
/// The actual points
pub spline_points: ... | self.cumulative_lengths[idx].into_inner(),
);
let proportion = (length - len1) / (len2 - len1);
let (p1, p2) = (self.spline_points[idx - 1], self.spline_points[idx]);
(p2 - p1) * P::new(proportion, proportion) + p1
}
... |
let (len1, len2) = (
self.cumulative_lengths[idx - 1].into_inner(), | random_line_split |
spline.rs | use ordered_float::NotNan;
use crate::hitobject::SliderSplineKind;
use crate::math::{Math, Point};
/// Represents a spline, a set of points that represents the actual shape of a slider, generated
/// from the control points.
#[derive(Clone, Debug)]
pub struct Spline {
/// The actual points
pub spline_points: ... | (control_points: &[P], l: &mut [P], r: &mut [P], midpoints_buf: &mut [P]) {
let count = control_points.len();
midpoints_buf.copy_from_slice(control_points);
for i in 0..count {
l[i] = midpoints_buf[0];
r[count - i - 1] = midpoints_buf[count - i - 1];
for j in 0..count - i - 1 {
... | subdivide | identifier_name |
spline.rs | use ordered_float::NotNan;
use crate::hitobject::SliderSplineKind;
use crate::math::{Math, Point};
/// Represents a spline, a set of points that represents the actual shape of a slider, generated
/// from the control points.
#[derive(Clone, Debug)]
pub struct Spline {
/// The actual points
pub spline_points: ... |
/// Calculate the angle at the given length on the slider
fn angle_at_length(&self, length: f64) -> P {
let _length_notnan = NotNan::new(length).unwrap();
// match self.cumulative_lengths.binary_search(&length_notnan) {
// Ok(_) => {}
// Err(_) => {}
// }
... | {
self.spline_points.last().cloned().unwrap()
} | identifier_body |
spline.rs | use ordered_float::NotNan;
use crate::hitobject::SliderSplineKind;
use crate::math::{Math, Point};
/// Represents a spline, a set of points that represents the actual shape of a slider, generated
/// from the control points.
#[derive(Clone, Debug)]
pub struct Spline {
/// The actual points
pub spline_points: ... | let diff = (t1 - t0).abs();
let pixel_length = pixel_length.unwrap_or(radius * diff);
// circumference is 2 * pi * r, slider length over circumference is length/(2 * pi * r)
let direction_unit = (t1 - t0) / (t1 - t0).abs();
let new_t1 = t0... | {
let (p1, p2, p3) = (points[0], points[1], points[2]);
let (center, radius) = Math::circumcircle(p1, p2, p3);
// find the t-values of the start and end of the slider
let t0 = (center.y - p1.y).atan2(p1.x - center.x);
let mut mid = (center... | conditional_block |
pattern.rs | use fmt::Formatter;
use log::*;
use std::borrow::Cow;
use std::fmt::{self, Display};
use std::{convert::TryFrom, str::FromStr};
use thiserror::Error;
use crate::*;
/// A pattern that can function as either a [`Searcher`] or [`Applier`].
///
/// A [`Pattern`] is essentially a for-all quantified expression with
/// [`... | lf) -> Vec<Var> {
Pattern::vars(self)
}
}
impl<L, A> Applier<L, A> for Pattern<L>
where
L: Language,
A: Analysis<L>,
{
fn get_pattern_ast(&self) -> Option<&PatternAst<L>> {
Some(&self.ast)
}
fn apply_matches(
&self,
egraph: &mut EGraph<L, A>,
matches: &[... | (&se | identifier_name |
pattern.rs | use fmt::Formatter;
use log::*;
use std::borrow::Cow;
use std::fmt::{self, Display};
use std::{convert::TryFrom, str::FromStr};
use thiserror::Error;
use crate::*;
/// A pattern that can function as either a [`Searcher`] or [`Applier`].
///
/// A [`Pattern`] is essentially a for-all quantified expression with
/// [`... | }
*ids.last().unwrap()
}
#[cfg(test)]
mod tests {
use crate::{SymbolLang as S, *};
type EGraph = crate::EGraph<S, ()>;
#[test]
fn simple_match() {
crate::init_logger();
let mut egraph = EGraph::default();
let (plus_id, _) = egraph.union_instantiations(
&... | };
ids[i] = id; | random_line_split |
pattern.rs | use fmt::Formatter;
use log::*;
use std::borrow::Cow;
use std::fmt::{self, Display};
use std::{convert::TryFrom, str::FromStr};
use thiserror::Error;
use crate::*;
/// A pattern that can function as either a [`Searcher`] or [`Applier`].
///
/// A [`Pattern`] is essentially a for-all quantified expression with
/// [`... | fn vars(&self) -> Vec<Var> {
Pattern::vars(self)
}
}
impl<L, A> Applier<L, A> for Pattern<L>
where
L: Language,
A: Analysis<L>,
{
fn get_pattern_ast(&self) -> Option<&PatternAst<L>> {
Some(&self.ast)
}
fn apply_matches(
&self,
egraph: &mut EGraph<L, A>,
... | let substs = self.program.run(egraph, eclass);
if substs.is_empty() {
None
} else {
let ast = Some(Cow::Borrowed(&self.ast));
Some(SearchMatches {
eclass,
substs,
ast,
})
}
}
| identifier_body |
pattern.rs | use fmt::Formatter;
use log::*;
use std::borrow::Cow;
use std::fmt::{self, Display};
use std::{convert::TryFrom, str::FromStr};
use thiserror::Error;
use crate::*;
/// A pattern that can function as either a [`Searcher`] or [`Applier`].
///
/// A [`Pattern`] is essentially a for-all quantified expression with
/// [`... | };
ids[i] = id;
}
*ids.last().unwrap()
}
#[cfg(test)]
mod tests {
use crate::{SymbolLang as S, *};
type EGraph = crate::EGraph<S, ()>;
#[test]
fn simple_match() {
crate::init_logger();
let mut egraph = EGraph::default();
let (plus_id, _) = egraph.union_... | let n = e.clone().map_children(|child| ids[usize::from(child)]);
trace!("adding: {:?}", n);
egraph.add(n)
}
| conditional_block |
main.rs | #![allow(clippy::single_match)]
use ::std::collections::HashMap;
use ::std::sync::Mutex;
use anyhow::Error;
use chrono::naive::NaiveDate as Date;
use derive_more::Display;
use log::*;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
mod citation;
mod filters;
mod github;
mod md;
lazy_static::lazy_static!... | (&self) -> String {
match self {
Self::BS => "Bachelor of Science".into(),
Self::MS => "Master of Science".into(),
Self::PhD => "PhD".into(),
}
}
}
#[derive(Serialize, Deserialize)]
struct Education {
institution: String,
degree: Degree,
major: String,
duration: DateRange,
#[serde(skip_serializing_i... | to_resume_string | identifier_name |
main.rs | #![allow(clippy::single_match)]
use ::std::collections::HashMap;
use ::std::sync::Mutex;
use anyhow::Error;
use chrono::naive::NaiveDate as Date;
use derive_more::Display;
use log::*;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
mod citation;
mod filters;
mod github;
mod md;
lazy_static::lazy_static!... | fn deserialize<D: Deserializer<'a>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
s.parse().map_err(serde::de::Error::custom)
}
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
enum Citation {
Raw(String),
RawWithYear { text: String, year: Option<u32> },
Url(citation::UrlCita... | }
impl<'a> Deserialize<'a> for DateRange { | random_line_split |
readbuf.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | /// A borrowed byte buffer which is incrementally filled and initialized.
///
/// This type is a sort of "double cursor". It tracks three regions in the buffer: a region at the beginning of the
/// buffer that has been logically filled with data, a region that has been initialized at some point but not yet
/// logicall... | random_line_split | |
readbuf.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
/// Returns a mutable reference to the initialized portion of the cursor.
#[inline]
pub fn init_mut(&mut self) -> &mut [u8] {
// SAFETY: We only slice the initialized part of the buffer, which is always valid
unsafe {
MaybeUninit::slice_assume_init_mut(&mut self.buf.buf[self.bu... | {
// SAFETY: We only slice the initialized part of the buffer, which is always valid
unsafe { MaybeUninit::slice_assume_init_ref(&self.buf.buf[self.buf.filled..self.buf.init]) }
} | identifier_body |
readbuf.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | (&mut self, buf: &[u8]) -> Result<usize> {
self.append(buf);
Ok(buf.len())
}
fn flush(&mut self) -> Result<()> {
Ok(())
}
}
| write | identifier_name |
shadow_logger.rs | use std::cell::RefCell;
use std::sync::mpsc::{Receiver, Sender};
use std::sync::Arc;
use std::sync::{Mutex, RwLock};
use std::time::Duration;
use crossbeam::queue::ArrayQueue;
use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError};
use logger as c_log;
use once_cell::sync::{Lazy, OnceCell};
use shadow_sh... |
}
| {
set_buffering_enabled(buffering_enabled != 0)
} | identifier_body |
shadow_logger.rs | use std::cell::RefCell;
use std::sync::mpsc::{Receiver, Sender};
use std::sync::Arc;
use std::sync::{Mutex, RwLock};
use std::time::Duration;
use crossbeam::queue::ArrayQueue;
use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError};
use logger as c_log;
use once_cell::sync::{Lazy, OnceCell};
use shadow_sh... | (&self, metadata: &Metadata) -> bool {
let filter = match Worker::with_active_host(|host| host.info().log_level) {
Some(Some(level)) => level,
_ => self.max_level(),
};
metadata.level() <= filter
}
fn log(&self, record: &Record) {
if!self.enabled(record.m... | enabled | identifier_name |
shadow_logger.rs | use std::cell::RefCell;
use std::sync::mpsc::{Receiver, Sender};
use std::sync::Arc;
use std::sync::{Mutex, RwLock};
use std::time::Duration;
use crossbeam::queue::ArrayQueue;
use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError};
use logger as c_log;
use once_cell::sync::{Lazy, OnceCell};
use shadow_sh... | fn log(&self, record: &Record) {
if!self.enabled(record.metadata()) {
return;
}
let message = std::fmt::format(*record.args());
let host_info = Worker::with_active_host(|host| host.info().clone());
let mut shadowrecord = ShadowLogRecord {
level: rec... | }
| random_line_split |
main.rs | extern crate byteorder;
///Used to get screen resolution.
extern crate screenshot;
extern crate inputbot;
extern crate ron;
extern crate bincode;
#[macro_use]
extern crate serde_derive;
extern crate serde;
use prelude::*;
use std::{
net::{TcpStream},
io::{self,BufRead,BufReader},
fs::{File},
cmp::{Ordering},
... | impl Default for Config {
fn default()->Config {
let screen_res=get_screen_resolution();
Config{
target: Rect{min: pair!(_=>0),max: screen_res},
source: Rect{min: pair!(_=>0.05),max: pair!(_=>0.95)},
clip: Rect{min: pair!(_=>0),max: screen_res},
correct_device_orientation: true,
... | ///Whether to attempt to do ADB port forwarding automatically.
///The android device needs to have `USB Debugging` enabled.
pub android_attempt_usb_connection: bool,
} | random_line_split |
main.rs | extern crate byteorder;
///Used to get screen resolution.
extern crate screenshot;
extern crate inputbot;
extern crate ron;
extern crate bincode;
#[macro_use]
extern crate serde_derive;
extern crate serde;
use prelude::*;
use std::{
net::{TcpStream},
io::{self,BufRead,BufReader},
fs::{File},
cmp::{Ordering},
... | Err(_err)=>println!(
"failed to open communication to android device, is USB Debugging enabled?"
),
}
}else{
println!("usb android device connection is disabled");
}
let mut session=AbsmSession::new(config);
loop {
session.wait_for_event();
}
/*
//Create tcp stream to... | //Parse arguments
let exec_path;
let cfg_path;
{
let mut args=env::args();
exec_path=args.next().expect("first argument should always be executable path!");
cfg_path=args.next().unwrap_or_else(|| String::from("config.txt"));
}
//Load configuration
let config=Config::load_path(&cfg_path);
... | identifier_body |
main.rs | extern crate byteorder;
///Used to get screen resolution.
extern crate screenshot;
extern crate inputbot;
extern crate ron;
extern crate bincode;
#[macro_use]
extern crate serde_derive;
extern crate serde;
use prelude::*;
use std::{
net::{TcpStream},
io::{self,BufRead,BufReader},
fs::{File},
cmp::{Ordering},
... | AsRef<Path>>(path: P,config: &Config)->Result<()> {
use std::process::{Command};
let local_port=match config.remote {
Remote::Tcp(_,port)=>port,
_ => {
println!("not connecting through tcp, skipping adb port forwarding");
return Ok(())
},
};
println!("attempting to adb port forward u... | _adb_forward<P: | identifier_name |
offset-monitor.rs | extern crate kafka;
extern crate getopts;
extern crate env_logger;
extern crate time;
#[macro_use]
extern crate error_chain;
use std::ascii::AsciiExt;
use std::cmp;
use std::env;
use std::io::{self, stdout, stderr, BufWriter, Write};
use std::process;
use std::thread;
use std::time as stdtime;
use kafka::client::{Kaf... | let _ = write!(self.fmt_buf, "({})", curr_lag);
let _ = write!(self.out_buf, " {1:<0$}", self.lag_width, self.fmt_buf);
}
} else {
for p in partitions {
let _ = write!(self.out_buf, " {1:>0$}", self.offset_width, p.c... | self.fmt_buf.clear(); | random_line_split |
offset-monitor.rs | extern crate kafka;
extern crate getopts;
extern crate env_logger;
extern crate time;
#[macro_use]
extern crate error_chain;
use std::ascii::AsciiExt;
use std::cmp;
use std::env;
use std::io::{self, stdout, stderr, BufWriter, Write};
use std::process;
use std::thread;
use std::time as stdtime;
use kafka::client::{Kaf... | {
prev_latest: i64,
curr_latest: i64,
curr_lag: i64,
}
impl Default for Partition {
fn default() -> Self {
Partition {
prev_latest: -1,
curr_latest: -1,
curr_lag: -1,
}
}
}
struct State {
offsets: Vec<Partition>,
lag_decr: i64,
}
impl S... | Partition | identifier_name |
offset-monitor.rs | extern crate kafka;
extern crate getopts;
extern crate env_logger;
extern crate time;
#[macro_use]
extern crate error_chain;
use std::ascii::AsciiExt;
use std::cmp;
use std::env;
use std::io::{self, stdout, stderr, BufWriter, Write};
use std::process;
use std::thread;
use std::time as stdtime;
use kafka::client::{Kaf... |
fn print_head(&mut self, num_partitions: usize) -> Result<()> {
self.out_buf.clear();
{
// ~ format
use std::fmt::Write;
let _ = write!(self.out_buf, "{1:<0$}", self.time_width, "time");
if self.print_summary {
let _ = write!(self.out... | {
Printer {
out: out,
timefmt: "%H:%M:%S".into(),
fmt_buf: String::with_capacity(30),
out_buf: String::with_capacity(160),
time_width: 10,
offset_width: 11,
diff_width: 8,
lag_width: 6,
print_diff: cfg.di... | identifier_body |
mock.rs | // Copyright 2019-2021 PureStake Inc.
// This file is part of Moonbeam.
// Moonbeam is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
pub(crate) fn events() -> Vec<pallet::Event<Test>> {
System::events()
.into_iter()
.map(|r| r.event)
.filter_map(|e| if let Event::Stake(inner) = e { Some(inner) } else { None })
.collect::<Vec<_>>()
}
// Same storage changes as EventHandler::note_author impl
pub(crate) fn set_author(round: u32, acc: u64, p... | {
System::events().pop().expect("Event expected").event
} | identifier_body |
mock.rs | // Copyright 2019-2021 PureStake Inc.
// This file is part of Moonbeam.
// Moonbeam is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | type Block = frame_system::mocking::MockBlock<Test>;
// Configure a mock runtime to test the pallet.
construct_runtime!(
pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
Timestamp: pallet_timest... | pub type Balance = u128;
pub type BlockNumber = u64;
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>; | random_line_split |
mock.rs | // Copyright 2019-2021 PureStake Inc.
// This file is part of Moonbeam.
// Moonbeam is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | <Ks: OpaqueKeys>(_: bool, keys: &[(u64, Ks)], _: &[(u64, Ks)]) {
SessionChangeBlock::set(System::block_number());
dbg!(keys.len());
SessionHandlerCollators::set(keys.iter().map(|(a, _)| *a).collect::<Vec<_>>())
}
fn on_before_session_ending() {}
fn on_disabled(_: u32) {}
}
impl pallet_session::Config for Te... | on_new_session | identifier_name |
mock.rs | // Copyright 2019-2021 PureStake Inc.
// This file is part of Moonbeam.
// Moonbeam is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | )
.collect::<Vec<_>>()
}
// Same storage changes as EventHandler::note_author impl
pub(crate) fn set_author(round: u32, acc: u64, pts: u32) {
<Points<Test>>::mutate(round, |p| *p += pts);
<AwardedPts<Test>>::mutate(round, acc, |p| *p += pts);
}
#[test]
fn geneses() {
ExtBuilder::default()
.with_balances(vec![
... | { None } | conditional_block |
non_blocking.rs | //! A non-blocking, off-thread writer.
//!
//! This spawns a dedicated worker thread which is responsible for writing log
//! lines to the provided writer. When a line is written using the returned
//! `NonBlocking` struct's `make_writer` method, it will be enqueued to be
//! written by the worker thread.
//!
//! The q... | (&mut self, buf: &[u8]) -> std::io::Result<usize> {
let buf_len = buf.len();
let _ = self.tx.send(String::from_utf8_lossy(buf).to_string());
Ok(buf_len)
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[test]
fn backpressure... | write | identifier_name |
non_blocking.rs | //! A non-blocking, off-thread writer.
//!
//! This spawns a dedicated worker thread which is responsible for writing log
//! lines to the provided writer. When a line is written using the returned
//! `NonBlocking` struct's `make_writer` method, it will be enqueued to be
//! written by the worker thread.
//!
//! The q... |
Ok(buf_size)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
#[inline]
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
self.write(buf).map(|_| ())
}
}
impl<'a> MakeWriter<'a> for NonBlocking {
type Writer = NonBlocking;
fn make_writer(&'a self) -> ... | {
return match self.channel.send(Msg::Line(buf.to_vec())) {
Ok(_) => Ok(buf_size),
Err(_) => Err(io::Error::from(io::ErrorKind::Other)),
};
} | conditional_block |
non_blocking.rs | //! A non-blocking, off-thread writer.
//!
//! This spawns a dedicated worker thread which is responsible for writing log
//! lines to the provided writer. When a line is written using the returned
//! `NonBlocking` struct's `make_writer` method, it will be enqueued to be
//! written by the worker thread.
//!
//! The q... | ///
/// By default, the built `NonBlocking` will be lossy.
pub fn lossy(mut self, is_lossy: bool) -> NonBlockingBuilder {
self.is_lossy = is_lossy;
self
}
/// Override the worker thread's name.
///
/// The default worker thread name is "tracing-appender".
pub fn thread_n... | random_line_split | |
non_blocking.rs | //! A non-blocking, off-thread writer.
//!
//! This spawns a dedicated worker thread which is responsible for writing log
//! lines to the provided writer. When a line is written using the returned
//! `NonBlocking` struct's `make_writer` method, it will be enqueued to be
//! written by the worker thread.
//!
//! The q... |
/// Override the worker thread's name.
///
/// The default worker thread name is "tracing-appender".
pub fn thread_name(mut self, name: &str) -> NonBlockingBuilder {
self.thread_name = name.to_string();
self
}
/// Completes the builder, returning the configured `NonBlocking`.
... | {
self.is_lossy = is_lossy;
self
} | identifier_body |
key.rs | //! Protected key
//!
use std::cell::{Cell, Ref, RefCell, RefMut, BorrowState};
use std::fmt::{self, Debug};
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use allocator::{Allocator, KeyAllocator, DefaultKeyAllocator};
use buf::ProtBuf;
/// Key of bytes
pub type ProtKey8<A = DefaultKeyAllocator> = ProtKey<u8, A>;... |
}
/// An RAII protected key with write access
///
/// This instance is the result of a `write` request on a `ProtKey`. Its
/// raw memory may only be written during the lifetime of this object.
pub struct ProtKeyWrite<'a, T: Copy + 'a, A: KeyAllocator + 'a> {
ref_key: RefMut<'a, ProtBuf<T, A>>,
}
impl<'a, T: Co... | {
self.ref_key.fmt(f)
} | identifier_body |
key.rs | //! Protected key
//!
use std::cell::{Cell, Ref, RefCell, RefMut, BorrowState};
use std::fmt::{self, Debug};
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use allocator::{Allocator, KeyAllocator, DefaultKeyAllocator};
use buf::ProtBuf;
/// Key of bytes
pub type ProtKey8<A = DefaultKeyAllocator> = ProtKey<u8, A>;... | }
impl<'a, T: Copy, A: KeyAllocator> Drop for ProtKeyRead<'a, T, A> {
fn drop(&mut self) {
self.read_ctr.set(self.read_ctr.get().checked_sub(1).unwrap());
if self.read_ctr.get() == NOREAD {
unsafe {
<A as KeyAllocator>::protect_none(
self.ref_key.as_p... | pub fn clone_it(&self) -> ProtKeyRead<T, A> {
ProtKeyRead::new(Ref::clone(&self.ref_key), self.read_ctr.clone())
} | random_line_split |
key.rs | //! Protected key
//!
use std::cell::{Cell, Ref, RefCell, RefMut, BorrowState};
use std::fmt::{self, Debug};
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use allocator::{Allocator, KeyAllocator, DefaultKeyAllocator};
use buf::ProtBuf;
/// Key of bytes
pub type ProtKey8<A = DefaultKeyAllocator> = ProtKey<u8, A>;... | (&self) -> ProtKey<T, A> {
ProtKey::new(self.read().clone())
}
}
impl<T: Copy, A: KeyAllocator> PartialEq for ProtKey<T, A> {
fn eq(&self, other: &ProtKey<T, A>) -> bool {
match (self.try_read(), other.try_read()) {
(Some(ref s), Some(ref o)) => *s == *o,
(_, _) => false... | clone | identifier_name |
renderer.rs | use gpukit::wgpu;
use std::sync::Arc;
pub struct Renderer {
context: Arc<gpukit::Context>,
pipeline: wgpu::RenderPipeline,
vertex_buffer: gpukit::Buffer<Vertex>,
index_buffer: gpukit::Buffer<u32>,
bind_group: gpukit::BindGroup,
screen_uniforms: UniformBuffer<ScreenUniforms>,
texture_bind... |
if index_count as usize > self.index_buffer.len() {
self.index_buffer = Self::create_index_buffer(&self.context, index_count as usize);
}
// Write vertices/indices to their respective buffers
for (egui::ClippedMesh(_, mesh), offset) in meshes.iter().zip(&offsets) {
... | {
self.vertex_buffer = Self::create_vertex_buffer(&self.context, vertex_count as usize);
} | conditional_block |
renderer.rs | use gpukit::wgpu;
use std::sync::Arc;
pub struct Renderer {
context: Arc<gpukit::Context>,
pipeline: wgpu::RenderPipeline,
vertex_buffer: gpukit::Buffer<Vertex>,
index_buffer: gpukit::Buffer<u32>,
bind_group: gpukit::BindGroup,
screen_uniforms: UniformBuffer<ScreenUniforms>,
texture_bind... | color_targets: &[wgpu::ColorTargetState {
format: target_format,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::OneMinusSrcAlph... | 2 => Uint32,
]],
bind_group_layouts: &[&bind_group.layout, &texture_bind_group.layout], | random_line_split |
renderer.rs | use gpukit::wgpu;
use std::sync::Arc;
pub struct Renderer {
context: Arc<gpukit::Context>,
pipeline: wgpu::RenderPipeline,
vertex_buffer: gpukit::Buffer<Vertex>,
index_buffer: gpukit::Buffer<u32>,
bind_group: gpukit::BindGroup,
screen_uniforms: UniformBuffer<ScreenUniforms>,
texture_bind... | (context: &gpukit::Context, value: T) -> Self {
let buffer = context
.build_buffer()
.with_usage(wgpu::BufferUsages::UNIFORM)
.init_with_data(std::slice::from_ref(&value));
UniformBuffer { buffer, value }
}
fn update(&self, context: &gpukit::Context) {
s... | new | identifier_name |
exec.rs | use crate::guest;
use crate::guest::{Crash, Guest};
use crate::utils::cli::{App, Arg, OptVal};
use crate::utils::free_ipv4_port;
use crate::Config;
use core::c::to_prog;
use core::prog::Prog;
use core::target::Target;
use executor::transfer::{async_recv_result, async_send};
use executor::{ExecResult, Reason};
use std::... | (&mut self) {
match self.inner {
ExecutorImpl::Linux(ref mut e) => e.start().await,
ExecutorImpl::Scripy(ref mut e) => e.start().await,
}
}
pub async fn exec(&mut self, p: &Prog, t: &Target) -> Result<ExecResult, Option<Crash>> {
match self.inner {
Ex... | start | identifier_name |
exec.rs | use crate::guest;
use crate::guest::{Crash, Guest};
use crate::utils::cli::{App, Arg, OptVal};
use crate::utils::free_ipv4_port;
use crate::Config;
use core::c::to_prog;
use core::prog::Prog;
use core::target::Target;
use executor::transfer::{async_recv_result, async_send};
use executor::{ExecResult, Reason};
use std::... | target_path: PathBuf::from(&cfg.fots_bin),
host_ip,
}
}
pub async fn start(&mut self) {
// handle should be set to kill on drop
self.exec_handle = None;
self.guest.boot().await;
self.start_executer().await
}
pub async fn start_executer(... | {
let guest = Guest::new(cfg);
let port = free_ipv4_port()
.unwrap_or_else(|| exits!(exitcode::TEMPFAIL, "No Free port for executor driver"));
let host_ip = cfg
.executor
.host_ip
.as_ref()
.map(String::from)
.unwrap_or_else... | identifier_body |
exec.rs | use crate::guest;
use crate::guest::{Crash, Guest};
use crate::utils::cli::{App, Arg, OptVal};
use crate::utils::free_ipv4_port;
use crate::Config;
use core::c::to_prog;
use core::prog::Prog;
use core::target::Target;
use executor::transfer::{async_recv_result, async_send};
use executor::{ExecResult, Reason};
use std::... |
Ok(conn) => Some(conn.unwrap()),
};
}
pub async fn exec(&mut self, p: &Prog) -> Result<ExecResult, Option<Crash>> {
// send must be success
assert!(self.conn.is_some());
if let Err(e) = timeout(
Duration::new(15, 0),
async_send(p, self.conn.a... | {
self.exec_handle = None;
eprintln!("Time out: wait executor connection {}", host_addr);
exit(1)
} | conditional_block |
exec.rs | use crate::guest;
use crate::guest::{Crash, Guest};
use crate::utils::cli::{App, Arg, OptVal};
use crate::utils::free_ipv4_port;
use crate::Config;
use core::c::to_prog;
use core::prog::Prog;
use core::target::Target;
use executor::transfer::{async_recv_result, async_send};
use executor::{ExecResult, Reason};
use std::... | listener = match TcpListener::bind(&host_addr).await {
Ok(l) => l,
Err(e) => {
if e.kind() == AddrInUse && retry!= 5 {
self.port = free_ipv4_port().unwrap();
retry += 1;
continue;
... | let host_addr = format!("{}:{}", self.host_ip, self.port); | random_line_split |
main.rs | /*
Copyright 2021 Integritee AG and Supercomputing Systems AG
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... | }
},
Event::Teerex(re) => {
debug!("{:?}", re);
match &re {
my_node_runtime::pallet_teerex::Event::AddedEnclave(sender, worker_url) => {
println!("[+] Received AddedEnclave event");
println!(" Sender (Worker): {:?}", sender);
println!(" Registered URL: {:?}", str::from_ut... | {
for evr in &events {
debug!("Decoded: phase = {:?}, event = {:?}", evr.phase, evr.event);
match &evr.event {
Event::Balances(be) => {
info!("[+] Received balances event");
debug!("{:?}", be);
match &be {
pallet_balances::Event::Transfer {
from: transactor,
to: dest,
amount: ... | identifier_body |
main.rs | /*
Copyright 2021 Integritee AG and Supercomputing Systems AG
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... | .subscribe_finalized_heads(sender)
.map_err(Error::ApiClient)?;
loop {
let new_header: Header = match receiver.recv() {
Ok(header_str) => serde_json::from_str(&header_str).map_err(Error::Serialization),
Err(e) => Err(Error::ApiSubscriptionDisconnected(e)),
}?;
println!(
"[+] Received finalized hea... | //TODO: this should be implemented by parentchain_handler directly, and not via
// exposed parentchain_api. Blocked by https://github.com/scs/substrate-api-client/issues/267.
parentchain_handler
.parentchain_api() | random_line_split |
main.rs | /*
Copyright 2021 Integritee AG and Supercomputing Systems AG
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... | (
node_api: &ParentchainApi,
register_enclave_xt_header: &Header,
) -> Result<bool, Error> {
let enclave_count_of_previous_block =
node_api.enclave_count(Some(*register_enclave_xt_header.parent_hash()))?;
Ok(enclave_count_of_previous_block == 0)
}
| we_are_primary_validateer | identifier_name |
main.rs | /*
Copyright 2021 Integritee AG and Supercomputing Systems AG
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... |
if WorkerModeProvider::worker_mode()!= WorkerMode::Teeracle {
println!("*** [+] Finished syncing light client, syncing parentchain...");
// Syncing all parentchain blocks, this might take a while..
let mut last_synced_header =
parentchain_handler.sync_parentchain(last_synced_header).unwrap();
// -------... | {
start_interval_market_update(
&node_api,
run_config.teeracle_update_interval,
enclave.as_ref(),
&teeracle_tokio_handle,
);
} | conditional_block |
material.rs | use std::ops::{Add, Div, Mul, Sub};
use crate::color::Color;
use crate::hittable::HitRecord;
use crate::ray::Ray;
use crate::rtweekend;
use crate::vec::Vec3;
/// Generic material trait.
pub trait Material<T: Copy> {
/// Scatter an incoming light ray on a material.
///
/// Returns a scattered ray and the a... | ///
/// In our current design, N is a unit vector, but the same does not have to be true for V.
/// Furthermore, V points inwards, so the sign has to be changed.
/// All this is encoded in the reflect() function.
pub struct Metal {
/// Color of the object.
albedo: Color,
/// Fuziness of the specular reflect... | ///
/// Additionally, B is an additional vector for illustration purposes.
/// The reflected ray (in between N and B) has the same angle as the incident ray V with regards to
// the surface. It can be computed as V + B + B. | random_line_split |
material.rs | use std::ops::{Add, Div, Mul, Sub};
use crate::color::Color;
use crate::hittable::HitRecord;
use crate::ray::Ray;
use crate::rtweekend;
use crate::vec::Vec3;
/// Generic material trait.
pub trait Material<T: Copy> {
/// Scatter an incoming light ray on a material.
///
/// Returns a scattered ray and the a... | let r = ray.direction().normalized();
// cosθ = R⋅n
let mut cos_theta = Vec3::dot(&(-r), &rec.normal);
if cos_theta > 1.0 {
cos_theta = 1.0;
}
// sinθ = sqrt(1 - cos²θ)
let sin_theta = (1.0 - cos_theta * cos_theta).sqrt();
// Snell's law
... | and have to reflect) instead!
| conditional_block |
material.rs | use std::ops::{Add, Div, Mul, Sub};
use crate::color::Color;
use crate::hittable::HitRecord;
use crate::ray::Ray;
use crate::rtweekend;
use crate::vec::Vec3;
/// Generic material trait.
pub trait Material<T: Copy> {
/// Scatter an incoming light ray on a material.
///
/// Returns a scattered ray and the a... |
}
impl Material<f64> for Lambertian {
fn scatter(&self, _ray: &Ray<f64>, rec: &HitRecord<f64>) -> Option<(Ray<f64>, Color)> {
// Diffuse reflection: True Lambertian reflection.
// We aim for a Lambertian distribution of the reflected rays, which has a distribution of
// cos(phi) instead of... | {
Lambertian { albedo }
} | identifier_body |
material.rs | use std::ops::{Add, Div, Mul, Sub};
use crate::color::Color;
use crate::hittable::HitRecord;
use crate::ray::Ray;
use crate::rtweekend;
use crate::vec::Vec3;
/// Generic material trait.
pub trait Material<T: Copy> {
/// Scatter an incoming light ray on a material.
///
/// Returns a scattered ray and the a... | {
/// Color of the object.
albedo: Color,
/// Fuziness of the specular reflections.
fuzz: f64,
}
impl Metal {
/// Create a new metallic material from a given intrinsic object color.
///
/// * `albedo`: Intrinsic surface color.
/// * `fuzz`: Fuzziness factor for specular reflection in th... | etal | identifier_name |
actions.rs | use crate::cards::CardInstance;
use crate::game::{Game, PlayerActionState, PlayerActiveInteraction, Time, UPDATE_DURATION};
use crate::geometry::{
Facing, FloatingVector, FloatingVectorExtension, GridVector, GridVectorExtension, Rotation,
TILE_RADIUS, TILE_SIZE, TILE_WIDTH,
};
use crate::mechanisms::{BuildMechanism... |
}
#[derive(Clone, PartialEq, Serialize, Deserialize, Debug)]
pub struct BuildConveyor {
pub allow_splitting: bool,
}
#[derive(Copy, Clone, PartialEq, Serialize, Deserialize, Debug)]
struct BuildConveyorCandidate {
position: GridVector,
input_side: Facing,
}
impl BuildConveyorCandidate {
fn input_position(&s... | {
draw.rectangle_on_map(
5,
game.player.position.containing_tile().to_floating(),
TILE_SIZE.to_floating(),
"#666",
);
} | identifier_body |
actions.rs | use crate::cards::CardInstance;
use crate::game::{Game, PlayerActionState, PlayerActiveInteraction, Time, UPDATE_DURATION};
use crate::geometry::{
Facing, FloatingVector, FloatingVectorExtension, GridVector, GridVectorExtension, Rotation,
TILE_RADIUS, TILE_SIZE, TILE_WIDTH,
};
use crate::mechanisms::{BuildMechanism... | (&self) -> bool {
self.progress > self.finish_time()
}
fn health_to_pay_by(&self, progress: f64) -> f64 {
smootherstep(self.startup_time(), self.finish_time(), progress) * self.health_cost()
}
}
impl ActionTrait for SimpleAction {
fn update(&mut self, context: ActionUpdateContext) -> ActionStatus {
... | finished | identifier_name |
actions.rs | use crate::cards::CardInstance;
use crate::game::{Game, PlayerActionState, PlayerActiveInteraction, Time, UPDATE_DURATION};
use crate::geometry::{
Facing, FloatingVector, FloatingVectorExtension, GridVector, GridVectorExtension, Rotation,
TILE_RADIUS, TILE_SIZE, TILE_WIDTH,
};
use crate::mechanisms::{BuildMechanism... |
}
_ => unreachable!(),
}
}
self.simple_action_type.finish(context);
}
}
if self.progress > self.time_cost() || self.cancel_progress > self.cooldown_time() {
ActionStatus::Completed
} else {
ActionStatus::StillGoing
}
}
fn display... | {
context.game.cards.selected_index = Some(index + 1);
} | conditional_block |
actions.rs | use crate::cards::CardInstance;
use crate::game::{Game, PlayerActionState, PlayerActiveInteraction, Time, UPDATE_DURATION};
use crate::geometry::{
Facing, FloatingVector, FloatingVectorExtension, GridVector, GridVectorExtension, Rotation,
TILE_RADIUS, TILE_SIZE, TILE_WIDTH,
};
use crate::mechanisms::{BuildMechanism... | } | random_line_split | |
lib.rs | // Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by ... | {
pub name: String,
pub id: usize,
}
/// The response to [`Client::database_metadata`].
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct DatabaseMetadata {
pub tables: Vec<Table>,
}
/// A table that is part of [`DatabaseMetadata`].
#[derive(Clone, Debug, Deserialize, Serialize, E... | Database | identifier_name |
lib.rs | // Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by ... | /// A field of a [`Table`].
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct TableField {
pub name: String,
pub database_type: String,
pub base_type: String,
pub special_type: Option<String>,
} | pub name: String,
pub schema: String,
pub fields: Vec<TableField>,
}
| random_line_split |
transaction.rs | use std::collections::HashMap;
use std::hash::Hash;
use std::ops::Range;
use rusqlite::Connection;
use ::serde::Serialize;
use chrono::{Datelike, Duration, Local, NaiveDate, NaiveDateTime};
use crate::db::account_dao::AccountDao;
use crate::db::transaction_dao::{Split, Transaction, TransactionDao};
use crate::db::acco... |
#[derive(Debug)]
#[derive(Serialize)]
pub struct MonthlyTotals {
summaries: Vec<MonthTotal>,
totalSpent: i64,
pub acctSums: Vec<MonthlyExpenseGroup>
}
#[derive(Debug)]
#[derive(Serialize)]
pub struct AccountSummary {
name: String,
monthlyTotals: Vec<MonthlyTotal>,
}
#[derive(Debug)]
#[derive(Ser... | {
let (since_nd, until_nd) = since_until(since, until, months, year);
let dao = TransactionDao { conn: &conn };
dao.list(&since_nd, &until_nd)
} | identifier_body |
transaction.rs | use std::collections::HashMap;
use std::hash::Hash;
use std::ops::Range;
use rusqlite::Connection;
use ::serde::Serialize;
use chrono::{Datelike, Duration, Local, NaiveDate, NaiveDateTime};
use crate::db::account_dao::AccountDao;
use crate::db::transaction_dao::{Split, Transaction, TransactionDao};
use crate::db::acco... | ;
NaiveDate::from_ymd(curr_year, curr_month, 1)
}).collect::<Vec<_>>();
desired_months.insert(0, NaiveDate::from_ymd(until.year(), until.month(), 1));
let mut cloned_expenses = expenses.clone();
(0..cloned_expenses.len()).for_each(|i| {
let mut exp = &mut cloned_expenses[i];
... | {
curr_month -= 1;
} | conditional_block |
transaction.rs | use std::collections::HashMap;
use std::hash::Hash;
use std::ops::Range;
use rusqlite::Connection;
use ::serde::Serialize;
use chrono::{Datelike, Duration, Local, NaiveDate, NaiveDateTime};
use crate::db::account_dao::AccountDao;
use crate::db::transaction_dao::{Split, Transaction, TransactionDao};
use crate::db::acco... | {
pub name: String,
pub total: i64,
monthlyTotals: Vec<MonthTotal>,
}
fn expenses_by_month(
transactions: &Vec<Transaction>,
accounts: &Vec<Account>
) -> Vec<MonthlyExpenseGroup> {
let mut accounts_map = HashMap::new();
for a in accounts {
accounts_map.insert(&a.guid, a);
}
... | MonthlyExpenseGroup | identifier_name |
transaction.rs | use std::collections::HashMap;
use std::hash::Hash;
use std::ops::Range;
use rusqlite::Connection;
use ::serde::Serialize;
use chrono::{Datelike, Duration, Local, NaiveDate, NaiveDateTime};
use crate::db::account_dao::AccountDao;
use crate::db::transaction_dao::{Split, Transaction, TransactionDao};
use crate::db::acco... | }).collect::<Vec<_>>();
summed.sort_by(|a, b| parse_nd(&b.month).cmp(&parse_nd(&a.month)));
let total_spent = summed.iter().map(|m| m.total).sum();
//let mut acct_sums = months.clone();
MonthlyTotals {
summaries: summed,
totalSpent: total_spent,
acctSums: months.clone()
... | month: i,
total: month_summary.into_iter().map(|m| m.total).sum()
} | random_line_split |
glyph_brush.rs | mod builder;
pub use self::builder::*;
use super::*;
use full_rusttype::gpu_cache::Cache;
use hashbrown::hash_map::Entry;
use log::error;
use std::{
borrow::Cow,
fmt,
hash::{BuildHasher, BuildHasherDefault, Hash, Hasher},
i32,
};
/// A hash of `Section` data
type SectionHash = u64;
... | Ok(None) => None,
Ok(Some((tex_coords, pixel_coords))) => {
if pixel_coords.min.x as f32 > bounds.max.x
|| pixel_coords.min.y as f32 > bounds.max.y
|| bound... | None
}
| random_line_split |
glyph_brush.rs | mod builder;
pub use self::builder::*;
use super::*;
use full_rusttype::gpu_cache::Cache;
use hashbrown::hash_map::Entry;
use log::error;
use std::{
borrow::Cow,
fmt,
hash::{BuildHasher, BuildHasherDefault, Hash, Hasher},
i32,
};
/// A hash of `Section` data
type SectionHash = u64;
... |
let verts: Vec<V> = if some_text {
let sections: Vec<_> = self
.section_buffer
.iter()
.map(|hash| &self.calculate_glyph_cache[hash])
.collect();
let mut verts = Vec::with_capacity(
... | {
let (width, height) = self.texture_cache.dimensions();
return Err(BrushError::TextureTooSmall {
suggested: (width * 2, height * 2),
});
} | conditional_block |
glyph_brush.rs | mod builder;
pub use self::builder::*;
use super::*;
use full_rusttype::gpu_cache::Cache;
use hashbrown::hash_map::Entry;
use log::error;
use std::{
borrow::Cow,
fmt,
hash::{BuildHasher, BuildHasherDefault, Hash, Hasher},
i32,
};
/// A hash of `Section` data
type SectionHash = u64;
... |
/// Adds an additional font to the one(s) initially added on build.
///
/// Returns a new [`FontId`](struct.FontId.html) to reference this font.
pub fn add_font<'a: 'font>(&mut self, font_data: Font<'a>) -> FontId {
self.fonts.push(font_data);
FontId(self.fonts.len() - 1)
}... | {
self.add_font(Font::from_bytes(font_data.into()).unwrap())
} | identifier_body |
glyph_brush.rs | mod builder;
pub use self::builder::*;
use super::*;
use full_rusttype::gpu_cache::Cache;
use hashbrown::hash_map::Entry;
use log::error;
use std::{
borrow::Cow,
fmt,
hash::{BuildHasher, BuildHasherDefault, Hash, Hasher},
i32,
};
/// A hash of `Section` data
type SectionHash = u64;
... | <'a, S, G>(&mut self, section: S, custom_layout: &G)
where
S: Into<Cow<'a, VariedSection<'a>>>,
G: GlyphPositioner,
{
if!self.cache_glyph_positioning {
return;
}
let section = section.into();
if cfg!(debug_assertions) {
for text i... | keep_cached_custom_layout | identifier_name |
shared.rs | /* Copyright 2016 Torbjørn Birch Moltu
*
* 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 agre... | let b2 = b.clone();
let mut z = Nbstr::from(b);
assert_eq!(z.deref().len(), len);
assert_eq!(z.deref().as_ptr(), ptr);
assert_eq!(z.deref(), STR);
assert_eq!(take_box(&mut z), Some(b2.clone()));
assert_eq!(take_box(&mut Nbstr::from_str(STR)), Some(b2.clone()));
... | fn boxed() {
let b: Box<str> = STR.to_string().into_boxed_str();
let len = b.len();
let ptr = b.as_ptr(); | random_line_split |
shared.rs | /* Copyright 2016 Torbjørn Birch Moltu
*
* 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 agre... |
impl From<Nbstr> for Box<str> {
fn from(mut z: Nbstr) -> Box<str> {
take_box(&mut z).unwrap_or_else(|| z.deref().to_owned().into_boxed_str() )
}
}
impl From<Nbstr> for String {
fn from(mut z: Nbstr) -> String {
take_box(&mut z)
.map(|b| b.into_string() )
.unwrap_or_els... |
if z.variant() == BOX {
// I asked on #rust, and transmuting from & to mut is apparently undefined behaviour.
// Is it really in this case?
let s: *mut str = unsafe{ mem::transmute(z.get_slice()) };
// Cannot just assign default; then rust tries to drop the previous value!
/... | identifier_body |
shared.rs | /* Copyright 2016 Torbjørn Birch Moltu
*
* 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 agre... | s: &'static str) -> Self {
Self::with_pointer(LITERAL, s)
}
}
impl Nbstr {
fn try_stack(s: &str) -> Option<Self> {match s.len() as u8 {
// Cannot have stack str with length 0, as variant might be NonZero
0 => Some(Self::default()),
1...MAX_STACK => {
let mut z = Self:... | rom( | identifier_name |
packfile.rs | use bytes::{BufMut, BytesMut};
use flate2::{write::ZlibEncoder, Compression};
use sha1::{
digest::{generic_array::GenericArray, FixedOutputDirty},
Digest, Sha1,
};
use std::{convert::TryInto, fmt::Write, io::Write as IoWrite};
// The packfile itself is a very simple format. There is a header, a
// series of pa... | }
#[derive(Debug)]
pub enum TreeItemKind {
File,
Directory,
}
impl TreeItemKind {
#[must_use]
pub const fn mode(&self) -> &'static str {
match self {
Self::File => "100644",
Self::Directory => "40000",
}
}
}
#[derive(Debug)]
pub struct TreeItem<'a> {
pu... | + " +0000".len()
} | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.