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 |
|---|---|---|---|---|
mod.rs | use std::mem;
use std::time::SystemTime; | #[cfg(not(feature="dynamic_mem"))]
const MAX_MEMORY_SLOTS: usize = 1024 * 128;
type Bits = u128;
const MARK_BITS_PER_SLOT: usize = mem::size_of::<Bits>();
const MARK_BITS: usize = MAX_MEMORY_SLOTS / MARK_BITS_PER_SLOT;
#[cfg(feature="dynamic_mem")]
type Mem = Vec<usize>;
#[cfg(not(feature="dynamic_mem"))]
type Mem =... |
#[cfg(feature="dynamic_mem")]
const MAX_MEMORY_SLOTS: usize = 1024 * 1024 * 2; | random_line_split |
mod.rs | use std::mem;
use std::time::SystemTime;
#[cfg(feature="dynamic_mem")]
const MAX_MEMORY_SLOTS: usize = 1024 * 1024 * 2;
#[cfg(not(feature="dynamic_mem"))]
const MAX_MEMORY_SLOTS: usize = 1024 * 128;
type Bits = u128;
const MARK_BITS_PER_SLOT: usize = mem::size_of::<Bits>();
const MARK_BITS: usize = MAX_MEMORY_SLO... |
let slots = self.get_size(object);
self.mark_object(object);
for i in OBJECT_HEADER_SLOTS..slots {
self.mark_and_scan(self.mem[object + i]);
}
}
pub fn print_gc_stats(&self) {
println!(
"{} gcs, {} object allocates, Last GC: Live {} Dead {} in {} ms, Lifetime GC {} ms\n",
sel... | {
return;
} | conditional_block |
gaia_executor.rs | //
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! 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 ... | (ip, rpc_port)
}
}
| {
let rpc_port = self.rpc_runtime.block_on(async {
let query_vineyard = QueryVineyard::new(
self.graph.clone(),
self.partition_manager.clone(),
self.partition_worker_mapping.clone(),
self.worker_partition_list_mapping.clone(),
... | identifier_body |
gaia_executor.rs | //
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! 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 ... |
init_log4rs();
let mut store_config = {
let args: Vec<String> = std::env::args().collect();
if args.len() <= 6 && args[1] == "--config" {
let mut store_config = StoreConfig::init_from_file(&args[2], &args[4]);
if args.len() == 6 {
store_config.graph_name ... | {
util::get_build_info();
return;
} | conditional_block |
gaia_executor.rs | //
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! 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 ... | server_manager,
store_config.clone(),
Box::new(recover_prepare),
)
.unwrap();
let gaia_service = GaiaService::new(
store_config.clone(),
graph.clone(),
partition_manager.clone(),
partition_worker_mapping,
worker_partition_list_mapping,
);
... | random_line_split | |
gaia_executor.rs | //
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! 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 ... | <V, VI, E, EI>(
store_config: Arc<StoreConfig>,
graph: Arc<GlobalGraphQuery<V = V, E = E, VI = VI, EI = EI>>,
partition_manager: Arc<GraphPartitionManager>,
) where
V: Vertex +'static,
VI: Iterator<Item = V> + Send +'static,
E: Edge +'static,
EI: Iterator<Item = E> + Send +'static,
{
let... | run_main | identifier_name |
edgehub.rs | use std::{
env, fs,
future::Future,
path::{Path, PathBuf},
time::Duration as StdDuration,
};
use anyhow::{bail, Context, Result};
use async_trait::async_trait;
use chrono::{DateTime, Duration, Utc};
use futures_util::{
future::{self, Either},
FutureExt,
};
use tracing::{debug, error, info};
us... |
snapshot??
}
// one of sidecars exited first
Either::Right(((res, stopped, sidecars), server)) => {
debug!("a sidecar has stopped. shutting down all sidecars...");
if let Err(e) = res {
error!(message = "failed wait... | // wait for the rest to exit
future::join_all(sidecars).await; | random_line_split |
edgehub.rs | use std::{
env, fs,
future::Future,
path::{Path, PathBuf},
time::Duration as StdDuration,
};
use anyhow::{bail, Context, Result};
use async_trait::async_trait;
use chrono::{DateTime, Duration, Utc};
use futures_util::{
future::{self, Either},
FutureExt,
};
use tracing::{debug, error, info};
us... |
fn session_expiration(&self, settings: &Self::Settings) -> StdDuration {
settings.broker().session().expiration()
}
fn session_cleanup_interval(&self, settings: &Self::Settings) -> StdDuration {
settings.broker().session().cleanup_interval()
}
async fn run(
self,
... | {
settings.broker().persistence().time_interval()
} | identifier_body |
edgehub.rs | use std::{
env, fs,
future::Future,
path::{Path, PathBuf},
time::Duration as StdDuration,
};
use anyhow::{bail, Context, Result};
use async_trait::async_trait;
use chrono::{DateTime, Duration, Utc};
use futures_util::{
future::{self, Either},
FutureExt,
};
use tracing::{debug, error, info};
us... | (&self, settings: &Self::Settings) -> StdDuration {
settings.broker().session().cleanup_interval()
}
async fn run(
self,
config: Self::Settings,
broker: Broker<Self::Authorizer>,
) -> Result<BrokerSnapshot> {
let broker_handle = broker.handle();
let sidecars ... | session_cleanup_interval | identifier_name |
edgehub.rs | use std::{
env, fs,
future::Future,
path::{Path, PathBuf},
time::Duration as StdDuration,
};
use anyhow::{bail, Context, Result};
use async_trait::async_trait;
use chrono::{DateTime, Duration, Utc};
use futures_util::{
future::{self, Either},
FutureExt,
};
use tracing::{debug, error, info};
us... |
};
Ok(state)
}
}
async fn make_server<Z>(
config: Settings,
broker: Broker<Z>,
broker_ready: BrokerReady,
) -> Result<Server<Z, MakeEdgeHubPacketProcessor<MakeMqttPacketProcessor>>>
where
Z: Authorizer + Send +'static,
{
let broker_handle = broker.handle();
let make_proce... | {
debug!("a sidecar has stopped. shutting down all sidecars...");
if let Err(e) = res {
error!(message = "failed waiting for sidecar shutdown", error = %e);
}
// send shutdown event to each of the rest sidecars
shutdown... | conditional_block |
cli.rs | fd: c_int) -> IoResult<Self> {
let mut attrs = MaybeUninit::uninit();
to_io_result(unsafe { libc::tcgetattr(fd, attrs.as_mut_ptr()) })?;
Ok(TerminalAttributes {
inner: unsafe { attrs.assume_init() },
})
}
/// Create a new TerminalAttributes, with an "empty" state (no... |
}
impl AbstractStream for Stream {
type Attributes = TerminalAttributes;
fn isatty(&self) -> bool {
let ret = unsafe { libc::isatty(self.to_fd()) };
let error: i32 = errno::errno().into();
match ret {
1 => true,
0 => match error {
libc::EBADF =>... | {
match *self {
Stream::Stdout => libc::STDOUT_FILENO,
Stream::Stderr => libc::STDERR_FILENO,
Stream::Stdin => libc::STDIN_FILENO,
}
} | identifier_body |
cli.rs | fd: c_int) -> IoResult<Self> {
let mut attrs = MaybeUninit::uninit();
to_io_result(unsafe { libc::tcgetattr(fd, attrs.as_mut_ptr()) })?;
Ok(TerminalAttributes {
inner: unsafe { attrs.assume_init() },
})
}
/// Create a new TerminalAttributes, with an "empty" state (no... | <IS: AbstractStream, OS: AbstractStream>(
mut input_stream: IS,
mut output_stream: OS,
prompt: &str,
is_sensitive: bool,
) -> Result<String> {
let mut input_reader = build_input_reader(&mut input_stream)?;
prompt_for_string_impl(
&mut input_stream,
&mut input_reader,
&mut... | prompt_for_string | identifier_name |
cli.rs | (fd: c_int) -> IoResult<Self> {
let mut attrs = MaybeUninit::uninit();
to_io_result(unsafe { libc::tcgetattr(fd, attrs.as_mut_ptr()) })?;
Ok(TerminalAttributes {
inner: unsafe { attrs.assume_init() },
})
}
/// Create a new TerminalAttributes, with an "empty" state (n... | && self.inner.c_oflag == other.inner.c_oflag
&& self.inner.c_cflag == other.inner.c_cflag
&& self.inner.c_lflag == other.inner.c_lflag
&& self.inner.c_line == other.inner.c_line
&& self.inner.c_cc == other.inner.c_cc
&& self.inner.c_ispeed == other... | random_line_split | |
functions_and_their_processes.rs | use rand::Rng;
use std::time::{SystemTime, UNIX_EPOCH};
pub fn factorial(n: i128) -> i128 {
if n == 1 {
1
} else {
n * factorial(n - 1)
}
}
pub fn fact_iter(n: i128) -> i128 {
fn helper(p: i128, c: i128, max_count: i128) -> i128 {
if c > max_count {
p
} else {
helper(p * c, c + 1, ... | d_divisor(n: i128, test_divisor: i128) -> i128 {
if square(test_divisor) > n {
n
} else {
if devides(test_divisor, n) {
test_divisor
} else {
find_divisor(n, test_divisor + 1)
}
}
}
pub fn smallest_divisor(n: i128) -> i128 {
find_divisor(n, 2)
}
pub fn is_prime(n: i128) -> bool {
... | test_divisor == 0
}
fn fin | identifier_body |
functions_and_their_processes.rs | use rand::Rng;
use std::time::{SystemTime, UNIX_EPOCH};
pub fn factorial(n: i128) -> i128 {
if n == 1 {
1
} else {
n * factorial(n - 1)
}
}
pub fn fact_iter(n: i128) -> i128 {
fn helper(p: i128, c: i128, max_count: i128) -> i128 {
if c > max_count {
p
} else {
helper(p * c, c + 1, ... | }
// Exercise 1.28 Miller-Rabin test
fn miller_rabin_test(n: i128, times: i128) -> bool {
fn expmod(base: i128, exp: i128, m: i128) -> i128 {
if exp == 0 {
1
} else {
if is_even(exp) {
// square after expmod, otherwise it will overflow easily
square(expmod(base, half(exp), m)) % m... | for i in 2..n {
if expmod(i, n, n) == i {
println!(" testing {}", i);
}
} | random_line_split |
functions_and_their_processes.rs | use rand::Rng;
use std::time::{SystemTime, UNIX_EPOCH};
pub fn factorial(n: i128) -> i128 {
if n == 1 {
1
} else {
n * factorial(n - 1)
}
}
pub fn fact_iter(n: i128) -> i128 {
fn helper(p: i128, c: i128, max_count: i128) -> i128 {
if c > max_count {
p
} else {
helper(p * c, c + 1, ... | else {
ackermann(a - 1, ackermann(a, b - 1))
}
}
}
}
fn f(n: i128) -> i128 {
ackermann(0, n)
}
fn g(n: i128) -> i128 {
ackermann(1, n)
}
fn h(n: i128) -> i128 {
ackermann(2, n)
}
pub fn fac(n: i128) -> i128 {
if n == 1 {
1
} else {
n * fac(n - 1)
}
}
pub fn fib(n: i128) -> ... | {
2
} | conditional_block |
functions_and_their_processes.rs | use rand::Rng;
use std::time::{SystemTime, UNIX_EPOCH};
pub fn factorial(n: i128) -> i128 {
if n == 1 {
1
} else {
n * factorial(n - 1)
}
}
pub fn fact_iter(n: i128) -> i128 {
fn helper(p: i128, c: i128, max_count: i128) -> i128 {
if c > max_count {
p
} else {
helper(p * c, c + 1, ... | (amount: i128, coin_kind: i8) -> i128 {
if amount == 0 {
1
} else {
if amount < 0 || coin_kind == 0 {
0
} else {
cc(amount, coin_kind - 1) + cc(amount - get_value(coin_kind), coin_kind)
}
}
}
fn get_value(coin_kind: i8) -> i128 {
match coin_kind {
6 => 100,
5 => 50,
4 =>... | cc | identifier_name |
lib.rs | Id;
pub use crate::interned::InternKey;
pub use crate::runtime::Runtime;
pub use crate::runtime::RuntimeId;
pub use crate::storage::Storage;
/// The base trait which your "query context" must implement. Gives
/// access to the salsa runtime, which you must embed into your query
/// context (along with whatever other s... | (&mut self, key: Q::Key, value: Q::Value)
where
Q::Storage: plumbing::InputQueryStorageOps<Q>,
{
self.set_with_durability(key, value, Durability::LOW);
}
/// Assign a value to an "input query", with the additional
/// promise that this value will **never change**. Must be used
/... | set | identifier_name |
lib.rs | InternId;
pub use crate::interned::InternKey;
pub use crate::runtime::Runtime;
pub use crate::runtime::RuntimeId;
pub use crate::storage::Storage;
/// The base trait which your "query context" must implement. Gives
/// access to the salsa runtime, which you must embed into your query
/// context (along with whatever o... |
/// Gives access to the underlying salsa runtime.
///
/// This method should not be overridden by `Database` implementors.
fn salsa_runtime(&self) -> &Runtime {
self.ops_salsa_runtime()
}
/// Gives access to the underlying salsa runtime.
///
/// This method should not be overri... | if pending_revision > current_revision {
runtime.unwind_cancelled();
}
} | random_line_split |
pwm.rs | use std::{
fmt::Display,
fs,
path::{Path, PathBuf},
str::FromStr,
time::Duration,
};
use thiserror::Error;
use tracing::{debug, instrument};
/// Everything that can go wrong.
#[derive(Error, Debug)]
pub enum PwmError {
#[error("{0:?} not found")]
ControllerNotFound(Controller),
#[error... | if path.is_file() {
Ok(path)
} else {
Err(PwmError::ControllerNotFound(controller.clone()))
}
}
fn channel_dir(&self, controller: &Controller, channel: &Channel) -> Result<PathBuf> {
let n_pwm = self.npwm(controller)?;
if channel.0 >= n_pwm {
... | let path = self
.sysfs_root
.join(format!("pwmchip{}/{}", controller.0, fname)); | random_line_split |
pwm.rs | use std::{
fmt::Display,
fs,
path::{Path, PathBuf},
str::FromStr,
time::Duration,
};
use thiserror::Error;
use tracing::{debug, instrument};
/// Everything that can go wrong.
#[derive(Error, Debug)]
pub enum PwmError {
#[error("{0:?} not found")]
ControllerNotFound(Controller),
#[error... | ormal,
Inversed,
}
impl Display for Polarity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use Polarity::*;
match *self {
Normal => write!(f, "normal"),
Inversed => write!(f, "inversed"),
}
}
}
impl FromStr for Polarity {
type Er... | {
N | identifier_name |
pwm.rs | use std::{
fmt::Display,
fs,
path::{Path, PathBuf},
str::FromStr,
time::Duration,
};
use thiserror::Error;
use tracing::{debug, instrument};
/// Everything that can go wrong.
#[derive(Error, Debug)]
pub enum PwmError {
#[error("{0:?} not found")]
ControllerNotFound(Controller),
#[error... | ve(Debug)]
pub enum Polarity {
Normal,
Inversed,
}
impl Display for Polarity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use Polarity::*;
match *self {
Normal => write!(f, "normal"),
Inversed => write!(f, "inversed"),
}
}
}
imp... | trim_end()
.parse::<u64>()
.map_err(|e| PwmError::NotADuration(s, e))
.map(Duration::from_nanos)
}
#[deri | identifier_body |
xcb.rs | pub type AtomID = xcb::Atom;
pub type Color = u32;
pub type ScreenID = i32;
pub type WindowID = xcb::Window;
pub type DrawableID = xcb::Window;
pub type GraphicsContextID = xcb::Atom;
pub type EventKeyID = xcb::EventMask;
pub type ColorMapID = xcb::Atom;
pub... | self.screen.client.flush().unwrap();
let window = Window
{
screen: self.screen,
id : child_id,
};
window.map();
return Ok(window);
}
}
pub struct GraphicsContext<'client, 'conn>
{
id : GraphicsContextID,
client: &'client Client<'conn>
}
impl<'client, 'conn> GraphicsContext<'client, 'conn>... | return Err(Error{error_code: e.error_code()})
};
| conditional_block |
xcb.rs | pub type AtomID = xcb::Atom;
pub type Color = u32;
pub type ScreenID = i32;
pub type WindowID = xcb::Window;
pub type DrawableID = xcb::Window;
pub type GraphicsContextID = xcb::Atom;
pub type EventKeyID = xcb::EventMask;
pub type ColorMapID = xcb::Atom;
pub... | impl PropertyValue
{
pub fn get_type_atom_id(&self) -> AtomID
{
return match self
{
PropertyValue::String(_) => xcb::ATOM_STRING,
PropertyValue::I32(_) => xcb::ATOM_INTEGER,
PropertyValue::U32(_) => xcb::ATOM_CARDINAL,
PropertyValue::Atom(_) => xcb::ATOM_ATOM,
PropertyValue::UnknownAtom(atom_id) =>... | None,
Atom(AtomID),
UnknownAtom(AtomID),
}
| random_line_split |
xcb.rs | pub type AtomID = xcb::Atom;
pub type Color = u32;
pub type ScreenID = i32;
pub type WindowID = xcb::Window;
pub type DrawableID = xcb::Window;
pub type GraphicsContextID = xcb::Atom;
pub type EventKeyID = xcb::EventMask;
pub type ColorMapID = xcb::Atom;
pub... | ndow: &Window<'_, 'client, 'conn>, foreground: Color, background: Color) -> GraphicsContext<'client, 'conn>
{
let id = window.screen.client.generate_id();
xcb::create_gc_checked(
&window.screen.client.conn,
id,
window.id,
&[
(xcb::GC_FOREGROUND, foreground),
(xcb::GC_BACKGROUND, background),
... | erate(wi | identifier_name |
xcb.rs | pub type AtomID = xcb::Atom;
pub type Color = u32;
pub type ScreenID = i32;
pub type WindowID = xcb::Window;
pub type DrawableID = xcb::Window;
pub type GraphicsContextID = xcb::Atom;
pub type EventKeyID = xcb::EventMask;
pub type ColorMapID = xcb::Atom;
pub... |
pub fn send_message(&self, destination: &Window, event: Event)
{
match event
{
Event::ClientMessageEvent {window, event_type, data,..} =>
{
let message_data = xcb::ffi::xproto::xcb_client_message_data_t::from_data32(data);
let event = xcb::Event::<xcb::ffi::xproto::xcb_client_message_event_t>::ne... | {
let event = match self.conn.poll_for_event()
{
Some(event) => event,
None => return None,
};
match event.response_type() & !0x80
{
xcb::EXPOSE => return Some(Event::ExposedEvent),
xcb::KEY_PRESS => return Some(Event::KeyEvent(KeyEvent::KeyPress)),
xcb::KEY_RELEASE => return Some(Event::KeyEv... | identifier_body |
api.rs | use std::io::{self, Read, Error, ErrorKind};
use std::borrow::Cow;
use hyper;
use hyper::{client, Client, Url };
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
use std::time::Duration;
use serde_json;
use product;
use configs::{Configs, ApiConfigs, ProxyConfigs};
const HOST_URL: &'static str ... | {
error: String
}
#[derive(Serialize, Deserialize, Debug)]
struct ShaItem {
language: String,
prod_key: String,
version: String,
sha_value: String,
sha_method: String,
prod_type: Option<String>,
group_id: Option<String>,
artifact_id: Option<String>,
classifier: Option<String>,
... | ApiError | identifier_name |
api.rs | use std::io::{self, Read, Error, ErrorKind};
use std::borrow::Cow;
use hyper;
use hyper::{client, Client, Url };
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
use std::time::Duration;
use serde_json;
use product;
use configs::{Configs, ApiConfigs, ProxyConfigs};
const HOST_URL: &'static str ... | let e = Error::new( ErrorKind::Other, "Unsupported SHA response - expected array");
return Err(e);
}
let shas = res.as_array().unwrap();
if shas.len() == 0 {
let e = Error::new( ErrorKind::Other, "No match for the SHA");
return Err(e);
}
let doc:ShaItem = serde_json... | {
if json_text.is_none() {
return Err(
Error::new(ErrorKind::Other, "No response from API")
)
}
let res: serde_json::Value = serde_json::from_str(json_text.unwrap().as_str())?;
if res.is_object() && res.get("error").is_some() {
let e = Error::new(
ErrorK... | identifier_body |
api.rs | use std::io::{self, Read, Error, ErrorKind};
use std::borrow::Cow;
use hyper;
use hyper::{client, Client, Url };
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
use std::time::Duration;
use serde_json;
use product;
use configs::{Configs, ApiConfigs, ProxyConfigs};
const HOST_URL: &'static str ... | .clear()
.append_pair("api_key", api_confs.key.clone().unwrap().as_str());
let json_txt = request_json( &resource_url, &confs.proxy );
process_sha_response(json_txt)
}
//replaces base64 special characters with HTML safe percentage encoding
//source: https://en.wikipedia.org/wiki/Base64#URL_appl... |
//attach query params
resource_url
.query_pairs_mut() | random_line_split |
api.rs | use std::io::{self, Read, Error, ErrorKind};
use std::borrow::Cow;
use hyper;
use hyper::{client, Client, Url };
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
use std::time::Duration;
use serde_json;
use product;
use configs::{Configs, ApiConfigs, ProxyConfigs};
const HOST_URL: &'static str ... | ,
Err(e) => Err(e)
}
}
pub fn fetch_product_by_sha(confs: &Configs, sha: &str)
-> Result<product::ProductMatch, io::Error> {
let api_confs = confs.api.clone();
let resource_path = format!("products/sha/{}", encode_sha(sha) );
let mut resource_url = match configs_to_url(&api_confs, resource_... | {
let sha = m.sha.expect("No product sha from SHA result");
let product = m.product.expect("No product info from SHA result");
match fetch_product( &confs, &product.language, &product.prod_key, &product.version ) {
Ok(mut m) => {
m.sha = Some(sha);... | conditional_block |
txn_ext.rs | // Copyright 2023 TiKV Project Authors. Licensed under Apache-2.0.
//! This module contains everything related to transaction hook.
//!
//! This is the temporary (efficient) solution, it should be implemented as one
//! type of coprocessor.
use std::sync::{atomic::Ordering, Arc};
use crossbeam::atomic::AtomicCell;
u... | && txn_context.reactivate_memory_lock_ticks >= ctx.cfg.reactive_memory_lock_timeout_tick
{
pessimistic_locks.status = LocksStatus::Normal;
txn_context.reactivate_memory_lock_ticks = 0;
} else {
drop(pessimistic_locks);
self.add_pending_tick(Pee... | {
// If it is not leader, we needn't reactivate by tick. In-memory pessimistic
// lock will be enabled when this region becomes leader again.
if !self.is_leader() {
return;
}
let transferring_leader = self.raft_group().raft.lead_transferee.is_some();
let txn_... | identifier_body |
txn_ext.rs | // Copyright 2023 TiKV Project Authors. Licensed under Apache-2.0.
//! This module contains everything related to transaction hook.
//!
//! This is the temporary (efficient) solution, it should be implemented as one
//! type of coprocessor.
use std::sync::{atomic::Ordering, Arc};
use crossbeam::atomic::AtomicCell;
u... | <T>(&mut self, ctx: &mut StoreContext<EK, ER, T>) {
// If it is not leader, we needn't reactivate by tick. In-memory pessimistic
// lock will be enabled when this region becomes leader again.
if!self.is_leader() {
return;
}
let transferring_leader = self.raft_group()... | on_reactivate_memory_lock_tick | identifier_name |
txn_ext.rs | // Copyright 2023 TiKV Project Authors. Licensed under Apache-2.0.
//! This module contains everything related to transaction hook.
//!
//! This is the temporary (efficient) solution, it should be implemented as one
//! type of coprocessor.
use std::sync::{atomic::Ordering, Arc};
use crossbeam::atomic::AtomicCell;
u... | continue;
}
lock_count += 1;
encoder.put(CF_LOCK, key.as_encoded(), &lock.to_lock().to_bytes());
}
}
if lock_count == 0 {
// If the map is not empty but all locks are deleted, it is possible that a
//... | let pessimistic_locks = RwLockWriteGuard::downgrade(pessimistic_locks);
fail::fail_point!("invalidate_locks_before_transfer_leader");
for (key, (lock, deleted)) in &*pessimistic_locks {
if *deleted { | random_line_split |
txn_ext.rs | // Copyright 2023 TiKV Project Authors. Licensed under Apache-2.0.
//! This module contains everything related to transaction hook.
//!
//! This is the temporary (efficient) solution, it should be implemented as one
//! type of coprocessor.
use std::sync::{atomic::Ordering, Arc};
use crossbeam::atomic::AtomicCell;
u... |
}
// Returns whether we should propose another TransferLeader command. This is
// for:
// - Considering the amount of pessimistic locks can be big, it can reduce
// unavailable time caused by waiting for the transferee catching up logs.
// - Make transferring leader strictly after write comm... | {
drop(pessimistic_locks);
self.add_pending_tick(PeerTick::ReactivateMemoryLock);
} | conditional_block |
lib.rs | use std::fmt;
use std::time::{Duration, SystemTime, SystemTimeError};
/// Enum with the seven days of the week.
#[derive(Debug, Clone, Copy)]
pub enum Day {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}
/// Maps the `Day` enum to a string representation, e.g. "Monday".
... | if year % 400 == 0 {
366
} else if year % 100 == 0 {
365
} else if year % 4 == 0 {
366
} else {
365
}
}
/// Takes in a year and month (e.g. 2020, February) and returns the number of days in that month.
pub fn days_in_month(year: u64, month: Month) -> u64 {
match ... | /// Takes in a year (e.g. 2019) and returns the number of days in that year.
pub fn days_in_year(year: u64) -> u64 { | random_line_split |
lib.rs | use std::fmt;
use std::time::{Duration, SystemTime, SystemTimeError};
/// Enum with the seven days of the week.
#[derive(Debug, Clone, Copy)]
pub enum Day {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}
/// Maps the `Day` enum to a string representation, e.g. "Monday".
... |
/// Returns the number of milliseconds passed since the unix epoch.
pub fn milliseconds_since_epoch(&self) -> u128 {
self.delta.as_millis()
}
/// Returns the number of microseconds passed since the unix epoch.
pub fn microseconds_since_epoch(&self) -> u128 {
self.delta.as_micros()... | {
Self::from(&SystemTime::now())
} | identifier_body |
lib.rs | use std::fmt;
use std::time::{Duration, SystemTime, SystemTimeError};
/// Enum with the seven days of the week.
#[derive(Debug, Clone, Copy)]
pub enum Day {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}
/// Maps the `Day` enum to a string representation, e.g. "Monday".
... | (month: Month) -> &'static str {
&month_string(month)[0..3]
}
impl fmt::Display for Month {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", month_string(*self))
}
}
/// Takes in a year (e.g. 2019) and returns the number of days in that year.
pub fn days_in_year(year: u64... | month_abbrev_string | identifier_name |
mysql.rs | used by quaint, including default values.
#[derive(Debug, Clone)]
pub struct MysqlUrl {
url: Url,
query_params: MysqlUrlQueryParams,
}
impl MysqlUrl {
/// Parse `Url` to `MysqlUrl`. Returns error for mistyped connection
/// parameters.
pub fn new(url: Url) -> Result<Self, Error> {
let quer... |
}
impl TransactionCapable for Mysql {}
impl Queryable for Mysql {
fn query<'a>(&'a self, q: Query<'a>) -> DBIO<'a, ResultSet> {
let (sql, params) = visitor::Mysql::build(q);
DBIO::new(async move { self.query_raw(&sql, ¶ms).await })
}
fn execute<'a>(&'a self, q: Query<'a>) -> DBIO<'a,... | {
match self.socket_timeout {
Some(duration) => match timeout(duration, f).await {
Ok(Ok(result)) => Ok(result),
Ok(Err(err)) => Err(err.into()),
Err(to) => Err(to.into()),
},
None => match f.await {
Ok(result) =... | identifier_body |
mysql.rs | logic used by quaint, including default values.
#[derive(Debug, Clone)]
pub struct MysqlUrl {
url: Url,
query_params: MysqlUrlQueryParams,
}
impl MysqlUrl {
/// Parse `Url` to `MysqlUrl`. Returns error for mistyped connection
/// parameters.
pub fn new(url: Url) -> Result<Self, Error> {
le... | () {
let conn = Quaint::new(&CONN_STR).await.unwrap();
let _ = conn.raw_cmd("DROP TABLE test_null_constraint_violation").await;
conn.raw_cmd("CREATE TABLE test_null_constraint_violation (id1 int not null, id2 int not null)")
.await
.unwrap();
// Error code 1364
... | test_null_constraint_violation | identifier_name |
mysql.rs | use url::Url;
use crate::{
ast::{ParameterizedValue, Query},
connector::{metrics, queryable::*, ResultSet, DBIO},
error::{Error, ErrorKind},
visitor::{self, Visitor},
};
/// A connector interface for the MySQL database.
#[derive(Debug)]
pub struct Mysql {
pub(crate) pool: my::Pool,
pub(crate) ... | use percent_encoding::percent_decode;
use std::{borrow::Cow, future::Future, path::Path, time::Duration};
use tokio::time::timeout; | random_line_split | |
lib.rs | //! Salak is a multi layered configuration loader and zero-boilerplate configuration parser, with many predefined sources.
//!
//! 1. [About](#about)
//! 2. [Quick Start](#quick-start)
//! 3. [Features](#features)
//! * [Predefined Sources](#predefined-sources)
//! * [Key Convention](#key-convention)
//! * [Va... | <T: PrefixedFromEnvironment>(&self) -> Res<T> {
self.require::<T>(T::prefix())
}
}
/// Context for implementing [`FromEnvironment`].
#[allow(missing_debug_implementations)]
pub struct SalakContext<'a> {
registry: &'a PropertyRegistryInternal<'a>,
iorefs: &'a Mutex<Vec<Box<dyn IORefT + Send>>>,
... | get | identifier_name |
lib.rs | //! Salak is a multi layered configuration loader and zero-boilerplate configuration parser, with many predefined sources.
//!
//! 1. [About](#about)
//! 2. [Quick Start](#quick-start)
//! 3. [Features](#features)
//! * [Predefined Sources](#predefined-sources)
//! * [Key Convention](#key-convention)
//! * [Va... | }
/// Parsing value from environment by [`SalakContext`].
pub trait FromEnvironment: Sized {
/// Generate object from [`SalakContext`].
/// * `val` - Property value can be parsed from.
/// * `env` - Context.
///
/// ```no_run
/// use salak::*;
/// pub struct Config {
/// key: String
... | iorefs: &'a Mutex<Vec<Box<dyn IORefT + Send>>>,
key: &'a mut Key<'a>, | random_line_split |
lib.rs | //! Salak is a multi layered configuration loader and zero-boilerplate configuration parser, with many predefined sources.
//!
//! 1. [About](#about)
//! 2. [Quick Start](#quick-start)
//! 3. [Features](#features)
//! * [Predefined Sources](#predefined-sources)
//! * [Key Convention](#key-convention)
//! * [Va... |
}
/// Context for implementing [`FromEnvironment`].
#[allow(missing_debug_implementations)]
pub struct SalakContext<'a> {
registry: &'a PropertyRegistryInternal<'a>,
iorefs: &'a Mutex<Vec<Box<dyn IORefT + Send>>>,
key: &'a mut Key<'a>,
}
/// Parsing value from environment by [`SalakContext`].
pub trait F... | {
self.require::<T>(T::prefix())
} | identifier_body |
mod.rs | //! TensorFlow Ops
use std::collections::HashMap;
use std::collections::VecDeque;
use std::fmt::Debug;
use std::mem;
use std::ops::{Index, IndexMut};
#[cfg(feature = "serialize")]
use std::result::Result as StdResult;
use std::sync::Arc;
use analyser::interface::{Solver, TensorsProxy};
use analyser::prelude::*;
use op... | (&self) -> &Tensor {
match self {
&TensorView::Owned(ref m) => &m,
&TensorView::Shared(ref m) => m.as_ref(),
}
}
/// Returns a shared copy of the TensorView, turning the one passed
/// as argument into a TensorView::Shared if necessary.
pub fn share(&mut self) ->... | as_tensor | identifier_name |
mod.rs | //! TensorFlow Ops
use std::collections::HashMap;
use std::collections::VecDeque;
use std::fmt::Debug;
use std::mem;
use std::ops::{Index, IndexMut};
#[cfg(feature = "serialize")]
use std::result::Result as StdResult;
use std::sync::Arc;
use analyser::interface::{Solver, TensorsProxy};
use analyser::prelude::*;
use op... | bail!("Streaming is not available for operator {:?}", self)
}
/// Infers properties about the input and output tensors.
///
/// The `inputs` and `outputs` arguments correspond to properties about
/// the input and output tensors that are already known.
///
/// Returns Err in case of... | fn step(
&self,
_inputs: Vec<(Option<usize>, Option<TensorView>)>,
_buffer: &mut Box<OpBuffer>,
) -> Result<Option<Vec<TensorView>>> { | random_line_split |
mod.rs | //! TensorFlow Ops
use std::collections::HashMap;
use std::collections::VecDeque;
use std::fmt::Debug;
use std::mem;
use std::ops::{Index, IndexMut};
#[cfg(feature = "serialize")]
use std::result::Result as StdResult;
use std::sync::Arc;
use analyser::interface::{Solver, TensorsProxy};
use analyser::prelude::*;
use op... |
/// Creates a Tensor from a TensorView.
pub fn into_tensor(self) -> Tensor {
match self {
TensorView::Owned(m) => m,
TensorView::Shared(m) => m.as_ref().clone(),
}
}
/// Returns a reference to the Tensor wrapped inside a TensorView.
pub fn as_tensor(&self) ... | {
match self {
TensorView::Owned(m) => TensorView::Shared(Arc::new(m)),
TensorView::Shared(_) => self,
}
} | identifier_body |
lib.rs | mod file_log;
mod formatter;
pub mod log_macro;
use std::env;
use std::fmt;
use std::io::{self, BufWriter};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
use std::thread;
use log::{self, SetLoggerError};
use slog::{self, slog_o, Drain, FnValue, Key, OwnedKVList,... | type Err = io::Error;
fn log(&self, record: &Record<'_>, values: &OwnedKVList) -> Result<Self::Ok, Self::Err> {
let tag = record.tag();
println!("{}", tag);
if self.slow.is_some() && tag.starts_with("slow_log") {
self.slow.as_ref().unwrap().log(record, values)
} else... | random_line_split | |
lib.rs | mod file_log;
mod formatter;
pub mod log_macro;
use std::env;
use std::fmt;
use std::io::{self, BufWriter};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
use std::thread;
use log::{self, SetLoggerError};
use slog::{self, slog_o, Drain, FnValue, Key, OwnedKVList,... |
// Converts `slog::Level` to unified log level format.
fn get_unified_log_level(lv: Level) -> &'static str {
match lv {
Level::Critical => "FATAL",
Level::Error => "ERROR",
Level::Warning => "WARN",
Level::Info => "INFO",
Level::Debug => "DEBUG",
Level::Trace => "TR... | {
match lv {
Level::Critical => "critical",
Level::Error => "error",
Level::Warning => "warning",
Level::Debug => "debug",
Level::Trace => "trace",
Level::Info => "info",
}
} | identifier_body |
lib.rs | mod file_log;
mod formatter;
pub mod log_macro;
use std::env;
use std::fmt;
use std::io::{self, BufWriter};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
use std::thread;
use log::{self, SetLoggerError};
use slog::{self, slog_o, Drain, FnValue, Key, OwnedKVList,... | (&self, record: &Record<'_>, values: &OwnedKVList) -> Result<Self::Ok, Self::Err> {
let tag = record.tag();
println!("{}", tag);
if self.slow.is_some() && tag.starts_with("slow_log") {
self.slow.as_ref().unwrap().log(record, values)
} else {
self.normal.log(record... | log | identifier_name |
section_0771_to_0788.rs | //! @ The |align_state| and |preamble| variables are initialized elsewhere.
//!
//! @<Set init...@>=
//! align_ptr:=null; cur_align:=null; cur_span:=null; cur_loop:=null;
//! cur_head:=null; cur_tail:=null;
//!
//! @ Alignment stack maintenance is handled by a pair of trivial routines
//! called |push_alignment| and |p... | //! procedure@?align_peek; forward;@t\2@>@/
//! procedure@?normal_paragraph; forward;@t\2@>@/
//! procedure init_align;
//! label done, done1, done2, continue;
//! var save_cs_ptr:pointer; {|warning_index| value for error messages}
//! @!p:pointer; {for short-term temporary use}
//! begin save_cs_ptr:=cur_cs; {\.{\\hal... | //! @p @t\4@>@<Declare the procedure called |get_preamble_token|@>@t@>@/ | random_line_split |
http.rs | time out, so the maximum time we allow Bitcoin Core to block for is twice this
/// value.
const TCP_STREAM_RESPONSE_TIMEOUT: Duration = Duration::from_secs(300);
/// Maximum HTTP message header size in bytes.
const MAX_HTTP_MESSAGE_HEADER_SIZE: usize = 8192;
/// Maximum HTTP message body size in bytes. Enough for a ... |
// Decode the chunk header to obtain the chunk size.
let mut buffer = Vec::new();
let mut decoder = chunked_transfer::Decoder::new(chunk_header.as_bytes());
decoder.read_to_end(&mut buffer)?;
// Read the chunk body.
let chunk_size = match decoder.remaining_chunks_size() {
... | {
// Read the terminator chunk since the decoder consumes the CRLF
// immediately when this chunk is encountered.
reader.read_line(&mut chunk_header).await?;
} | conditional_block |
http.rs | we time out, so the maximum time we allow Bitcoin Core to block for is twice this
/// value.
const TCP_STREAM_RESPONSE_TIMEOUT: Duration = Duration::from_secs(300);
/// Maximum HTTP message header size in bytes.
const MAX_HTTP_MESSAGE_HEADER_SIZE: usize = 8192;
/// Maximum HTTP message body size in bytes. Enough for... | if chunk_header == "0\r\n" {
// Read the terminator chunk since the decoder consumes the CRLF
// immediately when this chunk is encountered.
reader.read_line(&mut chunk_header).await?;
}
// Decode the chunk header to obtain the chunk size.
let mut buffer = Vec::new()... | random_line_split | |
http.rs | time out, so the maximum time we allow Bitcoin Core to block for is twice this
/// value.
const TCP_STREAM_RESPONSE_TIMEOUT: Duration = Duration::from_secs(300);
/// Maximum HTTP message header size in bytes.
const MAX_HTTP_MESSAGE_HEADER_SIZE: usize = 8192;
/// Maximum HTTP message body size in bytes. Enough for a ... | <F>(&mut self, uri: &str, host: &str, auth: &str, content: serde_json::Value) -> std::io::Result<F>
where F: TryFrom<Vec<u8>, Error = std::io::Error> {
let content = content.to_string();
let request = format!(
"POST {} HTTP/1.1\r\n\
Host: {}\r\n\
Authorization: {}\r\n\
Connection: keep-alive\r\n\
... | post | identifier_name |
mod.rs | // Buttplug Rust Source Code File - See https://buttplug.io for more info.
//
// Copyright 2016-2019 Nonpolynomial Labs LLC. All rights reserved.
//
// Licensed under the BSD 3-Clause license. See LICENSE file in the project root
// for full license information.
//! Handling of communication with Buttplug Server.
pub ... | (&self) -> Sender<ButtplugRemoteClientConnectorMessage> {
self.remote_send.clone()
}
pub async fn send(
&mut self,
msg: &ButtplugMessageUnion,
state: &ButtplugClientMessageStateShared,
) {
self.internal_send.send((msg.clone(), state.clone())).await;
}
pub as... | get_remote_send | identifier_name |
mod.rs | // Buttplug Rust Source Code File - See https://buttplug.io for more info.
//
// Copyright 2016-2019 Nonpolynomial Labs LLC. All rights reserved.
//
// Licensed under the BSD 3-Clause license. See LICENSE file in the project root
// for full license information.
//! Handling of communication with Buttplug Server.
pub ... | else {
panic!("Can't send message yet!");
}
}
}
}
}
}
}
| {
remote_sender.send(buttplug_fut_msg.0.clone());
} | conditional_block |
mod.rs | // Buttplug Rust Source Code File - See https://buttplug.io for more info.
//
// Copyright 2016-2019 Nonpolynomial Labs LLC. All rights reserved.
//
// Licensed under the BSD 3-Clause license. See LICENSE file in the project root
// for full license information.
//! Handling of communication with Buttplug Server.
pub ... | // We use two Options instead of an enum because we may never
// get anything.
let mut stream_return: StreamValue = async {
match remote_recv.next().await {
Some(msg) => StreamValue::Incoming(msg),
None =... | loop { | random_line_split |
mod.rs | // Buttplug Rust Source Code File - See https://buttplug.io for more info.
//
// Copyright 2016-2019 Nonpolynomial Labs LLC. All rights reserved.
//
// Licensed under the BSD 3-Clause license. See LICENSE file in the project root
// for full license information.
//! Handling of communication with Buttplug Server.
pub ... | loop {
// We use two Options instead of an enum because we may never
// get anything.
let mut stream_return: StreamValue = async {
match remote_recv.next().await {
Some(msg) => StreamValue::Incoming(msg),
... | {
// Set up a way to get futures in and out of the sorter, which will live
// in our connector task.
let event_send = self.event_send.take().unwrap();
// Remove the receivers we need to move into the task.
let mut remote_recv = self.remote_recv.take().unwrap();
let mut i... | identifier_body |
main.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless r... | ;
// To allow multiple instances of Habitat application in Kubernetes,
// random suffix in metadata_name is needed.
let metadata_name = format!(
"{}-{}{}",
pkg_ident.name,
rand::thread_rng()
.gen_ascii_chars()
.filter(|c| c.is_lowercase() || c.is_numeric())
... | {
PackageIdent::from_str(pkg_ident_str)?
} | conditional_block |
main.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless r... | (ui: &mut UI) -> Result<()> {
let m = cli().get_matches();
debug!("clap cli args: {:?}", m);
if!m.is_present("NO_DOCKER_IMAGE") {
gen_docker_img(ui, &m)?;
}
gen_k8s_manifest(ui, &m)
}
fn gen_docker_img(ui: &mut UI, matches: &clap::ArgMatches) -> Result<()> {
let default_channel = chann... | start | identifier_name |
main.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless r... | .multiple(true)
.number_of_values(1)
.help(
"Bind to another service to form a producer/consumer relationship, \
specified as name:service:group",
),
)
.arg(
Arg::with_name("NO_DOCKER_IMAGE")
... | random_line_split | |
main.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless r... | {
match val.parse::<u32>() {
Ok(_) => Ok(()),
Err(_) => Err(format!("{} is not a natural number", val)),
}
} | identifier_body | |
aes.rs | //! Interface to the AES peripheral.
//!
//! Note that the AES peripheral is only available on some MCUs in the L0/L1/L2
//! families. Check the datasheet for more information.
//!
//! See STM32L0x2 reference manual, chapter 18.
use core::{
convert::TryInto,
ops::{Deref, DerefMut},
pin::Pin,
};
use as_sli... | <Buffer, Channel>(
self,
dma: &mut dma::Handle,
buffer: Pin<Buffer>,
channel: Channel,
) -> Transfer<Self, Channel, Buffer, dma::Ready>
where
Self: dma::Target<Channel>,
Buffer: Deref +'static,
Buffer::Target: AsSlice<Element = u8>,
Channel: dma::C... | write_all | identifier_name |
aes.rs | //! Interface to the AES peripheral.
//!
//! Note that the AES peripheral is only available on some MCUs in the L0/L1/L2
//! families. Check the datasheet for more information.
//!
//! See STM32L0x2 reference manual, chapter 18.
use core::{
convert::TryInto,
ops::{Deref, DerefMut},
pin::Pin,
};
use as_sli... | }
}
/// An active encryption/decryption stream
///
/// You can get an instance of this struct by calling [`AES::enable`].
pub struct Stream {
aes: AES,
/// Can be used to write data to the AES peripheral
pub tx: Tx,
/// Can be used to read data from the AES peripheral
pub rx: Rx,
}
impl Stre... | rx: Rx(()),
tx: Tx(()),
} | random_line_split |
peer.rs | use std::io::BufferedReader;
use std::io::net::ip::SocketAddr;
use std::io::net::tcp::TcpStream;
use std::option::Option;
use std::io::timer::sleep;
use uuid::{Uuid, UuidVersion, Version4Random};
use super::super::events::*;
use super::parsers::{read_rpc, as_network_msg, make_id_bytes};
use super::types::*;
static CON... | (&mut self) {
match self.mgmt_port.try_recv() {
Ok(msg) => {
match msg {
AttachStreamMsg(id, mut stream) => {
if id == self.conf.id {
self.attach_stream(stream);
}
}
... | check_mgmt_msg | identifier_name |
peer.rs | use std::io::BufferedReader;
use std::io::net::ip::SocketAddr;
use std::io::net::tcp::TcpStream;
use std::option::Option;
use std::io::timer::sleep;
use uuid::{Uuid, UuidVersion, Version4Random};
use super::super::events::*;
use super::parsers::{read_rpc, as_network_msg, make_id_bytes};
use super::types::*;
static CON... |
fn new(id: u64, config: NetPeerConfig, to_raft: Sender<RaftMsg>, mgmt_port: Receiver<MgmtMsg>) -> NetPeer {
NetPeer {
id: id,
conf: config,
stream: None,
to_raft: to_raft,
mgmt_port: mgmt_port,
shutdown: false,
}
}
f... | {
let (mgmt_send, mgmt_port) = channel();
let conf = conf.clone();
spawn(proc() {
let mut netpeer = NetPeer::new(id, conf, to_raft, mgmt_port);
netpeer.peer_loop();
});
mgmt_send
} | identifier_body |
peer.rs | use std::io::BufferedReader;
use std::io::net::ip::SocketAddr;
use std::io::net::tcp::TcpStream;
use std::option::Option;
use std::io::timer::sleep;
use uuid::{Uuid, UuidVersion, Version4Random};
use super::super::events::*;
use super::parsers::{read_rpc, as_network_msg, make_id_bytes};
use super::types::*;
static CON... | break;
}
}
let mut replies = 0;
// We should get the votes back out on the port that we were waiting on
debug!("test_spawn(): waiting for replies");
spawn(proc() {
match recv1.recv() {
VRQ(recvote, chan) => {
... | stream.write(vote_bytes);
count += 1;
debug!("[test_spawn()] Sent {} vote requests.", count);
if count > 1 { | random_line_split |
peer.rs | use std::io::BufferedReader;
use std::io::net::ip::SocketAddr;
use std::io::net::tcp::TcpStream;
use std::option::Option;
use std::io::timer::sleep;
use uuid::{Uuid, UuidVersion, Version4Random};
use super::super::events::*;
use super::parsers::{read_rpc, as_network_msg, make_id_bytes};
use super::types::*;
static CON... |
StopMsg => {
self.shutdown = true;
self.stream = None;
}
}
}
_ => {
}
}
}
/*
* Send an RPC up to Raft, waiting for a reply if we need to.
*/
fn send... | {
if self.stream.is_some() {
self.send_rpc(rpc, self.stream.clone().unwrap());
}
} | conditional_block |
huffman.rs | //! Length-limited Huffman Codes.
use crate::bit;
use alloc::{vec, vec::Vec};
use core::cmp;
use core2::io;
const MAX_BITWIDTH: u8 = 15;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Code {
pub width: u8,
pub bits: u16,
}
impl Code {
pub fn new(width: u8, bits: u16) -> Self {
debug_assert!(wid... | else if x_weight < y_weight {
z.push(x.next().unwrap());
} else {
z.push(y.next().unwrap());
}
}
z
}
fn package(mut nodes: Vec<Node>) -> Vec<Node> {
if nodes.len() >= 2 {
let new_len = nodes.len() / 2;
for ... | {
z.extend(x);
break;
} | conditional_block |
huffman.rs | //! Length-limited Huffman Codes.
use crate::bit;
use alloc::{vec, vec::Vec};
use core::cmp;
use core2::io;
const MAX_BITWIDTH: u8 = 15;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Code {
pub width: u8,
pub bits: u16,
}
impl Code {
pub fn new(width: u8, bits: u16) -> Self {
debug_assert!(wid... | {
table: Vec<u16>,
eob_symbol: Option<u16>,
safely_peek_bitwidth: Option<u8>,
max_bitwidth: u8,
}
impl DecoderBuilder {
pub fn new(
max_bitwidth: u8,
safely_peek_bitwidth: Option<u8>,
eob_symbol: Option<u16>,
) -> Self {
debug_assert!(max_bitwidth <= MAX_BITWIDTH... | DecoderBuilder | identifier_name |
huffman.rs | //! Length-limited Huffman Codes.
use crate::bit;
use alloc::{vec, vec::Vec};
use core::cmp;
use core2::io;
const MAX_BITWIDTH: u8 = 15;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Code {
pub width: u8,
pub bits: u16,
}
impl Code {
pub fn new(width: u8, bits: u16) -> Self {
debug_assert!(wid... | EncoderBuilder {
table: vec![Code::new(0, 0); symbol_count],
}
}
pub fn from_bitwidthes(bitwidthes: &[u8]) -> io::Result<Encoder> {
let symbol_count = bitwidthes
.iter()
.enumerate()
.filter(|e| *e.1 > 0)
.last()
.map_or(... | pub struct EncoderBuilder {
table: Vec<Code>,
}
impl EncoderBuilder {
pub fn new(symbol_count: usize) -> Self { | random_line_split |
huffman.rs | //! Length-limited Huffman Codes.
use crate::bit;
use alloc::{vec, vec::Vec};
use core::cmp;
use core2::io;
const MAX_BITWIDTH: u8 = 15;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Code {
pub width: u8,
pub bits: u16,
}
impl Code {
pub fn new(width: u8, bits: u16) -> Self {
debug_assert!(wid... |
fn finish(self) -> Self::Instance {
Encoder { table: self.table }
}
}
#[derive(Debug, Clone)]
pub struct Encoder {
table: Vec<Code>,
}
impl Encoder {
#[inline(always)]
pub fn encode<W>(&self, writer: &mut bit::BitWriter<W>, symbol: u16) -> io::Result<()>
where
W: io::Write,
... | {
debug_assert_eq!(self.table[symbol as usize], Code::new(0, 0));
self.table[symbol as usize] = code.inverse_endian();
Ok(())
} | identifier_body |
post.rs | //! `post` table parsing and writing.
use std::str;
use crate::binary::read::{ReadArray, ReadBinary, ReadCtxt};
use crate::binary::write::{WriteBinary, WriteContext};
use crate::binary::{I16Be, I32Be, U16Be, U32Be, U8};
use crate::error::{ParseError, WriteError};
pub struct PostTable<'a> {
pub header: Header,
... | "florin",
"approxequal",
"Delta",
"guillemotleft",
"guillemotright",
"ellipsis",
"nonbreakingspace",
"Agrave",
"Atilde",
"Otilde",
"OE",
"oe",
"endash",
"emdash",
"quotedblleft",
"quotedblright",
"quoteleft",
"quoteright",
"divide",
"lozeng... | "radical", | random_line_split |
post.rs | //! `post` table parsing and writing.
use std::str;
use crate::binary::read::{ReadArray, ReadBinary, ReadCtxt};
use crate::binary::write::{WriteBinary, WriteContext};
use crate::binary::{I16Be, I32Be, U16Be, U32Be, U8};
use crate::error::{ParseError, WriteError};
pub struct PostTable<'a> {
pub header: Header,
... | // Write name indexes that have unused names between each used entry
U16Be::write(&mut w, 0u16)?; //.notdef
for i in 0..(num_glyphs - 1) {
U16Be::write(&mut w, i * 2 + 258)?;
}
// Write the names
for i in 1..num_glyphs {
// Write a real entry
... | {
// Build a post table with unused name entries
let mut w = WriteBuffer::new();
let header = Header {
version: 0x00020000,
italic_angle: 0,
underline_position: 0,
underline_thickness: 0,
is_fixed_pitch: 0,
min_mem_type_42: ... | identifier_body |
post.rs | //! `post` table parsing and writing.
use std::str;
use crate::binary::read::{ReadArray, ReadBinary, ReadCtxt};
use crate::binary::write::{WriteBinary, WriteContext};
use crate::binary::{I16Be, I32Be, U16Be, U32Be, U8};
use crate::error::{ParseError, WriteError};
pub struct PostTable<'a> {
pub header: Header,
... | <C: WriteContext>(ctxt: &mut C, table: &SubTable<'a>) -> Result<(), WriteError> {
U16Be::write(ctxt, table.num_glyphs)?;
<&ReadArray<'_, _>>::write(ctxt, &table.glyph_name_index)?;
for name in &table.names {
PascalString::write(ctxt, name)?;
}
Ok(())
}
}
impl<'a... | write | identifier_name |
main.rs | //! Default Compute@Edge template program.
use fastly::http::{header, HeaderValue, Method, StatusCode};
use fastly::{mime, Dictionary, Error, Request, Response};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// The name of a backend server associated with this service.
///
/// This should be ch... |
let modified_pop_status= modified_pop_status_opt.unwrap();
let mut modified_pop_status_map: HashMap<String, u8> =
serde_json::from_str(modified_pop_status.as_str()).unwrap();
let query_params: Vec<(String, String)> = req.get_query().unwrap();
println!("... | {
return Ok(Response::from_status(StatusCode::IM_A_TEAPOT)
.with_body_text_plain("Problem accessing API\n"));
} | conditional_block |
main.rs | //! Default Compute@Edge template program.
use fastly::http::{header, HeaderValue, Method, StatusCode};
use fastly::{mime, Dictionary, Error, Request, Response};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// The name of a backend server associated with this service.
///
/// This should be ch... | {
current_pop: String,
pop_status_data: Vec<PopStatusData>,
}
#[derive(Serialize, Deserialize, Debug)]
struct DictionaryInfo {
dictionary_id: String,
service_id: String,
item_key: String,
item_value: String,
}
/// The entry point for your application.
///
/// This function is triggered when y... | PopStatusResponse | identifier_name |
main.rs | //! Default Compute@Edge template program.
use fastly::http::{header, HeaderValue, Method, StatusCode};
use fastly::{mime, Dictionary, Error, Request, Response};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// The name of a backend server associated with this service.
///
/// This should be ch... | group: pop.group.to_string(),
shield: shield.to_string(),
status,
}
})
.collect();
let pop_status_response: PopStatusResponse = PopStatusResponse {
current_pop,
... | latitude: pop.coordinates.latitude,
longitude: pop.coordinates.longitude, | random_line_split |
spike_generators.rs | //! This module represents neurons, generalized as "spike generators." To
//! support a wider range of abstractions, the input neurons are divided into
//! discrete and continuous implementations.
/// The general trait encapsulating a spike generator that has an output voltage
/// V.
pub trait SpikeGenerator<V> {
... |
}
impl<T, V> InputSpikeGenerator<V, T> for SpikeAtTimes<T, V>
where
// TODO: alias this as a trait?
T: From<si::Second<f64>>
+ Copy
+ PartialOrd<T>
+ std::ops::AddAssign
+ std::ops::Sub<Output = T>
+ std::ops::Neg<Output = T>,
... | {
if self.did_spike() {
self.spike_voltage.into()
} else {
(0.0 * si::V).into()
}
} | identifier_body |
spike_generators.rs | //! This module represents neurons, generalized as "spike generators." To
//! support a wider range of abstractions, the input neurons are divided into
//! discrete and continuous implementations.
/// The general trait encapsulating a spike generator that has an output voltage
/// V.
pub trait SpikeGenerator<V> {
... | <'a>(
slot_starts_to_rate: &'a mut Vec<(T, i32)>,
) -> Box<dyn Fn(T) -> Option<(i32, T)> + 'a> {
slot_starts_to_rate.sort_unstable_by(|a, b| {
let (t1, r1) = a;
let (t2, r2) = b;
match t1.partial_cmp(t2) {
Option::None |... | rate_fn_of_times | identifier_name |
spike_generators.rs | //! This module represents neurons, generalized as "spike generators." To
//! support a wider range of abstractions, the input neurons are divided into
//! discrete and continuous implementations.
/// The general trait encapsulating a spike generator that has an output voltage
/// V.
pub trait SpikeGenerator<V> {
... |
}
}
impl<T, V> InputSpikeGenerator<V, T> for SpikeAtTimes<T, V>
where
// TODO: alias this as a trait?
T: From<si::Second<f64>>
+ Copy
+ PartialOrd<T>
+ std::ops::AddAssign
+ std::ops::Sub<Output = T>
+ std::ops::Neg<Output... | {
(0.0 * si::V).into()
} | conditional_block |
spike_generators.rs | //! This module represents neurons, generalized as "spike generators." To
//! support a wider range of abstractions, the input neurons are divided into
//! discrete and continuous implementations.
/// The general trait encapsulating a spike generator that has an output voltage
/// V.
pub trait SpikeGenerator<V> {
... | ) -> Box<dyn Fn(T) -> Option<(i32, T)> + 'a> {
slot_starts_to_rate.sort_unstable_by(|a, b| {
let (t1, r1) = a;
let (t2, r2) = b;
match t1.partial_cmp(t2) {
Option::None | Option::Some(Ordering::Equal) => r1.cmp(r2),
... | slot_starts_to_rate: &'a mut Vec<(T, i32)>, | random_line_split |
fs.rs | use rlua::prelude::*;
use std::{
sync::Arc,
env,
fs::{self, OpenOptions},
io::{self, SeekFrom, prelude::*},
path::Path
};
use serde_json;
use rlua_serde;
use crate::bindings::system::LuaMetadata;
use regex::Regex;
//TODO: Move to having a common interface so IO can share the same binding
pub struct... | if src.is_file() {
fs::copy(src, &dest)?;
}
else {
fs::create_dir_all(&dest)?;
recursive_copy(src, &dest)?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lua_fs () {
let lua = Lua::new();
init(&lua).un... | {
let path = src.as_ref();
if !src.as_ref().exists() {
return Err(io::Error::from(io::ErrorKind::NotFound));
}
if !dest.as_ref().exists() {
fs::create_dir(&dest)?;
}
for entry in path.read_dir()? {
let src = entry.map(|e| e.path())?;
let src_name = match src.file_n... | identifier_body |
fs.rs | use rlua::prelude::*;
use std::{
sync::Arc,
env,
fs::{self, OpenOptions},
io::{self, SeekFrom, prelude::*},
path::Path
};
use serde_json;
use rlua_serde;
use crate::bindings::system::LuaMetadata;
use regex::Regex;
//TODO: Move to having a common interface so IO can share the same binding
pub struct... | <A: AsRef<Path>, B: AsRef<Path>>(src: A, dest: B) -> io::Result<()> {
let path = src.as_ref();
if!src.as_ref().exists() {
return Err(io::Error::from(io::ErrorKind::NotFound));
}
if!dest.as_ref().exists() {
fs::create_dir(&dest)?;
}
for entry in path.read_dir()? {
let src =... | recursive_copy | identifier_name |
fs.rs | use rlua::prelude::*;
use std::{
sync::Arc,
env,
fs::{self, OpenOptions},
io::{self, SeekFrom, prelude::*},
path::Path
};
use serde_json;
use rlua_serde;
use crate::bindings::system::LuaMetadata;
use regex::Regex;
//TODO: Move to having a common interface so IO can share the same binding
pub struct... | fs::OpenOptions::new()
.write(true)
.create(true)
.open(&path)
.map(|_| ())
.map_err(LuaError::external)
})?)?;
module.set("copy_file", lua.create_function(|_, (src, dest): (String, String)| {
copy_file(src, dest)
})?)?;
// This binding has a kno... | //TODO: Rename to something suitable other than touch
//Probably deprecate for path:create_file
module.set("touch", lua.create_function( |_, path: String| { | random_line_split |
resolver.rs | use std::collections::HashMap;
use std::rc::Rc;
use crate::ast::{Expr, Identifier, Literal, Stmt, VisitorMut};
use crate::environment::Environment;
use crate::error::Reporter;
use crate::token::Position;
#[derive(Clone, PartialEq)]
pub enum FunctionKind {
None,
Function,
// TODO: add more kinds supposedly... |
// exit the current scope
pub fn end_scope(&mut self) {
self.scopes.pop();
}
// declare a variable in the current scope
pub fn declare(&mut self, ident: &Identifier) {
// try to access the top element of the stack
match self.scopes.last_mut() {
// if empty, do ... | {
self.scopes.push(HashMap::new());
} | identifier_body |
resolver.rs | use std::collections::HashMap;
use std::rc::Rc;
use crate::ast::{Expr, Identifier, Literal, Stmt, VisitorMut};
use crate::environment::Environment;
use crate::error::Reporter;
use crate::token::Position;
#[derive(Clone, PartialEq)]
pub enum FunctionKind {
None,
Function,
// TODO: add more kinds supposedly... | (&mut self, ident: &Identifier) {
// try to access the top element of the stack
match self.scopes.last_mut() {
// if empty, do nothing (don't worry about global vars)
None => (),
Some(scope) => {
// check if this has already been declared
... | declare | identifier_name |
resolver.rs | use std::collections::HashMap;
use std::rc::Rc;
use crate::ast::{Expr, Identifier, Literal, Stmt, VisitorMut};
use crate::environment::Environment;
use crate::error::Reporter;
use crate::token::Position;
#[derive(Clone, PartialEq)]
pub enum FunctionKind {
None,
Function,
// TODO: add more kinds supposedly... | // variable binding is split into 2 steps - declaring and defining
self.declare(name);
self.visit_expr(expr, env)?;
self.define(name);
}
Stmt::While(ref mut condition_expr, ref mut body) => {
// resolve the condition... | Stmt::Var(name, ref mut expr) => {
// this adds a new entry to the innermost scope | random_line_split |
youtube.rs | use anyhow::{Context, Result};
use chrono::offset::TimeZone;
use log::{debug, trace};
use crate::common::{Service, YoutubeID};
fn api_prefix() -> String |
/*
[
{
title: String,
videoId: String,
author: String,
authorId: String,
authorUrl: String,
videoThumbnails: [
{
quality: String,
url: String,
width: Int32,
height: Int32
}
],
description: String,
descriptionHtml: String,
viewCoun... | {
#[cfg(test)]
let prefix: &str = &mockito::server_url();
#[cfg(not(test))]
let prefix: &str = "https://invidio.us";
prefix.into()
} | identifier_body |
youtube.rs | use anyhow::{Context, Result};
use chrono::offset::TimeZone;
use log::{debug, trace};
use crate::common::{Service, YoutubeID};
fn api_prefix() -> String {
#[cfg(test)]
let prefix: &str = &mockito::server_url();
#[cfg(not(test))]
let prefix: &str = "https://invidio.us";
prefix.into()
}
/*
[
{... | /// Important info about channel
#[derive(Debug)]
pub struct ChannelMetadata {
pub title: String,
pub thumbnail: String,
pub description: String,
}
/// Important info about a video
pub struct VideoInfo {
pub id: String,
pub url: String,
pub title: String,
pub description: String,
pub th... | random_line_split | |
youtube.rs | use anyhow::{Context, Result};
use chrono::offset::TimeZone;
use log::{debug, trace};
use crate::common::{Service, YoutubeID};
fn api_prefix() -> String {
#[cfg(test)]
let prefix: &str = &mockito::server_url();
#[cfg(not(test))]
let prefix: &str = "https://invidio.us";
prefix.into()
}
/*
[
{... |
Ok(new_items) => {
if new_items.len() == 0 {
// No more items, stop iterator
None
} else {
current_items.extend(new_items);
Some(Ok(current... | {
// Error state, prevent future iteration
completed = true;
// Return error
Some(Err(e))
} | conditional_block |
youtube.rs | use anyhow::{Context, Result};
use chrono::offset::TimeZone;
use log::{debug, trace};
use crate::common::{Service, YoutubeID};
fn api_prefix() -> String {
#[cfg(test)]
let prefix: &str = &mockito::server_url();
#[cfg(not(test))]
let prefix: &str = "https://invidio.us";
prefix.into()
}
/*
[
{... | (&self) -> Result<ChannelMetadata> {
let url = format!(
"{prefix}/api/v1/channels/{chanid}",
prefix = api_prefix(),
chanid = self.chan_id.id
);
let d: YTChannelInfo = request_data(&url)?;
Ok(ChannelMetadata {
title: d.author.clone(),
... | get_metadata | identifier_name |
x25519.rs | // -*- mode: rust; -*-
//
// This file is part of x25519-dalek.
// Copyright (c) 2017-2019 isis lovecruft
// Copyright (c) 2019 DebugSteven
// See LICENSE for licensing information.
//
// Authors:
// - isis agora lovecruft <isis@patternsinthevoid.net>
// - DebugSteven <debugsteven@gmail.com>
//! x25519 Diffie-Hellman ... |
}
/// A short-lived Diffie-Hellman secret key that can only be used to compute a single
/// [`SharedSecret`].
///
/// This type is identical to the [`StaticSecret`] type, except that the
/// [`EphemeralSecret::diffie_hellman`] method consumes and then wipes the secret key, and there
/// are no serialization methods d... | {
self.0.as_bytes()
} | identifier_body |
x25519.rs | // -*- mode: rust; -*-
//
// This file is part of x25519-dalek.
// Copyright (c) 2017-2019 isis lovecruft
// Copyright (c) 2019 DebugSteven
// See LICENSE for licensing information.
//
// Authors:
// - isis agora lovecruft <isis@patternsinthevoid.net>
// - DebugSteven <debugsteven@gmail.com>
//! x25519 Diffie-Hellman ... | (bytes: [u8; 32]) -> PublicKey {
PublicKey(MontgomeryPoint(bytes))
}
}
impl PublicKey {
/// Convert this public key to a byte array.
#[inline]
pub fn to_bytes(&self) -> [u8; 32] {
self.0.to_bytes()
}
/// View this public key as a byte array.
#[inline]
pub fn as_bytes(&s... | from | identifier_name |
x25519.rs | // -*- mode: rust; -*-
//
// This file is part of x25519-dalek.
// Copyright (c) 2017-2019 isis lovecruft
// Copyright (c) 2019 DebugSteven
// See LICENSE for licensing information.
//
// Authors:
// - isis agora lovecruft <isis@patternsinthevoid.net>
// - DebugSteven <debugsteven@gmail.com>
//! x25519 Diffie-Hellman ... | }
#[test]
#[cfg(feature = "serde")]
fn serde_bincode_public_key_roundtrip() {
use bincode;
let public_key = PublicKey::from(X25519_BASEPOINT_BYTES);
let encoded = bincode::serialize(&public_key).unwrap();
let decoded: PublicKey = bincode::deserialize(&encoded).unwrap()... | .to_bytes();
assert_eq!(result, expected);
} | random_line_split |
engine.rs | use std::cmp;
use std::mem;
use std::collections::HashMap;
use std::thread::{self, Builder, Thread};
use std::time::Duration;
use std::sync::mpsc::{self, Sender, Receiver};
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::sync::Mutex;
use cpal;
use cpal::UnknownTypeBuff... | (&self) -> (usize, Option<usize>) {
// TODO: slow? benchmark this
let next_hints = self.next.lock().unwrap().iter()
.map(|i| i.size_hint().0).fold(0, |a, b| a + b);
(self.current.size_hint().0 + next_hints, None)
}
}
| size_hint | identifier_name |
engine.rs | use std::cmp;
use std::mem;
use std::collections::HashMap;
use std::thread::{self, Builder, Thread};
use std::time::Duration;
use std::sync::mpsc::{self, Sender, Receiver};
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::sync::Mutex;
use cpal;
use cpal::UnknownTypeBuff... | #[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
// TODO: slow? benchmark this
let next_hints = self.next.lock().unwrap().iter()
.map(|i| i.size_hint().0).fold(0, |a, b| a + b);
(self.current.size_hint().0 + next_hints, None)
}
} | }
}
| random_line_split |
gles2.rs | use std::mem::size_of;
use std::ptr;
use crossfont::RasterizedGlyph;
use log::info;
use alacritty_terminal::term::cell::Flags;
use crate::display::content::RenderableCell;
use crate::display::SizeInfo;
use crate::gl;
use crate::gl::types::*;
use crate::renderer::shader::{ShaderProgram, ShaderVersion};
use crate::ren... | {
tex: GLuint,
vertices: Vec<TextVertex>,
}
impl Batch {
fn new() -> Self {
Self { tex: 0, vertices: Vec::with_capacity(BATCH_MAX) }
}
#[inline]
fn len(&self) -> usize {
self.vertices.len()
}
#[inline]
fn capacity(&self) -> usize {
BATCH_MAX
}
#[i... | Batch | identifier_name |
gles2.rs | use std::mem::size_of;
use std::ptr;
use crossfont::RasterizedGlyph;
use log::info;
use alacritty_terminal::term::cell::Flags;
use crate::display::content::RenderableCell;
use crate::display::SizeInfo;
use crate::gl;
use crate::gl::types::*;
use crate::renderer::shader::{ShaderProgram, ShaderVersion};
use crate::ren... | gl::VertexAttribPointer(
index,
$count,
$gl_type,
gl::FALSE,
size_of::<TextVertex>() as i32,
size as *const _,
);
gl... | macro_rules! add_attr {
($count:expr, $gl_type:expr, $type:ty) => { | random_line_split |
gles2.rs | use std::mem::size_of;
use std::ptr;
use crossfont::RasterizedGlyph;
use log::info;
use alacritty_terminal::term::cell::Flags;
use crate::display::content::RenderableCell;
use crate::display::SizeInfo;
use crate::gl;
use crate::gl::types::*;
use crate::renderer::shader::{ShaderProgram, ShaderVersion};
use crate::ren... | ;
let is_wide = if cell.flags.contains(Flags::WIDE_CHAR) { 2 } else { 1 };
let mut vertex = TextVertex {
x,
y: y + size_info.cell_height() as i16,
glyph_x,
glyph_y: glyph_y + glyph.height,
u: glyph.uv_left,
v: glyph.uv_bot + gly... | {
RenderingGlyphFlags::empty()
} | conditional_block |
gles2.rs | use std::mem::size_of;
use std::ptr;
use crossfont::RasterizedGlyph;
use log::info;
use alacritty_terminal::term::cell::Flags;
use crate::display::content::RenderableCell;
use crate::display::SizeInfo;
use crate::gl;
use crate::gl::types::*;
use crate::renderer::shader::{ShaderProgram, ShaderVersion};
use crate::ren... |
}
impl<'a> LoadGlyph for RenderApi<'a> {
fn load_glyph(&mut self, rasterized: &RasterizedGlyph) -> Glyph {
Atlas::load_glyph(self.active_tex, self.atlas, self.current_atlas, rasterized)
}
fn clear(&mut self) {
Atlas::clear_atlas(self.atlas, self.current_atlas)
}
}
impl<'a> TextRender... | {
if !self.batch.is_empty() {
self.render_batch();
}
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.