hexsha
stringlengths 40
40
| size
int64 4
1.05M
| content
stringlengths 4
1.05M
| avg_line_length
float64 1.33
100
| max_line_length
int64 1
1k
| alphanum_fraction
float64 0.25
1
|
---|---|---|---|---|---|
e54309b7b2dde556fd78a7fd4c375ddd7be5ddac | 883 | use crate::io::IoImpl;
use std::time::Duration;
/// A wrapper around time facilities provided to Laythe
pub struct Time {
time: Box<dyn TimeImpl>,
}
impl Default for Time {
fn default() -> Self {
Self {
time: Box::new(TimeMock()),
}
}
}
impl Time {
/// Create a new wrapper around time
pub fn new(time: Box<dyn TimeImpl>) -> Self {
Self { time }
}
/// Get a duration from the start of the vm startup
pub fn elapsed(&self) -> Result<Duration, String> {
self.time.elapsed()
}
}
pub trait TimeImpl {
fn elapsed(&self) -> Result<Duration, String>;
}
#[derive(Debug)]
pub struct IoTimeMock();
impl IoImpl<Time> for IoTimeMock {
fn make(&self) -> Time {
Time::new(Box::new(TimeMock()))
}
}
pub struct TimeMock();
impl TimeImpl for TimeMock {
fn elapsed(&self) -> Result<Duration, String> {
Ok(Duration::new(3, 14236))
}
}
| 18.020408 | 55 | 0.630804 |
f5e53f84c16e6472dc4b39c3aca8a084cba288e7 | 553 | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn main() { let x = 1 && 2; }
//~^ ERROR mismatched types
//~| ERROR mismatched types
| 39.5 | 68 | 0.723327 |
48cf83c76e3cbc4301dff0fd5e270a626a0c45d4 | 1,326 | use rkyv::{archived_root, Archive, Archived, Deserialize, Infallible};
use std::marker::PhantomData;
/// A wrapper around a byte buffer `B` that denotes the bytes represent an [`Archived<T>`].
///
/// Note: This is not intended for use with archived structures that utilize shared memory like `ArchivedRc` and
/// `ArchivedArc`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ArchivedBuf<T, B> {
bytes: B,
marker: PhantomData<T>,
}
impl<T, B> ArchivedBuf<T, B>
where
T: Archive,
B: AsRef<[u8]>,
{
/// # Safety
///
/// - `bytes` must faithfully represent an [`Archived<T>`]
/// - the same constraints apply as if you were calling [`archived_root`] on `bytes`
pub unsafe fn new(bytes: B) -> Self {
Self {
bytes,
marker: PhantomData,
}
}
pub fn deserialize(&self) -> T
where
T::Archived: Deserialize<T, Infallible>,
{
self.as_ref().deserialize(&mut Infallible).unwrap()
}
pub fn as_bytes(&self) -> &[u8] {
self.bytes.as_ref()
}
pub fn take_bytes(self) -> B {
self.bytes
}
}
impl<T, B> AsRef<Archived<T>> for ArchivedBuf<T, B>
where
T: Archive,
B: AsRef<[u8]>,
{
fn as_ref(&self) -> &Archived<T> {
unsafe { archived_root::<T>(self.bytes.as_ref()) }
}
}
| 24.109091 | 112 | 0.59276 |
6a3d6a0efc697eb2215bf314d2458b3b9c413016 | 3,102 | use std::fmt::Debug;
use crate::magick_rust::MagickWand;
use crate::Crop;
// The general config of an image format.
pub trait ImageConfig: Debug {
fn is_remain_profile(&self) -> bool;
fn get_width(&self) -> u16;
fn get_height(&self) -> u16;
fn get_crop(&self) -> Option<Crop>;
fn get_sharpen(&self) -> f64;
fn is_shrink_only(&self) -> bool;
}
// Compute an appropriate sharpen value for the resized image.
pub(crate) fn compute_output_size_sharpen(
mw: &MagickWand,
config: &impl ImageConfig,
) -> (u16, u16, f64) {
let original_width = mw.get_image_width() as u16;
let original_height = mw.get_image_height() as u16;
let (width, height) = compute_output_size(
config.is_shrink_only(),
original_width,
original_height,
config.get_width(),
config.get_height(),
)
.unwrap_or((original_width, original_height));
let mut adjusted_sharpen = config.get_sharpen();
if adjusted_sharpen < 0f64 {
let origin_pixels = original_width as f64 * original_height as f64;
let resize_pixels = width as f64 * height as f64;
let resize_level = (resize_pixels / 5_000_000f64).sqrt();
let m;
let n = if origin_pixels >= resize_pixels {
m = origin_pixels;
resize_pixels
} else {
m = resize_pixels;
origin_pixels
};
adjusted_sharpen = (resize_level * ((m - n) / m)).min(3f64);
}
(width, height, adjusted_sharpen)
}
#[inline]
pub(crate) fn compute_output_size_if_different(
mw: &MagickWand,
config: &impl ImageConfig,
) -> Option<(u16, u16)> {
compute_output_size(
config.is_shrink_only(),
mw.get_image_width() as u16,
mw.get_image_height() as u16,
config.get_width(),
config.get_height(),
)
}
/// Compute the output size. If it returns `None`, the size remains the same.
pub fn compute_output_size(
shrink_only: bool,
input_width: u16,
input_height: u16,
max_width: u16,
max_height: u16,
) -> Option<(u16, u16)> {
let mut width = max_width;
let mut height = max_height;
if shrink_only {
if width == 0 || width > input_width {
width = input_width;
}
if height == 0 || height > input_height {
height = input_height;
}
} else {
if width == 0 {
width = input_width;
}
if height == 0 {
height = input_height;
}
}
if width == input_width && height == input_height {
return None;
}
let input_width_f64 = f64::from(input_width);
let input_height_f64 = f64::from(input_height);
let width_f64 = f64::from(width);
let height_f64 = f64::from(height);
let ratio = input_width_f64 / input_height_f64;
let wr = input_width_f64 / width_f64;
let hr = input_height_f64 / height_f64;
if wr >= hr {
height = (width_f64 / ratio).round() as u16;
} else {
width = (height_f64 * ratio).round() as u16;
}
Some((width, height))
}
| 26.288136 | 77 | 0.604771 |
db76e39036452539959378e456206c748f09a0a9 | 8,386 | use crossbeam_channel::{self, Receiver, Sender, SendError};
use hdfs_comm::protos::hdfs::DatanodeIdProto;
use shared::NahFSError;
use shared::protos::BlockMetadataProto;
use crate::index::IndexStore;
use std::sync::{Arc, RwLock};
use std::thread::JoinHandle;
static INDEXED_MASK: u64 = 18446744004990074880;
pub enum Operation {
INDEX,
WRITE,
TRANSFER,
}
pub struct BlockOperation {
operation: Operation,
pub bm_proto: BlockMetadataProto,
pub data: Vec<u8>,
pub replicas: Vec<DatanodeIdProto>,
}
impl BlockOperation {
pub fn new(operation: Operation, bm_proto: BlockMetadataProto,
data: Vec<u8>, replicas: Vec<DatanodeIdProto>) -> BlockOperation {
BlockOperation {
operation: operation,
bm_proto: bm_proto,
data: data,
replicas: replicas,
}
}
}
pub struct BlockProcessor {
index_store: Arc<RwLock<IndexStore>>,
thread_count: u8,
data_directory: String,
datanode_id: String,
namenode_ip_address: String,
namenode_port: u16,
operation_channel: (Sender<BlockOperation>,
Receiver<BlockOperation>),
shutdown_channel: (Sender<bool>, Receiver<bool>),
join_handles: Vec<JoinHandle<()>>,
}
impl BlockProcessor {
pub fn new(index_store: Arc<RwLock<IndexStore>>, thread_count: u8,
queue_length: u8, data_directory: String, datanode_id: String,
namenode_ip_address: String, namenode_port: u16) -> BlockProcessor {
BlockProcessor {
index_store: index_store,
thread_count: thread_count,
data_directory: data_directory,
datanode_id: datanode_id,
namenode_ip_address: namenode_ip_address,
namenode_port: namenode_port,
operation_channel: crossbeam_channel
::bounded(queue_length as usize),
shutdown_channel: crossbeam_channel::unbounded(),
join_handles: Vec::new(),
}
}
pub fn add_index(&self, bm_proto: BlockMetadataProto, data: Vec<u8>,
replicas: Vec<DatanodeIdProto>)
-> Result<(), SendError<BlockOperation>> {
let block_op = BlockOperation::new(Operation::INDEX,
bm_proto, data, replicas);
self.operation_channel.0.send(block_op)
}
pub fn add_write(&self, bm_proto: BlockMetadataProto, data: Vec<u8>,
replicas: Vec<DatanodeIdProto>)
-> Result<(), SendError<BlockOperation>> {
let block_op = BlockOperation::new(Operation::WRITE,
bm_proto, data, replicas);
self.operation_channel.0.send(block_op)
}
pub fn read(&self, block_id: u64, offset: u64,
buf: &mut [u8]) -> Result<(), NahFSError> {
super::read_block(block_id, offset, &self.data_directory, buf)
}
pub fn read_indexed(&self, block_id: u64, geohashes: &Vec<u8>,
offset: u64, buf: &mut [u8]) -> Result<(), NahFSError> {
super::read_indexed_block(block_id,
geohashes, offset, &self.data_directory, buf)
}
pub fn start(&mut self) -> Result<(), NahFSError> {
for _ in 0..self.thread_count {
// clone variables
let index_store_clone = self.index_store.clone();
let data_directory_clone = self.data_directory.clone();
let datanode_id_clone = self.datanode_id.clone();
let namenode_ip_address_clone = self.namenode_ip_address.clone();
let namenode_port_clone = self.namenode_port.clone();
let operation_sender = self.operation_channel.0.clone();
let operation_receiver = self.operation_channel.1.clone();
let shutdown_receiver = self.shutdown_channel.1.clone();
let join_handle = std::thread::spawn(move || {
process_loop(index_store_clone,
&operation_sender, &operation_receiver,
&shutdown_receiver, &data_directory_clone,
&datanode_id_clone, &namenode_ip_address_clone,
namenode_port_clone);
});
self.join_handles.push(join_handle);
}
Ok(())
}
/*
// TODO - unused
pub fn stop(mut self) {
// send shutdown messages
for _ in 0..self.join_handles.len() {
self.shutdown_channel.0.send(true).unwrap();
}
// join threads
while self.join_handles.len() != 0 {
let join_handle = self.join_handles.pop().unwrap();
join_handle.join().unwrap();
}
}*/
}
fn process_loop(index_store: Arc<RwLock<IndexStore>>,
operation_sender: &Sender<BlockOperation>,
operation_receiver: &Receiver<BlockOperation>,
shutdown_receiver: &Receiver<bool>, data_directory: &str,
datanode_id: &str, namenode_ip_address: &str, namenode_port: u16) {
loop {
select! {
recv(operation_receiver) -> result => {
// read block operation
if let Err(e) = result {
error!("recv block operation: {}", e);
continue;
}
// process block operation
let mut block_op = result.unwrap();
let process_result = match (&block_op.operation,
&block_op.bm_proto.index) {
(Operation::INDEX, _) =>
index_block(&index_store, &mut block_op),
(Operation::WRITE, _) =>
super::write_block(&block_op.data,
&block_op.bm_proto, &data_directory),
(Operation::TRANSFER, None) =>
super::transfer_block(&block_op.data,
&block_op.replicas, &block_op.bm_proto),
(Operation::TRANSFER, Some(_)) =>
super::transfer_indexed_block(&block_op.data,
&block_op.bm_proto, &datanode_id,
block_op.replicas.len() as u32,
&namenode_ip_address, namenode_port),
};
// check for error
if let Err(e) = process_result {
error!("processing block: {}", e);
continue;
}
// send block operation to next stage
let send_result = match block_op.operation {
Operation::INDEX => {
block_op.operation = Operation::WRITE;
operation_sender.send(block_op)
},
Operation::WRITE => {
if block_op.replicas.len() != 0 {
block_op.operation = Operation::TRANSFER;
operation_sender.send(block_op)
} else {
Ok(())
}
},
Operation::TRANSFER => Ok(()),
};
// check for error
if let Err(e) = send_result {
error!("sending processed block: {}", e);
continue;
}
},
recv(shutdown_receiver) -> _ => break,
}
}
}
fn index_block(index_store: &Arc<RwLock<IndexStore>>,
block_op: &mut BlockOperation) -> Result<(), NahFSError> {
// parse storage_policy_id and get Indexer
let storage_policy_id = block_op.bm_proto.block_id as u32;
let available = {
let index_store = index_store.read().unwrap();
index_store.contains_index(&storage_policy_id)
};
if !available {
let mut index_store = index_store.write().unwrap();
index_store.retrieve_index(&storage_policy_id)?;
}
// retrieve indexer
let index_store = index_store.read().unwrap();
let indexer = index_store.get_index(&storage_policy_id).unwrap();
// index block
let (indexed_data, bi_proto) =
indexer.process(&block_op.data, &block_op.bm_proto)?;
// update BlockOperation
block_op.bm_proto.block_id =
block_op.bm_proto.block_id & INDEXED_MASK;
block_op.bm_proto.index = Some(bi_proto);
block_op.bm_proto.length = indexed_data.len() as u64;
block_op.data = indexed_data;
Ok(())
}
| 35.383966 | 80 | 0.565943 |
8700749f81fc7dd12a7a040ce5e08b0753d19205 | 446 | const THRESHOLD: i32 = 120;
pub struct ScrollAccum {
x: i32,
y: i32,
}
impl Default for ScrollAccum {
fn default() -> Self {
Self { x: 0, y: 0 }
}
}
impl ScrollAccum {
pub fn accumulate(&mut self, x: i32, y: i32) -> (i32, i32) {
self.x += x;
self.y += y;
let result = (self.x / THRESHOLD, self.y / THRESHOLD);
self.x %= THRESHOLD;
self.y %= THRESHOLD;
result
}
}
| 18.583333 | 64 | 0.511211 |
382f73f48e1fed1ada89b8a0891e8dcd0c783ee3 | 3,564 | use crate::util::SendSyncError as Error;
use serde::{Deserialize, Serialize};
use serde_with::{serde_as, DisplayFromStr};
use serenity::{
model::id::{ChannelId, RoleId},
prelude::{RwLock, TypeMapKey},
};
use std::{
collections::{HashMap, HashSet},
fs::File,
sync::Arc,
};
#[serde_as]
#[derive(Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Config {
#[serde(default)]
allowed_channels: HashSet<ChannelId>,
#[serde(default)]
greet_channel: Option<ChannelId>,
#[serde(default)]
greet_message: Option<String>,
#[serde(default)]
log_channel: Option<ChannelId>,
#[serde(default)]
#[serde_as(as = "HashMap<DisplayFromStr, _>")]
user_groups: HashMap<RoleId, String>,
#[serde(default)]
mute_role: Option<RoleId>,
}
const CONFIG: &str = "config.json";
impl Config {
fn serialize(&self) -> Result<(), Error> {
serde_json::to_writer(File::create(CONFIG)?, self).map_err(|e| e.into())
}
pub fn new() -> Result<Self, Error> {
serde_json::from_reader(File::open(CONFIG)?).map_err(|e| e.into())
}
pub fn add_allowed_channel(&mut self, ch: ChannelId) -> Result<(), Error> {
self.allowed_channels.insert(ch);
Config::serialize(self)
}
pub fn channel_is_allowed(&self, ch: ChannelId) -> bool {
self.allowed_channels.contains(&ch)
}
pub fn allowed_channels(&self) -> impl Iterator<Item = &ChannelId> {
self.allowed_channels.iter()
}
pub fn remove_allowed_channel(&mut self, ch: ChannelId) -> Result<(), Error> {
self.allowed_channels.remove(&ch);
Config::serialize(self)
}
pub fn greet_channel(&self) -> Option<ChannelId> {
self.greet_channel
}
pub fn set_greet_channel(
&mut self,
greet_channel: ChannelId,
msg: Option<String>,
) -> Result<(), Error> {
if let Some(msg) = msg.or_else(|| self.greet_message.take()) {
self.greet_message = Some(msg);
self.greet_channel = Some(greet_channel);
Config::serialize(self)
} else {
Err("Provide a greeting for the channel".into())
}
}
pub fn remove_greet_channel(&mut self) -> Result<(), Error> {
self.greet_channel = None;
Config::serialize(self)
}
pub fn greet_channel_message(&self) -> Option<&str> {
self.greet_message.as_ref().map(|s| s.as_str())
}
pub fn set_log_channel(&mut self, ch: Option<ChannelId>) -> Result<(), Error> {
self.log_channel = ch;
Config::serialize(self)
}
pub fn log_channel(&self) -> Option<ChannelId> {
self.log_channel
}
pub fn add_user_group(&mut self, ch: RoleId, desc: String) -> Result<(), Error> {
self.user_groups.insert(ch, desc);
Config::serialize(self)
}
pub fn user_group_exists(&self, ch: RoleId) -> bool {
self.user_groups.contains_key(&ch)
}
pub fn user_groups(&self) -> impl Iterator<Item = (&RoleId, &str)> {
self.user_groups.iter().map(|(r, s)| (r, s.as_str()))
}
pub fn remove_user_group(&mut self, ch: RoleId) -> Result<(), Error> {
self.user_groups.remove(&ch);
Config::serialize(self)
}
pub fn get_mute_role(&self) -> Option<RoleId> {
self.mute_role
}
pub fn set_mute_role(&mut self, rl: RoleId) -> Result<(), Error> {
self.mute_role = Some(rl);
Config::serialize(self)
}
}
impl TypeMapKey for Config {
type Value = Arc<RwLock<Config>>;
}
| 27.84375 | 85 | 0.607183 |
b94af23c630b5cd10991beae7049e5fc534a47bc | 27,212 | use std::io::Write;
use std::io::{ErrorKind, Read};
use std::ops::Range;
use crate::errors::RuntimeError;
use crate::ir::ops::{LoopDecrement, Op, OpType};
use crate::parser::Program;
const MAX_HEAP_SIZE: usize = 16 * 1024 * 1024;
/// Interpreter to execute a program
pub struct Interpreter<R: Read, W: Write> {
max_heap_size: usize,
pub(crate) heap: Vec<u8>,
pointer: usize,
input: R,
output: W,
}
impl<R: Read, W: Write> Interpreter<R, W> {
/// Create a default interpreter
pub fn new(input: R, output: W) -> Interpreter<R, W> {
Interpreter {
max_heap_size: MAX_HEAP_SIZE,
heap: vec![0; 1024],
pointer: 0,
input,
output,
}
}
/// Execute program
pub fn execute(&mut self, program: &Program) -> Result<(), RuntimeError> {
self.execute_ops(&program.ops)
}
fn execute_ops(&mut self, ops: &[Op]) -> Result<(), RuntimeError> {
for op in ops {
self.execute_op(op)?;
}
Ok(())
}
fn execute_op(&mut self, op: &Op) -> Result<(), RuntimeError> {
match &op.op_type {
OpType::Start => {
// ignore
}
OpType::IncPtr(count) => self.pointer = self.pointer.wrapping_add(*count),
OpType::DecPtr(count) => self.pointer = self.pointer.wrapping_sub(*count),
OpType::Inc(offset, count) => {
let value = self.heap_value_at_offset(&op.span, *offset)?;
*value = value.wrapping_add(*count);
}
OpType::Dec(offset, count) => {
let value = self.heap_value_at_offset(&op.span, *offset)?;
*value = value.wrapping_sub(*count);
}
OpType::Set(offset, value) => *self.heap_value_at_offset(&op.span, *offset)? = *value,
OpType::Add(src_offset, dest_offset, multi) => {
let source = *self.heap_value_at_offset(&op.span, *src_offset)?;
let target = self.heap_value_at_offset(&op.span, *dest_offset)?;
*target = target.wrapping_add(source.wrapping_mul(*multi));
*self.heap_value_at_offset(&op.span, *src_offset)? = 0;
}
OpType::NzAdd(src_offset, dest_offset, multi) => {
let source = *self.heap_value_at_offset(&op.span, *src_offset)?;
let target = self.heap_value_at_offset(&op.span, *dest_offset)?;
*target = target.wrapping_add(source.wrapping_mul(*multi));
}
OpType::CAdd(src_offset, dest_offset, value) => {
let target = self.heap_value_at_offset(&op.span, *dest_offset)?;
*target = target.wrapping_add(*value);
*self.heap_value_at_offset(&op.span, *src_offset)? = 0;
}
OpType::NzCAdd(_src_offset, dest_offset, value) => {
let target = self.heap_value_at_offset(&op.span, *dest_offset)?;
*target = target.wrapping_add(*value);
}
OpType::Sub(src_offset, dest_offset, multi) => {
let source = *self.heap_value_at_offset(&op.span, *src_offset)?;
let target = self.heap_value_at_offset(&op.span, *dest_offset)?;
*target = target.wrapping_sub(source.wrapping_mul(*multi));
*self.heap_value_at_offset(&op.span, *src_offset)? = 0;
}
OpType::NzSub(src_offset, dest_offset, multi) => {
let source = *self.heap_value_at_offset(&op.span, *src_offset)?;
let target = self.heap_value_at_offset(&op.span, *dest_offset)?;
*target = target.wrapping_sub(source.wrapping_mul(*multi));
}
OpType::CSub(src_offset, dest_offset, value) => {
let target = self.heap_value_at_offset(&op.span, *dest_offset)?;
*target = target.wrapping_sub(*value);
*self.heap_value_at_offset(&op.span, *src_offset)? = 0;
}
OpType::NzCSub(_src_offset, dest_offset, value) => {
let target = self.heap_value_at_offset(&op.span, *dest_offset)?;
*target = target.wrapping_sub(*value);
}
OpType::Mul(src_offset, dest_offset, multi) => {
let source = *self.heap_value_at_offset(&op.span, *src_offset)?;
let target = self.heap_value_at_offset(&op.span, *dest_offset)?;
*target = source.wrapping_mul(*multi);
*self.heap_value_at_offset(&op.span, *src_offset)? = 0;
}
OpType::NzMul(src_offset, dest_offset, multi) => {
let source = *self.heap_value_at_offset(&op.span, *src_offset)?;
let target = self.heap_value_at_offset(&op.span, *dest_offset)?;
*target = source.wrapping_mul(*multi);
}
OpType::Move(src_offset, dest_offset) => {
let source = *self.heap_value_at_offset(&op.span, *src_offset)?;
let target = self.heap_value_at_offset(&op.span, *dest_offset)?;
*target = source;
*self.heap_value_at_offset(&op.span, *src_offset)? = 0;
}
OpType::Copy(src_offset, dest_offset) => {
let source = *self.heap_value_at_offset(&op.span, *src_offset)?;
let target = self.heap_value_at_offset(&op.span, *dest_offset)?;
*target = source;
}
OpType::GetChar(offset) => self.get_char(&op.span, *offset)?,
OpType::PutChar(offset) => self.put_char(&op.span, *offset)?,
OpType::PutString(array) => self.put_string(&op.span, array)?,
OpType::DLoop(ops, _) => {
while *self.heap_value(&op.span)? > 0 {
self.execute_ops(ops)?;
}
}
OpType::LLoop(ops, _) => {
let heap_pointer = self.pointer;
while *self.heap_value(&op.span)? > 0 {
self.execute_ops(ops)?;
self.pointer = heap_pointer;
}
}
OpType::ILoop(ops, step, decrement, _) => match decrement {
LoopDecrement::Pre => {
let heap_pointer = self.pointer;
let mut left = *self.heap_value(&op.span)?;
while left > 0 {
left = left.wrapping_sub(*step);
*self.heap_value(&op.span)? = left;
self.execute_ops(ops)?;
self.pointer = heap_pointer;
}
*self.heap_value(&op.span)? = 0;
}
LoopDecrement::Post => {
let heap_pointer = self.pointer;
let mut left = *self.heap_value(&op.span)?;
while left > 0 {
self.execute_ops(ops)?;
left = left.wrapping_sub(*step);
*self.heap_value(&op.span)? = left;
self.pointer = heap_pointer;
}
*self.heap_value(&op.span)? = 0;
}
LoopDecrement::Auto => {
let heap_pointer = self.pointer;
let mut left = *self.heap_value(&op.span)?;
while left > 0 {
self.execute_ops(ops)?;
left = left.wrapping_sub(*step);
self.pointer = heap_pointer;
}
*self.heap_value(&op.span)? = 0;
}
},
OpType::CLoop(ops, iterations, decrement, _) => match decrement {
LoopDecrement::Pre => {
let heap_pointer = self.pointer;
*self.heap_value(&op.span)? = *iterations;
let mut left = *self.heap_value(&op.span)?;
while left > 0 {
left = left.wrapping_sub(1);
*self.heap_value(&op.span)? = left;
self.execute_ops(ops)?;
self.pointer = heap_pointer;
}
*self.heap_value(&op.span)? = 0;
}
LoopDecrement::Post => {
let heap_pointer = self.pointer;
*self.heap_value(&op.span)? = *iterations;
let mut left = *self.heap_value(&op.span)?;
while left > 0 {
self.execute_ops(ops)?;
self.pointer = heap_pointer;
left = left.wrapping_sub(1);
*self.heap_value(&op.span)? = left;
}
*self.heap_value(&op.span)? = 0;
}
LoopDecrement::Auto => {
let heap_pointer = self.pointer;
for _ in 0..*iterations {
self.execute_ops(ops)?;
self.pointer = heap_pointer;
}
*self.heap_value(&op.span)? = 0;
}
},
OpType::TNz(ops, _) => {
if *self.heap_value(&op.span)? != 0 {
let heap_pointer = self.pointer;
self.execute_ops(ops)?;
self.pointer = heap_pointer;
*self.heap_value(&op.span)? = 0;
}
}
OpType::DTNz(ops, _, _) => {
if *self.heap_value(&op.span)? > 0 {
self.execute_ops(ops)?;
}
}
OpType::SearchZero(step, _) => {
let mut pointer = self.pointer as isize;
loop {
let value = self.heap_value_at(&op.span, pointer)?;
if *value == 0 {
break;
}
pointer += step;
}
self.pointer = pointer as usize;
}
}
Ok(())
}
fn heap_value(&mut self, span: &Range<usize>) -> Result<&mut u8, RuntimeError> {
if self.pointer >= self.max_heap_size {
return Err(RuntimeError::MaxHeapSizeReached {
span: span.clone(),
max_heap_size: self.max_heap_size,
required: self.pointer.saturating_add(1),
});
}
while self.pointer > self.heap.len() - 1 {
self.heap.push(0);
}
Ok(&mut self.heap[self.pointer])
}
fn heap_value_at(
&mut self,
span: &Range<usize>,
pointer: isize,
) -> Result<&mut u8, RuntimeError> {
let pointer = pointer.max(0) as usize;
if pointer >= self.max_heap_size {
return Err(RuntimeError::MaxHeapSizeReached {
span: span.clone(),
max_heap_size: self.max_heap_size,
required: self.pointer.saturating_add(1),
});
}
while pointer > self.heap.len() - 1 {
self.heap.push(0);
}
Ok(&mut self.heap[pointer])
}
fn heap_value_at_offset(
&mut self,
span: &Range<usize>,
ptr_offset: isize,
) -> Result<&mut u8, RuntimeError> {
let pointer = self.pointer as isize + ptr_offset;
let pointer = pointer.max(0) as usize;
if pointer >= self.max_heap_size {
return Err(RuntimeError::MaxHeapSizeReached {
span: span.clone(),
max_heap_size: self.max_heap_size,
required: self.pointer.saturating_add(1),
});
}
while pointer > self.heap.len() - 1 {
self.heap.push(0);
}
Ok(&mut self.heap[pointer])
}
fn get_char(&mut self, span: &Range<usize>, offset: isize) -> Result<(), RuntimeError> {
let mut buf = [0];
if let Err(error) = self.input.read_exact(&mut buf) {
// In case of EOF the system will read 0 as a fallback
if error.kind() != ErrorKind::UnexpectedEof {
return Err(RuntimeError::IoError {
span: span.clone(),
error,
});
}
};
*self.heap_value_at_offset(span, offset)? = buf[0];
Ok(())
}
fn put_char(&mut self, span: &Range<usize>, offset: isize) -> Result<(), RuntimeError> {
let ch = *self.heap_value_at_offset(span, offset)?;
if ch.is_ascii() {
write!(self.output, "{}", ch as char)
} else {
write!(self.output, "\\0x{:x}", ch)
}
.map_err(|error| RuntimeError::IoError {
span: span.clone(),
error,
})
}
fn put_string(&mut self, span: &Range<usize>, array: &[u8]) -> Result<(), RuntimeError> {
for &ch in array {
if ch.is_ascii() {
write!(self.output, "{}", ch as char)
} else {
write!(self.output, "\\0x{:x}", ch)
}
.map_err(|error| RuntimeError::IoError {
span: span.clone(),
error,
})?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::io::Cursor;
use crate::backends::interpreter::Interpreter;
use crate::ir::ops::{LoopDecrement, Op};
use crate::ir::opt_info::BlockInfo;
use crate::parser::parse;
use crate::{optimize_with_config, OptimizeConfig, Program};
#[test]
fn test_out_1() {
let mut program = parse(">+.").unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = b"";
let mut output = Vec::new();
Interpreter::new(Cursor::new(input), &mut output)
.execute(&program)
.unwrap();
assert_eq!(output, b"\x01");
}
#[test]
fn test_out_b() {
let mut program = parse(",++.").unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = b"a";
let mut output = Vec::new();
Interpreter::new(Cursor::new(input), &mut output)
.execute(&program)
.unwrap();
assert_eq!(output, b"c");
}
#[test]
fn test_loop() {
let mut program = parse("+++[>+<-]>.").unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = b"";
let mut output = Vec::new();
Interpreter::new(Cursor::new(input), &mut output)
.execute(&program)
.unwrap();
assert_eq!(output, b"\x03");
}
#[test]
fn test_hello_world() {
let mut program = parse(
"
>+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.[-]
>++++++++[<++++>-] <.>+++++++++++[<++++++++>-]<-.--------.+++
.------.--------.[-]>++++++++[<++++>- ]<+.[-]++++++++++.",
)
.unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = b"";
let mut output = Vec::new();
Interpreter::new(Cursor::new(input), &mut output)
.execute(&program)
.unwrap();
assert_eq!(output, b"Hello world!\n");
}
#[test]
fn test_hello_world_v2() {
let mut program = parse(include_str!("../../../test_programs/hello_world.bf")).unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = b"";
let mut output = Vec::new();
Interpreter::new(Cursor::new(input), &mut output)
.execute(&program)
.unwrap();
assert_eq!(output, b"Hello World!\n");
}
#[test]
fn test_count_loop() {
let mut program = parse("++++[->++<]").unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = b"";
let mut output = Vec::new();
let mut interpreter = Interpreter::new(Cursor::new(input), &mut output);
interpreter.execute(&program).unwrap();
assert_eq!(interpreter.heap[0], 0);
assert_eq!(interpreter.heap[1], 8);
}
#[test]
fn test_count_loop_inv() {
let mut program = parse("++++[->++<]").unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = b"";
let mut output = Vec::new();
let mut interpreter = Interpreter::new(Cursor::new(input), &mut output);
interpreter.execute(&program).unwrap();
assert_eq!(interpreter.heap[0], 0);
assert_eq!(interpreter.heap[1], 8);
}
#[test]
fn test_totally_empty() {
let mut program = parse("").unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = b"";
let mut output = Vec::new();
let mut interpreter = Interpreter::new(Cursor::new(input), &mut output);
interpreter.execute(&program).unwrap();
assert_eq!(interpreter.heap[0], 0);
}
#[test]
fn test_optimized_empty() {
let mut program = parse("[>+++++<-]").unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = b"";
let mut output = Vec::new();
let mut interpreter = Interpreter::new(Cursor::new(input), &mut output);
interpreter.execute(&program).unwrap();
assert_eq!(interpreter.heap[0], 0);
}
#[test]
fn test_multiply() {
let mut program = parse(">>++<<++[>+++++<-]").unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = b"";
let mut output = Vec::new();
let mut interpreter = Interpreter::new(Cursor::new(input), &mut output);
interpreter.execute(&program).unwrap();
assert_eq!(interpreter.heap[0], 0);
assert_eq!(interpreter.heap[1], 10);
}
#[test]
fn test_divide() {
let mut program = parse(">>++<<++++++++++++[>+<---]").unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = b"";
let mut output = Vec::new();
let mut interpreter = Interpreter::new(Cursor::new(input), &mut output);
interpreter.execute(&program).unwrap();
assert_eq!(interpreter.heap[0], 0);
assert_eq!(interpreter.heap[1], 4);
}
#[test]
fn test_pow_5_3() {
let mut program = parse("+++++[>+++++[>+++++<-]<-]").unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = b"";
let mut output = Vec::new();
let mut interpreter = Interpreter::new(Cursor::new(input), &mut output);
interpreter.execute(&program).unwrap();
assert_eq!(interpreter.heap[0], 0);
assert_eq!(interpreter.heap[1], 0);
assert_eq!(interpreter.heap[2], 125);
}
#[test]
fn test_bad_count_loop() {
let mut program = parse("++++++++[---->+<++]").unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = b"";
let mut output = Vec::new();
let mut interpreter = Interpreter::new(Cursor::new(input), &mut output);
interpreter.execute(&program).unwrap();
assert_eq!(interpreter.heap[0], 0);
assert_eq!(interpreter.heap[1], 4);
}
#[test]
fn test_conditional_set() {
let mut program = parse("+>>++<<[->[-]++++++<]").unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = b"";
let mut output = Vec::new();
let mut interpreter = Interpreter::new(Cursor::new(input), &mut output);
interpreter.execute(&program).unwrap();
assert_eq!(interpreter.heap[0], 0);
assert_eq!(interpreter.heap[1], 6);
assert_eq!(interpreter.heap[2], 2);
}
#[test]
fn test_overwrite_prev_set() {
let mut program = parse("++++[-]++").unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = b"";
let mut output = Vec::new();
let mut interpreter = Interpreter::new(Cursor::new(input), &mut output);
interpreter.execute(&program).unwrap();
assert_eq!(interpreter.heap[0], 2);
}
#[test]
fn test_hello_fizz() {
let mut program = parse(include_str!("../../../test_programs/fizz.bf")).unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = b"";
let mut output = Vec::new();
Interpreter::new(Cursor::new(input), &mut output)
.execute(&program)
.unwrap();
assert_eq!(output, b"1W\n");
}
#[test]
fn test_hello_fizzbuzz() {
let mut program = parse(include_str!("../../../test_programs/fizzbuzz.bf")).unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = b"";
let mut output = Vec::new();
Interpreter::new(Cursor::new(input), &mut output)
.execute(&program)
.unwrap();
assert_eq!(output, b"987654321");
}
#[test]
fn test_bottles() {
let mut program = parse(include_str!("../../../test_programs/bottles.bf")).unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = b"";
let mut output = Vec::new();
Interpreter::new(Cursor::new(input), &mut output)
.execute(&program)
.unwrap();
assert_eq!(
output,
include_bytes!("../../../test_programs/bottles.bf.out")
);
}
#[test]
fn test_factor() {
let mut program = parse(include_str!("../../../test_programs/factor.bf")).unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = include_bytes!("../../../test_programs/factor.bf.in");
let mut output = Vec::new();
Interpreter::new(Cursor::new(input), &mut output)
.execute(&program)
.unwrap();
assert_eq!(
output,
include_bytes!("../../../test_programs/factor.bf.out")
);
}
#[test]
fn test_life() {
let mut program = parse(include_str!("../../../test_programs/life.bf")).unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = include_bytes!("../../../test_programs/life.bf.in");
let mut output = Vec::new();
Interpreter::new(Cursor::new(input), &mut output)
.execute(&program)
.unwrap();
assert_eq!(output, include_bytes!("../../../test_programs/life.bf.out"));
}
#[test]
fn test_test_io() {
let mut program = parse(",[.,]").unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = b"0123456789aZ";
let mut output = Vec::new();
Interpreter::new(Cursor::new(input), &mut output)
.execute(&program)
.unwrap();
assert_eq!(output, b"0123456789aZ");
}
#[test]
fn test_cell_size() {
let mut program = parse(include_str!("../../../test_programs/cell_size.bf")).unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = b"";
let mut output = Vec::new();
Interpreter::new(Cursor::new(input), &mut output)
.execute(&program)
.unwrap();
assert_eq!(output, b"8 bit cells\n");
}
#[test]
fn test_awib() {
let mut program = parse(include_str!("../../../test_programs/awib.bf")).unwrap();
optimize_with_config(&mut program, &OptimizeConfig::o3());
let input = include_bytes!("../../../test_programs/mandelbrot.bf");
let mut output = Vec::new();
Interpreter::new(Cursor::new(input), &mut output)
.execute(&program)
.unwrap();
assert_eq!(
output,
include_bytes!("../../../test_programs/mandelbrot.c")
);
}
#[test]
fn test_i_loop_pre() {
let program = Program {
ops: vec![
Op::set(0..1, 5),
Op::i_loop_with_decrement(
1..4,
vec![
Op::inc_ptr(1..2, 1),
Op::inc(1..2, 1),
Op::dec_ptr(1..2, 1),
Op::put_char(1..2),
],
1,
LoopDecrement::Pre,
BlockInfo::new_empty(),
),
],
};
let input = b"";
let mut output = Vec::new();
let mut interpreter = Interpreter::new(Cursor::new(input), &mut output);
interpreter.execute(&program).unwrap();
assert_eq!(interpreter.heap[0], 0);
assert_eq!(interpreter.heap[1], 5);
assert_eq!(&output, &[4, 3, 2, 1, 0]);
}
#[test]
fn test_i_loop_post() {
let program = Program {
ops: vec![
Op::set(0..1, 5),
Op::i_loop_with_decrement(
1..4,
vec![Op::put_char(1..2)],
1,
LoopDecrement::Post,
BlockInfo::new_empty(),
),
],
};
let input = b"";
let mut output = Vec::new();
let mut interpreter = Interpreter::new(Cursor::new(input), &mut output);
interpreter.execute(&program).unwrap();
assert_eq!(interpreter.heap[0], 0);
assert_eq!(&output, &[5, 4, 3, 2, 1]);
}
#[test]
fn test_c_loop_pre() {
let program = Program {
ops: vec![Op::c_loop_with_decrement(
1..4,
vec![
Op::inc_ptr(1..2, 1),
Op::inc(1..2, 1),
Op::dec_ptr(1..2, 1),
Op::put_char(1..2),
],
5,
LoopDecrement::Pre,
BlockInfo::new_empty(),
)],
};
let input = b"";
let mut output = Vec::new();
let mut interpreter = Interpreter::new(Cursor::new(input), &mut output);
interpreter.execute(&program).unwrap();
assert_eq!(interpreter.heap[0], 0);
assert_eq!(interpreter.heap[1], 5);
assert_eq!(&output, &[4, 3, 2, 1, 0]);
}
#[test]
fn test_c_loop_post() {
let program = Program {
ops: vec![Op::c_loop_with_decrement(
1..4,
vec![Op::put_char(1..2)],
5,
LoopDecrement::Post,
BlockInfo::new_empty(),
)],
};
let input = b"";
let mut output = Vec::new();
let mut interpreter = Interpreter::new(Cursor::new(input), &mut output);
interpreter.execute(&program).unwrap();
assert_eq!(interpreter.heap[0], 0);
assert_eq!(&output, &[5, 4, 3, 2, 1]);
}
}
| 32.20355 | 98 | 0.495664 |
5013c4ebc74015db11951afa7a02fbe4d7a7b6f1 | 110 | pub mod io;
pub use io::MidiIn;
pub mod msg;
pub use msg::Msg;
pub mod port;
pub use port::{PortNb, Ports};
| 12.222222 | 30 | 0.672727 |
eb9336ceb1534d0930f9573884b881e63197f23e | 2,523 | /// 初項 `a`, 項数 `n`, 公差 `d` の等差数列の和を求めます。
///
/// # Panics
/// if `n` is negative or zero.
///
/// # Examples
/// ```
/// use arithmetic_series::arithmetic_series;
///
/// // 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
/// assert_eq!(arithmetic_series(1, 10, 1), Some(55));
/// // 1 + 3 + 5 + 7 + 9
/// assert_eq!(arithmetic_series(1, 5, 2), Some(25));
/// // 5 + 2 + (-1) + (-4) + (-7) + (-10)
/// assert_eq!(arithmetic_series(5, 6, -3), Some(-15));
/// ```
pub fn arithmetic_series<T: Int>(a: T, n: T, d: T) -> Option<T> {
assert!(n.is_positive());
let last = d.checked_mul(n.decrement())?.checked_add(a)?;
a.checked_add(last)?.checked_mul(n)?.checked_div(T::two())
}
pub trait Int: Copy + Ord {
fn is_positive(self) -> bool;
fn decrement(self) -> Self;
fn checked_add(self, rhs: Self) -> Option<Self>;
fn checked_mul(self, rhs: Self) -> Option<Self>;
fn checked_div(self, rhs: Self) -> Option<Self>;
fn two() -> Self;
}
macro_rules! impl_int {
($($t:ty),+) => {
$(
impl Int for $t {
fn is_positive(self) -> bool {
self >= 1
}
fn decrement(self) -> Self {
self - 1
}
fn checked_add(self, rhs: Self) -> Option<Self> {
self.checked_add(rhs)
}
fn checked_mul(self, rhs: Self) -> Option<Self> {
self.checked_mul(rhs)
}
fn checked_div(self, rhs: Self) -> Option<Self> {
self.checked_div(rhs)
}
fn two() -> Self {
2
}
}
)+
};
}
impl_int!(i32, i64, u32, u64, usize);
#[cfg(test)]
mod tests {
use crate::arithmetic_series;
#[test]
fn test_sum_of_1_2_3_to_10() {
assert_eq!(arithmetic_series(1, 10, 1), Some(55));
}
#[test]
fn test_single() {
assert_eq!(arithmetic_series(42, 1, 3), Some(42));
}
#[test]
fn test_decrease_sequence() {
assert_eq!(
arithmetic_series(8, 6, -3),
Some(8 + 5 + 2 + (-1) + (-4) + (-7))
);
}
#[test]
fn test_too_large() {
assert_eq!(arithmetic_series(1, std::i64::MAX, 1), None);
}
#[test]
#[should_panic]
fn test_empty() {
arithmetic_series(42, 0, 3);
}
#[test]
#[should_panic]
fn test_negative_length() {
arithmetic_series(42, -4, 3);
}
}
| 25.23 | 65 | 0.474832 |
33a1669c44fb0229f928147bbe79909eee321d75 | 9,466 | use crate::protocol::util;
// use serde::Serialize;
/// ID of the value type of a database column or a parameter.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
pub enum TypeId {
/// For database type TINYINT;
/// used with [`HdbValue::TINYINT`](crate::HdbValue::TINYINT).
TINYINT = 1,
/// For database type SMALLINT;
/// used with [`HdbValue::SMALLINT`](crate::HdbValue::SMALLINT).
SMALLINT = 2,
/// For database type INT;
/// used with [`HdbValue::INT`](crate::HdbValue::INT).
INT = 3,
/// For database type BIGINT;
/// used with [`HdbValue::BIGINT`](crate::HdbValue::BIGINT).
BIGINT = 4,
/// For database type DECIMAL and SMALLDECIMAL;
/// used with [`HdbValue::DECIMAL`](crate::HdbValue::DECIMAL).
DECIMAL = 5,
/// For database type REAL;
/// used with [`HdbValue::REAL`](crate::HdbValue::REAL).
REAL = 6,
/// For database type DOUBLE;
/// used with [`HdbValue::DOUBLE`](crate::HdbValue::DOUBLE).
DOUBLE = 7,
/// For database type CHAR;
/// used with [`HdbValue::STRING`](crate::HdbValue::STRING).
CHAR = 8,
/// For database type VARCHAR;
/// used with [`HdbValue::STRING`](crate::HdbValue::STRING).
VARCHAR = 9,
/// For database type NCHAR;
/// used with [`HdbValue::STRING`](crate::HdbValue::STRING).
NCHAR = 10,
/// For database type NVARCHAR;
/// used with [`HdbValue::STRING`](crate::HdbValue::STRING).
NVARCHAR = 11,
/// For database type BINARY;
/// used with [`HdbValue::BINARY`](crate::HdbValue::BINARY).
BINARY = 12,
/// For database type VARBINARY;
/// used with [`HdbValue::BINARY`](crate::HdbValue::BINARY).
VARBINARY = 13,
/// For database type CLOB;
/// used with [`HdbValue::CLOB`](crate::HdbValue::CLOB).
CLOB = 25,
/// For database type NCLOB;
/// used with [`HdbValue::NCLOB`](crate::HdbValue::NCLOB).
NCLOB = 26,
/// For database type BLOB;
/// used with [`HdbValue::BLOB`](crate::HdbValue::BLOB).
BLOB = 27,
/// For database type BOOLEAN;
/// used with [`HdbValue::BOOLEAN`](crate::HdbValue::BOOLEAN).
BOOLEAN = 28,
/// For database type STRING;
/// used with [`HdbValue::STRING`](crate::HdbValue::STRING).
STRING = 29,
/// For database type NSTRING;
/// used with [`HdbValue::STRING`](crate::HdbValue::STRING).
NSTRING = 30,
/// Maps to [`HdbValue::BINARY`](crate::HdbValue::BINARY)
/// or [`HdbValue::BLOB`](crate::HdbValue::BLOB).
BLOCATOR = 31,
/// Used with [`HdbValue::BINARY`](crate::HdbValue::BINARY).
BSTRING = 33,
/// For database type TEXT.
TEXT = 51,
/// For database type SHORTTEXT;
/// used with [`HdbValue::STRING`](crate::HdbValue::STRING).
SHORTTEXT = 52,
/// For database type BINTEXT;
/// Used with [`HdbValue::BINARY`](crate::HdbValue::BINARY) or
/// [`HdbValue::BLOB`](crate::HdbValue::BLOB).
BINTEXT = 53,
/// For database type ALPHANUM;
/// used with [`HdbValue::STRING`](crate::HdbValue::STRING).
ALPHANUM = 55,
/// For database type LONGDATE;
/// used with [`HdbValue::LONGDATE`](crate::HdbValue::LONGDATE).
LONGDATE = 61,
/// For database type SECONDDATE;
/// used with [`HdbValue::SECONDDATE`](crate::HdbValue::SECONDDATE).
SECONDDATE = 62,
/// For database type DAYDATE;
/// used with [`HdbValue::DAYDATE`](crate::HdbValue::DAYDATE).
DAYDATE = 63,
/// For database type SECONDTIME;
/// used with [`HdbValue::SECONDTIME`](crate::HdbValue::SECONDTIME).
SECONDTIME = 64,
/// For database type GEOMETRY;
/// used with [`HdbValue::GEOMETRY`](crate::HdbValue::GEOMETRY).
GEOMETRY = 74,
/// For database type POINT;
/// used with [`HdbValue::POINT`](crate::HdbValue::POINT).
POINT = 75,
/// Transport format for database type DECIMAL;
/// used with [`HdbValue::DECIMAL`](crate::HdbValue::DECIMAL).
FIXED8 = 81,
/// Transport format for database type DECIMAL;
/// used with [`HdbValue::DECIMAL`](crate::HdbValue::DECIMAL).
FIXED12 = 82,
/// Transport format for database type DECIMAL;
/// used with [`HdbValue::DECIMAL`](crate::HdbValue::DECIMAL).
FIXED16 = 76,
}
impl TypeId {
pub(crate) fn try_new(id: u8) -> std::io::Result<Self> {
Ok(match id {
1 => Self::TINYINT,
2 => Self::SMALLINT,
3 => Self::INT,
4 => Self::BIGINT,
5 => Self::DECIMAL,
6 => Self::REAL,
7 => Self::DOUBLE,
8 => Self::CHAR,
9 => Self::VARCHAR,
10 => Self::NCHAR,
11 => Self::NVARCHAR,
12 => Self::BINARY,
13 => Self::VARBINARY,
// DATE: 14, TIME: 15, TIMESTAMP: 16 (all deprecated with protocol version 3)
// 17 - 24: reserved, do not use
25 => Self::CLOB,
26 => Self::NCLOB,
27 => Self::BLOB,
28 => Self::BOOLEAN,
29 => Self::STRING,
30 => Self::NSTRING,
31 => Self::BLOCATOR,
// 32 => Self::NLOCATOR,
33 => Self::BSTRING,
// 34 - 46: docu unclear, likely unused
// 47 => SMALLDECIMAL not needed on client-side
// 48, 49: ABAP only?
// ARRAY: 50 TODO not yet implemented
51 => Self::TEXT,
52 => Self::SHORTTEXT,
53 => Self::BINTEXT,
// 54: Reserved, do not use
55 => Self::ALPHANUM,
// 56: Reserved, do not use
// 57 - 60: not documented
61 => Self::LONGDATE,
62 => Self::SECONDDATE,
63 => Self::DAYDATE,
64 => Self::SECONDTIME,
// 65 - 80: Reserved, do not use
// TypeCode_CLOCATOR =70, // TODO
// TypeCode_BLOB_DISK_RESERVED =71,
// TypeCode_CLOB_DISK_RESERVED =72,
// TypeCode_NCLOB_DISK_RESERVE =73,
74 => Self::GEOMETRY,
75 => Self::POINT,
76 => Self::FIXED16,
// TypeCode_ABAP_ITAB =77, // TODO
// TypeCode_RECORD_ROW_STORE = 78, // TODO
// TypeCode_RECORD_COLUMN_STORE = 79, // TODO
81 => Self::FIXED8,
82 => Self::FIXED12,
// TypeCode_CIPHERTEXT = 90, // TODO
tc => return Err(util::io_error(format!("Illegal type code {}", tc))),
})
}
// hdb protocol uses ids < 128 for non-null values, and ids > 128 for nullable values
pub(crate) fn type_code(self, nullable: bool) -> u8 {
(if nullable { 128 } else { 0 }) + self as u8
}
pub(crate) fn matches_value_type(self, value_type: Self) -> std::io::Result<()> {
if value_type == self {
return Ok(());
}
// From To Conversions
#[allow(clippy::match_same_arms)]
match (value_type, self) {
(Self::BOOLEAN, Self::TINYINT | Self::SMALLINT | Self::INT | Self::BIGINT) => {
return Ok(())
}
// no clear strategy for GEO stuff yet, so be restrictive
(Self::STRING, Self::GEOMETRY | Self::POINT) => {}
(Self::STRING, _) => return Ok(()), // Allow all other cases
(
Self::BINARY,
Self::BLOB | Self::BLOCATOR | Self::VARBINARY | Self::GEOMETRY | Self::POINT,
)
| (Self::DECIMAL, Self::FIXED8 | Self::FIXED12 | Self::FIXED16) => return Ok(()),
_ => {}
}
Err(util::io_error(format!(
"value type id {:?} does not match metadata {:?}",
value_type, self
)))
}
}
impl std::fmt::Display for TypeId {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
fmt,
"{}",
match self {
Self::TINYINT => "TINYINT",
Self::SMALLINT => "SMALLINT",
Self::INT => "INT",
Self::BIGINT => "BIGINT",
Self::DECIMAL => "DECIMAL",
Self::REAL => "REAL",
Self::DOUBLE => "DOUBLE",
Self::CHAR => "CHAR",
Self::VARCHAR => "VARCHAR",
Self::NCHAR => "NCHAR",
Self::NVARCHAR => "NVARCHAR",
Self::BINARY => "BINARY",
Self::VARBINARY => "VARBINARY",
Self::CLOB => "CLOB",
Self::NCLOB => "NCLOB",
Self::BLOB => "BLOB",
Self::BOOLEAN => "BOOLEAN",
Self::STRING => "STRING",
Self::NSTRING => "NSTRING",
Self::BLOCATOR => "BLOCATOR",
Self::BSTRING => "BSTRING",
Self::TEXT => "TEXT",
Self::SHORTTEXT => "SHORTTEXT",
Self::BINTEXT => "BINTEXT",
Self::ALPHANUM => "ALPHANUM",
Self::LONGDATE => "LONGDATE",
Self::SECONDDATE => "SECONDDATE",
Self::DAYDATE => "DAYDATE",
Self::SECONDTIME => "SECONDTIME",
Self::GEOMETRY => "GEOMETRY",
Self::POINT => "POINT",
Self::FIXED16 => "FIXED16",
Self::FIXED8 => "FIXED8",
Self::FIXED12 => "FIXED12",
}
)
}
}
| 37.713147 | 93 | 0.517748 |
0e186e6f29ce6636f4c6b669e913229941d4a282 | 580 | // if1.rs
// I AM DONE 2021-05-04 by stphnsmpsn
pub fn bigger(a: i32, b: i32) -> i32 {
if a > b {a}
else {b}
// Complete this function to return the bigger number!
// Do not use:
// - another function call
// - additional variables
// Execute `rustlings hint if1` for hints
}
// Don't mind this for now :)
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ten_is_bigger_than_eight() {
assert_eq!(10, bigger(10, 8));
}
#[test]
fn fortytwo_is_bigger_than_thirtytwo() {
assert_eq!(42, bigger(32, 42));
}
}
| 19.333333 | 58 | 0.577586 |
718a3db6ed789d5cab8bbe742dadee9384aa223e | 611 | use crate::units::altitude::Altitude;
use crate::units::water_density::WaterDensity;
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "use-serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Environment {
water_density: WaterDensity,
altitude: Altitude,
}
impl Environment {
pub fn new(water_density: WaterDensity, altitude: Altitude) -> Self {
Self {
water_density,
altitude,
}
}
pub fn water_density(&self) -> WaterDensity {
self.water_density
}
pub fn altitude(&self) -> Altitude {
self.altitude
}
}
| 22.62963 | 80 | 0.635025 |
d5c66f862077b4d1331efe789090c445ca5d5967 | 1,592 | use std::io::Result;
use std::path::PathBuf;
fn delinkify(path: &PathBuf) -> PathBuf {
let mut delinked = PathBuf::new();
for comp in path.components() {
delinked.push(comp);
/* make sure that `delinked` isn't a link */
while let Ok(target) = std::fs::read_link(&delinked) {
delinked = target;
}
}
delinked
}
fn path() -> Result<String> {
let current = delinkify(&std::env::current_dir()?)
.to_string_lossy()
.to_string();
let home = delinkify(&dirs::home_dir().unwrap())
.to_string_lossy()
.to_string();
let result = if current.starts_with(&home) {
current.replacen(&home, "~", 1)
} else {
current
};
Ok(result)
}
fn emoji(username: &str) -> &'static str {
if username == "root" {
"🔥"
} else {
"🚀"
}
}
fn print_prompt_fallible() -> Result<()> {
use colored::*;
let username = whoami::username();
let hostname = whoami::hostname();
let path = path()?;
let emoji = emoji(&username);
control::set_override(true);
println!(
"{user}{at}{host}{colon}{path} {emoji} ",
user = username.bright_green().bold(),
at = "@".bright_green().bold(),
host = hostname.bright_green().bold(),
colon = ":".white().bold(),
path = path.cyan().bold(),
emoji = emoji,
);
Ok(())
}
fn print_prompt_infallible() {
println!("[ps1 failed] $");
}
fn main() {
if let Err(_) = print_prompt_fallible() {
print_prompt_infallible();
}
}
| 21.513514 | 62 | 0.537688 |
76430ae8786516a313f7f9b4bdf693bd74b172ec | 7,899 | // Unless explicitly stated otherwise all files in this repository are licensed under the
// MIT/Apache-2.0 License, at your convenience
//
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2020 Datadog, Inc.
//
use crate::sys::{self, DmaBuffer, Source, SourceType};
use crate::{ByteSliceMutExt, Local, Reactor};
use std::cell::Cell;
use std::io;
use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
use std::rc::{Rc, Weak};
const DEFAULT_BUFFER_SIZE: usize = 8192;
#[derive(Debug)]
pub struct GlommioDatagram<S: AsRawFd + FromRawFd + From<socket2::Socket>> {
pub(crate) reactor: Weak<Reactor>,
pub(crate) socket: S,
// you only live once, you've got no time to block! if this is set to true try a direct non-blocking syscall otherwise schedule for sending later over the ring
//
// If you are familiar with high throughput networking code you might have seen similar
// techniques with names such as "optimistic" "speculative" or things like that. But frankly "yolo" is such a
// better name. Calling this "yolo" is likely glommio's biggest contribution to humankind.
pub(crate) tx_yolo: Cell<bool>,
pub(crate) rx_yolo: Cell<bool>,
pub(crate) rx_buf_size: usize,
}
impl<S: AsRawFd + FromRawFd + From<socket2::Socket>> From<socket2::Socket> for GlommioDatagram<S> {
fn from(socket: socket2::Socket) -> GlommioDatagram<S> {
let socket = socket.into();
GlommioDatagram {
reactor: Rc::downgrade(&Local::get_reactor()),
socket,
tx_yolo: Cell::new(true),
rx_yolo: Cell::new(true),
rx_buf_size: DEFAULT_BUFFER_SIZE,
}
}
}
impl<S: AsRawFd + FromRawFd + From<socket2::Socket>> AsRawFd for GlommioDatagram<S> {
fn as_raw_fd(&self) -> RawFd {
self.socket.as_raw_fd()
}
}
impl<S: FromRawFd + AsRawFd + From<socket2::Socket>> FromRawFd for GlommioDatagram<S> {
unsafe fn from_raw_fd(fd: RawFd) -> Self {
let socket = socket2::Socket::from_raw_fd(fd);
GlommioDatagram::from(socket)
}
}
impl<S: AsRawFd + FromRawFd + From<socket2::Socket>> GlommioDatagram<S> {
async fn consume_receive_buffer(&self, source: &Source, buf: &mut [u8]) -> io::Result<usize> {
let sz = source.collect_rw().await?;
let src = match source.extract_source_type() {
SourceType::SockRecv(mut buf) => {
let mut buf = buf.take().unwrap();
buf.trim_to_size(sz);
buf
}
_ => unreachable!(),
};
buf[0..sz].copy_from_slice(&src.as_bytes()[0..sz]);
self.rx_yolo.set(true);
Ok(sz)
}
pub(crate) async fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
let source = self.reactor.upgrade().unwrap().recv(
self.socket.as_raw_fd(),
buf.len(),
iou::MsgFlags::MSG_PEEK,
);
self.consume_receive_buffer(&source, buf).await
}
pub(crate) async fn peek_from(
&self,
buf: &mut [u8],
) -> io::Result<(usize, nix::sys::socket::SockAddr)> {
match self.yolo_recvmsg(buf, iou::MsgFlags::MSG_PEEK) {
Some(res) => res,
None => self.recv_from_blocking(buf, iou::MsgFlags::MSG_PEEK).await,
}
}
pub(crate) async fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
match self.yolo_rx(buf) {
Some(x) => x,
None => {
let source = self
.reactor
.upgrade()
.unwrap()
.rushed_recv(self.socket.as_raw_fd(), buf.len())?;
self.consume_receive_buffer(&source, buf).await
}
}
}
pub(crate) async fn recv_from_blocking(
&self,
buf: &mut [u8],
flags: iou::MsgFlags,
) -> io::Result<(usize, nix::sys::socket::SockAddr)> {
let source = self.reactor.upgrade().unwrap().rushed_recvmsg(
self.socket.as_raw_fd(),
buf.len(),
flags,
)?;
let sz = source.collect_rw().await?;
match source.extract_source_type() {
SourceType::SockRecvMsg(mut src, _iov, hdr, addr) => {
let mut src = src.take().unwrap();
src.trim_to_size(sz);
buf[0..sz].copy_from_slice(&src.as_bytes()[0..sz]);
let addr = unsafe { sys::ssptr_to_sockaddr(addr, hdr.msg_namelen as _)? };
self.rx_yolo.set(true);
Ok((sz, addr))
}
_ => unreachable!(),
}
}
pub(crate) async fn recv_from(
&self,
buf: &mut [u8],
) -> io::Result<(usize, nix::sys::socket::SockAddr)> {
match self.yolo_recvmsg(buf, iou::MsgFlags::empty()) {
Some(res) => res,
None => self.recv_from_blocking(buf, iou::MsgFlags::empty()).await,
}
}
pub(crate) async fn send_to_blocking(
&self,
buf: &[u8],
sockaddr: nix::sys::socket::SockAddr,
) -> io::Result<usize> {
let mut dma = self.allocate_buffer(buf.len());
assert_eq!(dma.write_at(0, buf), buf.len());
let source = self.reactor.upgrade().unwrap().rushed_sendmsg(
self.socket.as_raw_fd(),
dma,
sockaddr,
)?;
let ret = source.collect_rw().await?;
self.tx_yolo.set(true);
Ok(ret)
}
pub(crate) async fn send_to(
&self,
buf: &[u8],
mut addr: nix::sys::socket::SockAddr,
) -> io::Result<usize> {
match self.yolo_sendmsg(buf, &mut addr) {
Some(res) => res,
None => self.send_to_blocking(buf, addr).await,
}
}
pub(crate) async fn send(&self, buf: &[u8]) -> io::Result<usize> {
match self.yolo_tx(buf) {
Some(r) => r,
None => {
let mut dma = self.allocate_buffer(buf.len());
assert_eq!(dma.write_at(0, buf), buf.len());
let source = self
.reactor
.upgrade()
.unwrap()
.rushed_send(self.socket.as_raw_fd(), dma)?;
let ret = source.collect_rw().await?;
self.tx_yolo.set(true);
Ok(ret)
}
}
}
fn allocate_buffer(&self, size: usize) -> DmaBuffer {
self.reactor.upgrade().unwrap().alloc_dma_buffer(size)
}
fn yolo_rx(&self, buf: &mut [u8]) -> Option<io::Result<usize>> {
if self.rx_yolo.get() {
super::yolo_recv(self.socket.as_raw_fd(), buf)
} else {
None
}
.or_else(|| {
self.rx_yolo.set(false);
None
})
}
fn yolo_recvmsg(
&self,
buf: &mut [u8],
flags: iou::MsgFlags,
) -> Option<io::Result<(usize, nix::sys::socket::SockAddr)>> {
if self.rx_yolo.get() {
super::yolo_recvmsg(self.socket.as_raw_fd(), buf, flags)
} else {
None
}
.or_else(|| {
self.rx_yolo.set(false);
None
})
}
fn yolo_tx(&self, buf: &[u8]) -> Option<io::Result<usize>> {
if self.tx_yolo.get() {
super::yolo_send(self.socket.as_raw_fd(), buf)
} else {
None
}
.or_else(|| {
self.tx_yolo.set(false);
None
})
}
fn yolo_sendmsg(
&self,
buf: &[u8],
addr: &mut nix::sys::socket::SockAddr,
) -> Option<io::Result<usize>> {
if self.tx_yolo.get() {
super::yolo_sendmsg(self.socket.as_raw_fd(), buf, addr)
} else {
None
}
.or_else(|| {
self.tx_yolo.set(false);
None
})
}
}
| 31.979757 | 163 | 0.533359 |
38609dba17d220fc612dc2708e406558c94b630a | 1,441 | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use depgraph_api::DeclName;
pub type Result<T, E = Error> = std::result::Result<T, E>;
/// A system error preventing us from proceeding with typechecking. When we
/// encounter one during a bulk typecheck, we should abort the check, report the
/// error to the user, and log the error to Scuba. In some circumstances (e.g.,
/// decl-consistency errors), we might attempt the bulk check again. Includes
/// decl-provider errors like file-not-found (even though it was listed in our
/// global symbol table), decl-consistency errors (i.e., we detected that a
/// source file on disk changed under our feet), etc.
///
/// This type should not be used for internal compiler errors (i.e., invariant
/// violations in our own logic). In OCaml, those are represented as exceptions
/// which are caught at the typing entrypoint and reported as a Hack error
/// (i.e., `Typing_error.invariant_violation`). In Rust, we should represent
/// these with a panic.
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("{0}")]
DeclProvider(#[from] crate::typing_decl_provider::Error),
#[error("Decl Not Found: {0:?}")]
DeclNotFound(DeclName),
#[error("An invariant expected after the naming phase was violated")]
NamingInvariantViolated,
}
| 45.03125 | 80 | 0.720333 |
e63d4b19127e0df56971061fcf52d43e5898ca7d | 5,390 | use euclid::vec3;
use gdnative::prelude::*;
#[derive(Debug, Clone, PartialEq)]
pub enum ManageErrs {
CouldNotMakeInstance,
RootClassNotSpatial(String),
}
#[derive(gdnative::NativeClass)]
#[inherit(Spatial)]
struct SceneCreate {
// Store the loaded scene for a very slight performance boost but mostly to show you how.
template: Option<Ref<PackedScene, ThreadLocal>>,
children_spawned: u32,
}
// Demonstrates Scene creation, calling to/from gdscript
//
// 1. Child scene is created when spawn_one is called
// 2. Child scenes are deleted when remove_one is called
// 3. Find and call functions in a node (Panel)
// 4. Call functions in GDNative (from panel into spawn/remove)
//
// Note, the same mechanism which is used to call from panel into spawn_one and remove_one can be
// used to call other GDNative classes here in rust.
#[gdnative::methods]
impl SceneCreate {
fn new(_owner: &Spatial) -> Self {
SceneCreate {
template: None, // Have not loaded this template yet.
children_spawned: 0,
}
}
#[export]
fn _ready(&mut self, _owner: &Spatial) {
self.template = load_scene("res://Child_scene.tscn");
match &self.template {
Some(_scene) => godot_print!("Loaded child scene successfully!"),
None => godot_print!("Could not load child scene. Check name."),
}
}
#[export]
fn spawn_one(&mut self, owner: &Spatial, message: GodotString) {
godot_print!("Called spawn_one({})", message.to_string());
let template = if let Some(template) = &self.template {
template
} else {
godot_print!("Cannot spawn a child because we couldn't load the template scene");
return;
};
// Create the scene here. Note that we are hardcoding that the parent must at least be a
// child of Spatial in the template argument here...
match instance_scene::<Spatial>(template) {
Ok(spatial) => {
// Here is how you rename the child...
let key_str = format!("child_{}", self.children_spawned);
spatial.set_name(&key_str);
let x = (self.children_spawned % 10) as f32;
let z = (self.children_spawned / 10) as f32;
spatial.translate(vec3(-10.0 + x * 2.0, 0.0, -10.0 + z * 2.0));
// You need to parent the new scene under some node if you want it in the scene.
// We parent it under ourselves.
owner.add_child(spatial.into_shared(), false);
self.children_spawned += 1;
}
Err(err) => godot_print!("Could not instance Child : {:?}", err),
}
let num_children = owner.get_child_count();
update_panel(owner, num_children);
}
#[export]
fn remove_one(&mut self, owner: &Spatial, str: GodotString) {
godot_print!("Called remove_one({})", str);
let num_children = owner.get_child_count();
if num_children <= 0 {
godot_print!("No children to delete");
return;
}
assert_eq!(self.children_spawned as i64, num_children);
let last_child = owner.get_child(num_children - 1);
if let Some(node) = last_child {
unsafe {
node.assume_unique().queue_free();
}
self.children_spawned -= 1;
}
update_panel(owner, num_children - 1);
}
}
fn init(handle: InitHandle) {
handle.add_class::<SceneCreate>();
}
pub fn load_scene(path: &str) -> Option<Ref<PackedScene, ThreadLocal>> {
let scene = ResourceLoader::godot_singleton().load(path, "PackedScene", false)?;
let scene = unsafe { scene.assume_thread_local() };
scene.cast::<PackedScene>()
}
/// Root here is needs to be the same type (or a parent type) of the node that you put in the child
/// scene as the root. For instance Spatial is used for this example.
fn instance_scene<Root>(scene: &PackedScene) -> Result<Ref<Root, Unique>, ManageErrs>
where
Root: gdnative::GodotObject<RefKind = ManuallyManaged> + SubClass<Node>,
{
let instance = scene
.instance(PackedScene::GEN_EDIT_STATE_DISABLED)
.ok_or(ManageErrs::CouldNotMakeInstance)?;
let instance = unsafe { instance.assume_unique() };
instance
.try_cast::<Root>()
.map_err(|instance| ManageErrs::RootClassNotSpatial(instance.name().to_string()))
}
fn update_panel(owner: &Spatial, num_children: i64) {
// Here is how we call into the panel. First we get its node (we might have saved it
// from earlier)
let panel_node_opt = owner.get_parent().and_then(|parent| {
let parent = unsafe { parent.assume_safe() };
parent.find_node("Panel", true, false)
});
if let Some(panel_node) = panel_node_opt {
let panel_node = unsafe { panel_node.assume_safe() };
// Put the Node
let mut as_variant = Variant::from_object(panel_node);
match as_variant.call(
"set_num_children",
&[Variant::from_u64(num_children as u64)],
) {
Ok(_) => godot_print!("Called Panel OK."),
Err(_) => godot_print!("Error calling Panel"),
}
} else {
godot_print!("Could not find panel node");
}
}
godot_init!(init);
| 34.113924 | 99 | 0.613729 |
8a1c0d8252271779257173ddd6f54d321c75f400 | 4,246 | // Copyright 2019-2021 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! A layer between raw [`Runtime`] webview windows and Tauri.
use crate::{
webview::{FileDropHandler, WebviewAttributes, WebviewRpcHandler},
Dispatch, Params, Runtime, WindowBuilder,
};
use serde::Serialize;
use tauri_utils::config::WindowConfig;
use std::hash::{Hash, Hasher};
/// UI scaling utilities.
pub mod dpi;
/// An event from a window.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum WindowEvent {
/// The size of the window has changed. Contains the client area's new dimensions.
Resized(dpi::PhysicalSize<u32>),
/// The position of the window has changed. Contains the window's new position.
Moved(dpi::PhysicalPosition<i32>),
/// The window has been requested to close.
CloseRequested,
/// The window has been destroyed.
Destroyed,
/// The window gained or lost focus.
///
/// The parameter is true if the window has gained focus, and false if it has lost focus.
Focused(bool),
/// The window's scale factor has changed.
///
/// The following user actions can cause DPI changes:
///
/// - Changing the display's resolution.
/// - Changing the display's scale factor (e.g. in Control Panel on Windows).
/// - Moving the window to a display with a different scale factor.
ScaleFactorChanged {
/// The new scale factor.
scale_factor: f64,
/// The window inner size.
new_inner_size: dpi::PhysicalSize<u32>,
},
}
/// A menu event.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MenuEvent {
pub menu_item_id: u16,
}
/// A webview window that has yet to be built.
pub struct PendingWindow<P: Params> {
/// The label that the window will be named.
pub label: P::Label,
/// The [`WindowBuilder`] that the window will be created with.
pub window_builder: <<P::Runtime as Runtime>::Dispatcher as Dispatch>::WindowBuilder,
/// The [`WebviewAttributes`] that the webview will be created with.
pub webview_attributes: WebviewAttributes,
/// How to handle RPC calls on the webview window.
pub rpc_handler: Option<WebviewRpcHandler<P>>,
/// How to handle a file dropping onto the webview window.
pub file_drop_handler: Option<FileDropHandler<P>>,
/// The resolved URL to load on the webview.
pub url: String,
}
impl<P: Params> PendingWindow<P> {
/// Create a new [`PendingWindow`] with a label and starting url.
pub fn new(
window_builder: <<P::Runtime as Runtime>::Dispatcher as Dispatch>::WindowBuilder,
webview_attributes: WebviewAttributes,
label: P::Label,
) -> Self {
Self {
window_builder,
webview_attributes,
label,
rpc_handler: None,
file_drop_handler: None,
url: "tauri://localhost".to_string(),
}
}
/// Create a new [`PendingWindow`] from a [`WindowConfig`] with a label and starting url.
pub fn with_config(
window_config: WindowConfig,
webview_attributes: WebviewAttributes,
label: P::Label,
) -> Self {
Self {
window_builder:
<<<P::Runtime as Runtime>::Dispatcher as Dispatch>::WindowBuilder>::with_config(
window_config,
),
webview_attributes,
label,
rpc_handler: None,
file_drop_handler: None,
url: "tauri://localhost".to_string(),
}
}
}
/// A webview window that is not yet managed by Tauri.
pub struct DetachedWindow<P: Params> {
/// Name of the window
pub label: P::Label,
/// The [`Dispatch`](crate::Dispatch) associated with the window.
pub dispatcher: <P::Runtime as Runtime>::Dispatcher,
}
impl<P: Params> Clone for DetachedWindow<P> {
fn clone(&self) -> Self {
Self {
label: self.label.clone(),
dispatcher: self.dispatcher.clone(),
}
}
}
impl<P: Params> Hash for DetachedWindow<P> {
/// Only use the [`DetachedWindow`]'s label to represent its hash.
fn hash<H: Hasher>(&self, state: &mut H) {
self.label.hash(state)
}
}
impl<P: Params> Eq for DetachedWindow<P> {}
impl<P: Params> PartialEq for DetachedWindow<P> {
/// Only use the [`DetachedWindow`]'s label to compare equality.
fn eq(&self, other: &Self) -> bool {
self.label.eq(&other.label)
}
}
| 28.884354 | 91 | 0.678521 |
611c04c2bbe659f3681b06ec7d1410f52dc6e51e | 2,129 | use crate::process::ProcessInfo;
use crate::{column_default, Column};
#[cfg(not(target_os = "windows"))]
use chrono::offset::TimeZone;
use chrono::{DateTime, Local};
use std::cmp;
use std::collections::HashMap;
pub struct StartTime {
header: String,
unit: String,
fmt_contents: HashMap<i32, String>,
raw_contents: HashMap<i32, DateTime<Local>>,
width: usize,
}
impl StartTime {
pub fn new() -> Self {
let header = String::from("Start");
let unit = String::from("");
StartTime {
fmt_contents: HashMap::new(),
raw_contents: HashMap::new(),
width: 0,
header,
unit,
}
}
}
#[cfg(target_os = "linux")]
impl Column for StartTime {
fn add(&mut self, proc: &ProcessInfo) {
let start_time = proc
.curr_proc
.stat
.starttime()
.unwrap_or(Local.timestamp(0, 0));
let raw_content = start_time;
let fmt_content = format!("{}", start_time.format("%Y/%m/%d %H:%M"));
self.fmt_contents.insert(proc.pid, fmt_content);
self.raw_contents.insert(proc.pid, raw_content);
}
column_default!(DateTime<Local>);
}
#[cfg_attr(tarpaulin, skip)]
#[cfg(target_os = "macos")]
impl Column for StartTime {
fn add(&mut self, proc: &ProcessInfo) {
let start_time = Local.timestamp(proc.curr_task.pbsd.pbi_start_tvsec as i64, 0);
let raw_content = start_time;
let fmt_content = format!("{}", start_time.format("%Y/%m/%d %H:%M"));
self.fmt_contents.insert(proc.pid, fmt_content);
self.raw_contents.insert(proc.pid, raw_content);
}
column_default!(DateTime<Local>);
}
#[cfg_attr(tarpaulin, skip)]
#[cfg(target_os = "windows")]
impl Column for StartTime {
fn add(&mut self, proc: &ProcessInfo) {
let raw_content = proc.start_time;
let fmt_content = format!("{}", proc.start_time.format("%Y/%m/%d %H:%M"));
self.fmt_contents.insert(proc.pid, fmt_content);
self.raw_contents.insert(proc.pid, raw_content);
}
column_default!(DateTime<Local>);
}
| 27.649351 | 88 | 0.609206 |
e278b04302653da3135ad4ae4c24e43b80ecc07a | 2,278 |
use std::io;
use std::time::Instant;
use std::sync::Arc;
use std::net::SocketAddr;
use crossbeam::sync::MsQueue;
use mio::{Ready, Poll, PollOpt, Token, Registration, SetReadiness, Evented};
use siege_example_net::GamePacket;
pub struct PacketSender {
pub outbound: Arc<MsQueue<(GamePacket,SocketAddr,Option<u32>)>>, // optional in reply to seq no.
registration: Registration,
set_readiness: SetReadiness,
}
impl PacketSender {
pub fn new() -> PacketSender {
let (registration, set_readiness) = Registration::new2();
PacketSender {
outbound: Arc::new(MsQueue::new()),
registration: registration,
set_readiness: set_readiness
}
}
pub fn send(&self, packet: GamePacket, addr: SocketAddr, in_reply_to: Option<u32>)
-> ::errors::Result<()>
{
self.outbound.push((packet,addr,in_reply_to));
self.set_readiness.set_readiness(Ready::readable())?;
Ok(())
}
pub fn send_at_future_time(&self, packet: GamePacket, addr: SocketAddr,
in_reply_to: Option<u32>, when: Instant)
-> ::errors::Result<()>
{
let msqueue = self.outbound.clone();
let setr = self.set_readiness.clone();
::std::thread::spawn(move|| {
let now = Instant::now();
if now < when {
::std::thread::sleep(when - now);
}
msqueue.push((packet,addr,in_reply_to));
let _ = setr.set_readiness(Ready::readable());
});
Ok(())
}
}
impl Evented for PacketSender {
fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt)
-> io::Result<()>
{
self.registration.register(poll, token, interest, opts)
}
fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt)
-> io::Result<()>
{
self.registration.reregister(poll, token, interest, opts)
}
fn deregister(&self, poll: &Poll) -> io::Result<()> {
// For some reason, rust is choosing the wrong fn. Once it goes away entirely
// this warning will disappear.
#[allow(deprecated)]
self.registration.deregister(poll)
}
}
| 32.084507 | 100 | 0.583845 |
6a81d2c8685762602acb9f89aee3b64b7a4b45c0 | 3,081 | use linkify::LinkFinder;
use once_cell::sync::Lazy;
static LINK_FINDER: Lazy<LinkFinder> = Lazy::new(LinkFinder::new);
/// Remove all GET parameters from a URL.
/// The link is not a URL but a String as it may not have a base domain.
pub(crate) fn remove_get_params_and_fragment(url: &str) -> &str {
let path = match url.split_once('#') {
Some((path_without_fragment, _fragment)) => path_without_fragment,
None => url,
};
let path = match path.split_once('?') {
Some((path_without_params, _params)) => path_without_params,
None => path,
};
path
}
/// Determine if an element's attribute contains a link / URL.
pub(crate) fn elem_attr_is_link(attr_name: &str, elem_name: &str) -> bool {
// See a comprehensive list of attributes that might contain URLs/URIs
// over at: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
matches!(
(attr_name, elem_name),
("href" | "src" | "srcset" | "cite", _) | ("data", "object") | ("onhashchange", "body")
)
}
// Taken from https://github.com/getzola/zola/blob/master/components/link_checker/src/lib.rs
pub(crate) fn is_anchor(url: &str) -> bool {
url.starts_with('#')
}
// Use `LinkFinder` to offload the raw link searching in plaintext
pub(crate) fn find_links(input: &str) -> impl Iterator<Item = linkify::Link> {
LINK_FINDER.links(input)
}
#[cfg(test)]
mod test_fs_tree {
use super::*;
#[test]
fn test_is_anchor() {
assert!(is_anchor("#anchor"));
assert!(!is_anchor("notan#anchor"));
}
#[test]
fn test_remove_get_params_and_fragment() {
assert_eq!(remove_get_params_and_fragment("/"), "/");
assert_eq!(
remove_get_params_and_fragment("index.html?foo=bar"),
"index.html"
);
assert_eq!(
remove_get_params_and_fragment("/index.html?foo=bar"),
"/index.html"
);
assert_eq!(
remove_get_params_and_fragment("/index.html?foo=bar&baz=zorx?bla=blub"),
"/index.html"
);
assert_eq!(
remove_get_params_and_fragment("https://example.org/index.html?foo=bar"),
"https://example.org/index.html"
);
assert_eq!(
remove_get_params_and_fragment("test.png?foo=bar"),
"test.png"
);
assert_eq!(
remove_get_params_and_fragment("https://example.org/index.html#anchor"),
"https://example.org/index.html"
);
assert_eq!(
remove_get_params_and_fragment("https://example.org/index.html?foo=bar#anchor"),
"https://example.org/index.html"
);
assert_eq!(
remove_get_params_and_fragment("test.png?foo=bar#anchor"),
"test.png"
);
assert_eq!(
remove_get_params_and_fragment("test.png#anchor?anchor!?"),
"test.png"
);
assert_eq!(
remove_get_params_and_fragment("test.png?foo=bar#anchor?anchor!"),
"test.png"
);
}
}
| 31.762887 | 95 | 0.599481 |
fe9885b84af001c06068b1a4696c73039df190ea | 1,708 | use std::fmt::{Debug, Display};
use crate::{
structs::{PrivateField, Tuple},
traits::Simple,
unions::Basic,
RenamedPlain,
};
pub fn plain() {}
pub const fn const_fn() {}
pub fn one_arg(x: usize) {
println!("{}", x);
}
pub fn struct_arg(s: PrivateField) {
println!("{}", s.x);
}
pub fn fn_arg(f: impl Fn(bool, RenamedPlain) -> bool, mut f_mut: impl FnMut() -> ()) {
if f(false, RenamedPlain { x: 9 }) {
f_mut();
}
}
pub fn return_tuple() -> (bool, Basic) {
(true, Basic { x: 42 })
}
pub fn return_slice<'a>(input: &'a [usize]) -> &'a [usize] {
&input
}
pub fn return_raw_pointer(input: &usize) -> *const usize {
input
}
pub fn return_mut_raw_pointer(input: &mut usize) -> *mut usize {
input
}
pub fn return_array() -> [u8; 2] {
[99, 98]
}
pub fn return_iterator() -> impl Iterator<Item = u32> {
vec![1, 2, 3].into_iter()
}
pub fn generic_arg<T>(t: T) -> T {
t
}
pub fn generic_bound<T: Sized>(t: T) -> T {
t
}
pub fn inferred_lifetime(foo: &'_ usize) -> usize {
*foo
}
pub fn outlives<'a, 'b: 'a, 'c: 'b + 'a>(x: &'a bool, y: &'b i128, z: &'c Tuple) -> usize {
if *x && *y > 0 {
z.0
} else {
1234
}
}
pub fn synthetic_arg(t: impl Simple) -> impl Simple {
t
}
pub fn impl_multiple<T>(t: impl Simple + AsRef<T>) -> impl Simple {}
pub fn somewhere<T, U>(t: T, u: U)
where
T: Display,
U: Debug,
{
println!("{}, {:?}", t, u);
}
pub fn multiple_bounds<T>(t: T)
where
T: Debug + Display,
{
}
pub fn multiple_bounds_inline<T: Debug + Display>(t: T) {}
pub fn dyn_arg(d: &(dyn std::io::Write + Send + 'static)) {}
pub unsafe fn unsafe_fn() {}
pub async fn async_fn() {}
| 17.252525 | 91 | 0.559133 |
0ebf209fe0dfac40b9d4a2e3b373b7548ffdcc93 | 1,048 | /*
How to get best move for current state of the board
*/
use pleco::tools::Searcher;
pub fn main()
{
/*
https://docs.rs/pleco/0.5.0/pleco/
https://docs.rs/pleco/0.5.0/pleco/board/struct.Board.html
https://docs.rs/pleco/latest/pleco/board/struct.Board.html#bitboard-representation
https://docs.rs/pleco/latest/pleco/tools/trait.Searcher.html#tymethod.best_move
*/
/*
8 | 56 57 58 59 60 61 62 63
7 | 48 49 50 51 52 53 54 55
6 | 40 41 42 43 44 45 46 47
5 | 32 33 34 35 36 37 38 39
4 | 24 25 26 27 28 29 30 31
3 | 16 17 18 19 20 21 22 23
2 | 8 9 10 11 12 13 14 15
1 | 0 1 2 3 4 5 6 7
-------------------------
a b c d e f g h
*/
let board : pleco::Board = pleco::Board::from_fen("7k/1pR2P2/N1pb1K2/2B3N1/1P5p/3q1p2/2p5/7B w - - 0 1").unwrap(); //Board from generated fen
board.pretty_print();
let depth = 1;
let best_move = pleco::bots::MiniMaxSearcher::best_move(board.clone(), depth); // Return best move for current state of the board
println!("Best move: {}", best_move);
}
| 29.111111 | 143 | 0.626908 |
0390f538b222a160cb2e9292a2a58c91f83d6770 | 4,016 | use crate::auth::AuthenticationScheme;
use crate::bail_status as bail;
use crate::headers::{Header, HeaderName, HeaderValue, Headers, AUTHORIZATION};
/// Credentials to authenticate a user agent with a server.
///
/// # Specifications
///
/// - [RFC 7235, section 4.2: Authorization](https://tools.ietf.org/html/rfc7235#section-4.2)
///
/// # Examples
///
/// ```
/// # fn main() -> http_types::Result<()> {
/// #
/// use http_types::Response;
/// use http_types::auth::{AuthenticationScheme, Authorization};
///
/// let scheme = AuthenticationScheme::Basic;
/// let credentials = "0xdeadbeef202020";
/// let authz = Authorization::new(scheme, credentials.into());
///
/// let mut res = Response::new(200);
/// res.insert_header(&authz, &authz);
///
/// let authz = Authorization::from_headers(res)?.unwrap();
///
/// assert_eq!(authz.scheme(), AuthenticationScheme::Basic);
/// assert_eq!(authz.credentials(), credentials);
/// #
/// # Ok(()) }
/// ```
#[derive(Debug)]
pub struct Authorization {
scheme: AuthenticationScheme,
credentials: String,
}
impl Authorization {
/// Create a new instance of `Authorization`.
pub fn new(scheme: AuthenticationScheme, credentials: String) -> Self {
Self {
scheme,
credentials,
}
}
/// Create a new instance from headers.
pub fn from_headers(headers: impl AsRef<Headers>) -> crate::Result<Option<Self>> {
let headers = match headers.as_ref().get(AUTHORIZATION) {
Some(headers) => headers,
None => return Ok(None),
};
// If we successfully parsed the header then there's always at least one
// entry. We want the last entry.
let value = headers.iter().last().unwrap();
let mut iter = value.as_str().splitn(2, ' ');
let scheme = iter.next();
let credential = iter.next();
let (scheme, credentials) = match (scheme, credential) {
(None, _) => bail!(400, "Could not find scheme"),
(Some(_), None) => bail!(400, "Could not find credentials"),
(Some(scheme), Some(credentials)) => (scheme.parse()?, credentials.to_owned()),
};
Ok(Some(Self {
scheme,
credentials,
}))
}
/// Get the authorization scheme.
pub fn scheme(&self) -> AuthenticationScheme {
self.scheme
}
/// Set the authorization scheme.
pub fn set_scheme(&mut self, scheme: AuthenticationScheme) {
self.scheme = scheme;
}
/// Get the authorization credentials.
pub fn credentials(&self) -> &str {
self.credentials.as_str()
}
/// Set the authorization credentials.
pub fn set_credentials(&mut self, credentials: String) {
self.credentials = credentials;
}
}
impl Header for Authorization {
fn header_name(&self) -> HeaderName {
AUTHORIZATION
}
fn header_value(&self) -> HeaderValue {
let output = format!("{} {}", self.scheme, self.credentials);
// SAFETY: the internal string is validated to be ASCII.
unsafe { HeaderValue::from_bytes_unchecked(output.into()) }
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::headers::Headers;
#[test]
fn smoke() -> crate::Result<()> {
let scheme = AuthenticationScheme::Basic;
let credentials = "0xdeadbeef202020";
let authz = Authorization::new(scheme, credentials.into());
let mut headers = Headers::new();
authz.apply_header(&mut headers);
let authz = Authorization::from_headers(headers)?.unwrap();
assert_eq!(authz.scheme(), AuthenticationScheme::Basic);
assert_eq!(authz.credentials(), credentials);
Ok(())
}
#[test]
fn bad_request_on_parse_error() {
let mut headers = Headers::new();
headers.insert(AUTHORIZATION, "<nori ate the tag. yum.>");
let err = Authorization::from_headers(headers).unwrap_err();
assert_eq!(err.status(), 400);
}
}
| 29.313869 | 93 | 0.608566 |
d5a6e20b35a7d1231a5c4e12b34cc8b71df5688b | 622 | // Copyright (c) 2015 Robert Clipsham <[email protected]>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate pnet_macros;
extern crate pnet_macros_support;
use pnet_macros::packet;
#[packet]
pub struct PacketU16 {
banana: u16, //~ ERROR endianness must be specified for types of size >= 8
#[payload]
payload: Vec<u8>,
}
fn main() {}
| 29.619048 | 79 | 0.721865 |
1cae90ee948cb89a10024218239de92843bd09e2 | 56,169 | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{
cell::RefCell,
collections::{BTreeMap, HashMap, HashSet},
fmt,
iter::{Iterator as StdIterator, Peekable},
marker::PhantomData,
mem,
ops::{Bound, Deref, DerefMut},
rc::Rc,
result::Result as StdResult,
};
use crate::{
validation::assert_valid_name_component,
views::{
get_object_hash, AsReadonly, ChangesIter, IndexesPool, RawAccess, ResolvedAddress, View,
},
Error, Result, SystemSchema,
};
/// Changes related to a specific `View`.
#[derive(Debug, Default, Clone)]
pub struct ViewChanges {
/// Changes within the view.
pub(super) data: BTreeMap<Vec<u8>, Change>,
/// Was the view cleared as a part of changes?
is_cleared: bool,
/// Is the view aggregated into `state_hash` of the database?
/// Storing this information directly in the changes allows to avoid relatively expensive
/// metadata lookups during state aggregator update in `Fork::into_patch()`.
namespace: Option<String>,
}
impl ViewChanges {
fn new() -> Self {
Self::default()
}
pub fn is_cleared(&self) -> bool {
self.is_cleared
}
#[cfg(test)]
pub fn is_aggregated(&self) -> bool {
self.namespace.as_ref().map_or(false, String::is_empty)
}
pub fn clear(&mut self) {
self.data.clear();
self.is_cleared = true;
}
pub fn set_aggregation(&mut self, namespace: Option<String>) {
self.namespace = namespace;
}
pub(crate) fn into_data(self) -> BTreeMap<Vec<u8>, Change> {
self.data
}
/// Returns a value for the specified key, or an `Err(_)` if the value should be determined
/// by the underlying snapshot.
pub fn get(&self, key: &[u8]) -> StdResult<Option<Vec<u8>>, ()> {
if let Some(change) = self.data.get(key) {
return Ok(match *change {
Change::Put(ref v) => Some(v.clone()),
Change::Delete => None,
});
}
if self.is_cleared() {
return Ok(None);
}
Err(())
}
/// Returns whether the view contains the specified `key`. An `Err(_)` is returned if this
/// is determined by the underlying snapshot.
pub fn contains(&self, key: &[u8]) -> StdResult<bool, ()> {
if let Some(change) = self.data.get(key) {
return Ok(match *change {
Change::Put(..) => true,
Change::Delete => false,
});
}
if self.is_cleared() {
return Ok(false);
}
Err(())
}
}
/// Cell holding changes for a specific view. Mutable view borrows take changes out
/// of the `Option` and unwraps `Rc` into inner data, while immutable borrows clone inner `Rc`.
type ChangesCell = Option<Rc<ViewChanges>>;
#[derive(Debug, Default)]
struct WorkingPatch {
changes: RefCell<HashMap<ResolvedAddress, ChangesCell>>,
}
#[derive(Debug)]
enum WorkingPatchRef<'a> {
Borrowed(&'a WorkingPatch),
Owned(Rc<Fork>),
}
impl WorkingPatchRef<'_> {
fn patch(&self) -> &WorkingPatch {
match self {
WorkingPatchRef::Borrowed(patch) => patch,
WorkingPatchRef::Owned(ref fork) => &fork.working_patch,
}
}
}
#[derive(Debug)]
pub struct ChangesRef<'a> {
inner: Rc<ViewChanges>,
_lifetime: PhantomData<&'a ()>,
}
impl Drop for ChangesRef<'_> {
fn drop(&mut self) {
// Do nothing. The implementation is required to make `View`s based on `ChangesRef`
// drop before a mutable operation is performed on a fork (e.g., it's converted
// into a patch).
}
}
impl Deref for ChangesRef<'_> {
type Target = ViewChanges;
fn deref(&self) -> &ViewChanges {
&*self.inner
}
}
/// `RefMut`, but dumber.
#[derive(Debug)]
pub struct ChangesMut<'a> {
parent: WorkingPatchRef<'a>,
key: ResolvedAddress,
changes: Option<Rc<ViewChanges>>,
}
impl Deref for ChangesMut<'_> {
type Target = ViewChanges;
fn deref(&self) -> &ViewChanges {
// `.unwrap()` is safe: `changes` can be equal to `None` only when
// the instance is being dropped.
self.changes.as_ref().unwrap()
}
}
impl DerefMut for ChangesMut<'_> {
fn deref_mut(&mut self) -> &mut ViewChanges {
// `.unwrap()`s are safe:
//
// - `changes` can be equal to `None` only when the instance is being dropped.
// - We know that `Rc` with the changes is unique.
Rc::get_mut(self.changes.as_mut().unwrap()).unwrap()
}
}
impl Drop for ChangesMut<'_> {
fn drop(&mut self) {
let mut change_map = self.parent.patch().changes.borrow_mut();
let changes = change_map.get_mut(&self.key).unwrap_or_else(|| {
panic!("insertion point for changes disappeared at {:?}", self.key);
});
debug_assert!(changes.is_none(), "edit conflict at {:?}", self.key);
*changes = self.changes.take();
}
}
impl WorkingPatch {
/// Creates a new empty patch.
fn new() -> Self {
Self {
changes: RefCell::new(HashMap::new()),
}
}
/// Takes a cell with changes for a specific `View` out of the patch.
/// The returned cell is guaranteed to contain an `Rc` with an exclusive ownership.
fn take_view_changes(&self, address: &ResolvedAddress) -> ChangesCell {
let view_changes = {
let mut changes = self.changes.borrow_mut();
let view_changes = changes.get_mut(address).map(Option::take);
view_changes.unwrap_or_else(|| {
changes
.entry(address.clone())
.or_insert_with(|| Some(Rc::new(ViewChanges::new())))
.take()
})
};
if let Some(ref view_changes) = view_changes {
assert!(
Rc::strong_count(view_changes) == 1,
"Attempting to borrow {:?} mutably while it's borrowed immutably",
address
);
} else {
panic!("Multiple mutable borrows of an index at {:?}", address);
}
view_changes
}
/// Clones changes for a specific `View` from the patch. Panics if the changes
/// are mutably borrowed.
fn clone_view_changes(&self, address: &ResolvedAddress) -> Rc<ViewChanges> {
let mut changes = self.changes.borrow_mut();
// Get changes for the specified address.
let changes: &ChangesCell = changes
.entry(address.clone())
.or_insert_with(|| Some(Rc::new(ViewChanges::new())));
changes
.as_ref()
.unwrap_or_else(|| {
// If the `changes` are `None`, this means they have been taken by a previous call
// to `take_view_changes` and not yet returned.
panic!(
"Attempting to borrow {:?} immutably while it's borrowed mutably",
address
);
})
.clone()
}
// TODO: verify that this method updates `Change`s already in the `Patch` [ECR-2834]
fn merge_into(self, patch: &mut Patch) {
for (address, changes) in self.changes.into_inner() {
// Check that changes are not borrowed mutably (in this case, the corresponding
// `ChangesCell` is `None`).
//
// Both this and the following `panic`s cannot feasibly be triggered,
// since the only place where this method is called (`Fork::flush()`) borrows
// `Fork` mutably; this forces both mutable and immutable index borrows to be dropped,
// since they borrow `Fork` immutably.
let changes = changes.unwrap_or_else(|| {
panic!(
"changes are still mutably borrowed at address {:?}",
address
);
});
// Check that changes are not borrowed immutably (in this case, there is another
// `Rc<_>` pointer to changes somewhere).
let mut changes = Rc::try_unwrap(changes).unwrap_or_else(|_| {
panic!(
"changes are still immutably borrowed at address {:?}",
address
);
});
if let Some(namespace) = mem::replace(&mut changes.namespace, None) {
patch
.changed_aggregated_addrs
.insert(address.clone(), namespace);
}
// The patch may already contain changes related to the `address`. If it does,
// we extend these changes with the new changes (relying on the fact that
// newer changes override older ones), unless the view was cleared (in which case,
// the old changes do not matter and should be forgotten).
let patch_changes = patch
.changes
.entry(address)
.or_insert_with(ViewChanges::new);
if changes.is_cleared() {
*patch_changes = changes;
} else {
patch_changes.data.extend(changes.data);
}
}
}
}
/// A generalized iterator over the storage views.
pub type Iter<'a> = Box<dyn Iterator + 'a>;
/// An enum that represents a type of change made to some key in the storage.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(test, derive(Eq, Hash))] // needed for patch equality comparison
pub enum Change {
/// Put the specified value into the storage for the corresponding key.
Put(Vec<u8>),
/// Delete a value from the storage for the corresponding key.
Delete,
}
/// A combination of a database snapshot and changes on top of it.
///
/// A `Fork` provides both immutable and mutable operations over the database by implementing
/// the [`RawAccessMut`] trait. Like [`Snapshot`], `Fork` provides read isolation.
/// When mutable operations are applied to a fork, the subsequent reads act as if the changes
/// are applied to the database; in reality, these changes are accumulated in memory.
///
/// To apply the changes to the database, you need to convert a `Fork` into a [`Patch`] using
/// [`into_patch`] and then atomically [`merge`] it into the database. If two
/// conflicting forks are merged into a database, this can lead to an inconsistent state. If you
/// need to consistently apply several sets of changes to the same data, the next fork should be
/// created after the previous fork has been merged.
///
/// `Fork` also supports checkpoints ([`flush`] and [`rollback`] methods), which allows
/// rolling back the latest changes. A checkpoint is created automatically after calling
/// the `flush` method.
///
/// ```
/// # use merkledb::{access::CopyAccessExt, Database, TemporaryDB};
/// let db = TemporaryDB::new();
/// let mut fork = db.fork();
/// fork.get_list("list").extend(vec![1_u32, 2]);
/// fork.flush();
/// fork.get_list("list").push(3_u32);
/// fork.rollback();
/// // The changes after the latest `flush()` are now forgotten.
/// let list = fork.get_list::<_, u32>("list");
/// assert_eq!(list.len(), 2);
/// # assert_eq!(list.iter().collect::<Vec<_>>(), vec![1, 2]);
/// ```
///
/// In order to convert a fork into `&dyn Snapshot` presentation, convert it into a `Patch`
/// and use a reference to it (`Patch` implements `Snapshot`). Using `<Fork as RawAccess>::snapshot`
/// for this purpose is logically incorrect and may lead to hard-to-debug errors.
///
/// # Borrow checking
///
/// It is possible to create only one instance of index with the specified `IndexAddress` based on a
/// single fork. If an additional instance is requested, the code will panic in runtime.
/// Hence, obtaining indexes from a `Fork` functions similarly to [`RefCell::borrow_mut()`].
///
/// For example the code below will panic at runtime.
///
/// ```rust,should_panic
/// # use merkledb::{access::CopyAccessExt, TemporaryDB, ListIndex, Database};
/// let db = TemporaryDB::new();
/// let fork = db.fork();
/// let index = fork.get_list::<_, u8>("index");
/// // This code will panic at runtime.
/// let index2 = fork.get_list::<_, u8>("index");
/// ```
///
/// To enable immutable / shared references to indexes, you may use [`readonly`] method:
///
/// ```
/// # use merkledb::{access::CopyAccessExt, TemporaryDB, ListIndex, Database};
/// let db = TemporaryDB::new();
/// let fork = db.fork();
/// fork.get_list::<_, u8>("index").extend(vec![1, 2, 3]);
///
/// let readonly = fork.readonly();
/// let index = readonly.get_list::<_, u8>("index");
/// // Works fine.
/// let index2 = readonly.get_list::<_, u8>("index");
/// ```
///
/// It is impossible to mutate index contents having a readonly access to the fork; this is
/// checked by the Rust type system.
///
/// Shared references work like `RefCell::borrow()`; it is a runtime error to try to obtain
/// a shared reference to an index if there is an exclusive reference to the same index,
/// and vice versa.
///
/// [`RawAccessMut`]: access/trait.RawAccessMut.html
/// [`Snapshot`]: trait.Snapshot.html
/// [`Patch`]: struct.Patch.html
/// [`into_patch`]: #method.into_patch
/// [`merge`]: trait.Database.html#tymethod.merge
/// [`commit`]: #method.commit
/// [`flush`]: #method.flush
/// [`rollback`]: #method.rollback
/// [`readonly`]: #method.readonly
/// [`RefCell::borrow_mut()`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.borrow_mut
#[derive(Debug)]
pub struct Fork {
patch: Patch,
working_patch: WorkingPatch,
}
/// A set of changes that can be atomically applied to a `Database`.
///
/// This set can contain changes from multiple indexes. Changes can be read from the `Patch`
/// using its `RawAccess` implementation.
///
/// # Examples
///
/// ```
/// # use merkledb::{
/// # access::CopyAccessExt, Database, ObjectHash, Patch, SystemSchema, TemporaryDB,
/// # };
/// let db = TemporaryDB::new();
/// let fork = db.fork();
/// fork.get_proof_list("list").extend(vec![1_i32, 2, 3]);
/// let patch: Patch = fork.into_patch();
/// // The patch contains changes recorded in the fork.
/// let list = patch.get_proof_list::<_, i32>("list");
/// assert_eq!(list.len(), 3);
/// // Unlike `Fork`, `Patch`es have consistent aggregated state.
/// let aggregator = SystemSchema::new(&patch).state_aggregator();
/// assert_eq!(aggregator.get("list").unwrap(), list.object_hash());
/// ```
#[derive(Debug)]
pub struct Patch {
snapshot: Box<dyn Snapshot>,
changes: HashMap<ResolvedAddress, ViewChanges>,
/// Addresses of aggregated indexes that were changed within this patch. This information
/// is used to update the state aggregator in `Fork::into_patch()`.
changed_aggregated_addrs: HashMap<ResolvedAddress, String>,
/// Names of removed aggregated indexes.
removed_aggregated_addrs: HashSet<String>,
}
pub(super) struct ForkIter<'a, T: StdIterator> {
snapshot: Iter<'a>,
changes: Option<Peekable<T>>,
}
#[derive(Debug, PartialEq, Eq)]
enum NextIterValue {
Stored,
Replaced,
Inserted,
Deleted,
MissDeleted,
Finished,
}
/// Low-level storage backend implementing a collection of named key-value stores
/// (aka column families).
///
/// A `Database` instance is shared across different threads, so it must be `Sync` and `Send`.
///
/// There is no way to directly interact with data in the database; use [`snapshot`], [`fork`]
/// and [`merge`] methods for indirect interaction. See [the crate-level documentation](index.html)
/// for more details.
///
/// Note that `Database` effectively has [interior mutability][interior-mut];
/// `merge` and `merge_sync` methods take a shared reference to the database (`&self`)
/// rather than an exclusive one (`&mut self`). This means that the following code compiles:
///
/// ```
/// use merkledb::{access::CopyAccessExt, Database, TemporaryDB};
///
/// // not declared as `mut db`!
/// let db: Box<dyn Database> = Box::new(TemporaryDB::new());
/// let fork = db.fork();
/// {
/// let mut list = fork.get_proof_list("list");
/// list.push(42_u64);
/// }
/// db.merge(fork.into_patch()).unwrap();
/// ```
///
/// # Merge Workflow
///
/// The user of a `Database` is responsible to ensure that forks are either created and merged
/// sequentially or do not contain overlapping changes. By sequential creation we mean the following
/// workflow:
///
/// ```
/// # use merkledb::{Database, TemporaryDB};
/// let db = TemporaryDB::new();
/// let first_fork = db.fork();
/// // Perform some operations on `first_fork`...
/// db.merge(first_fork.into_patch()).unwrap();
/// let second_fork = db.fork();
/// // Perform some operations on `second_fork`...
/// db.merge(second_fork.into_patch()).unwrap();
/// ```
///
/// In contrast, this is a non-sequential workflow:
///
/// ```
/// # use merkledb::{Database, TemporaryDB};
/// let db = TemporaryDB::new();
/// let first_fork = db.fork();
/// // Perform some operations on `first_fork`...
/// let second_fork = db.fork();
/// // Perform some operations on `second_fork`...
/// db.merge(first_fork.into_patch()).unwrap();
/// db.merge(second_fork.into_patch()).unwrap();
/// ```
///
/// In a non-sequential workflow, `first_fork` and `second_fork` **must not** contain overlapping
/// changes (i.e., changes to the same index). If they do, the result of the merge may be
/// unpredictable to the programmer and may break database invariants, e.g., that the length
/// of an index is equal to the number of elements obtained by iterating over the index:
///
/// ```
/// // NEVER USE THIS PATTERN!
/// # use merkledb::{access::CopyAccessExt, Database, TemporaryDB};
/// let db = TemporaryDB::new();
/// let first_fork = db.fork();
/// first_fork.get_list("list").extend(vec![1, 2, 3]);
/// let second_fork = db.fork();
/// second_fork.get_list("list").push(4);
/// db.merge(first_fork.into_patch()).unwrap();
/// db.merge(second_fork.into_patch()).unwrap();
///
/// let snapshot = db.snapshot();
/// let list = snapshot.get_list::<_, i32>("list");
/// assert_eq!(list.len(), 1);
/// assert_eq!(list.iter().collect::<Vec<_>>(), vec![4, 2, 3]);
/// // ^-- Oops, we got two phantom elements!
/// ```
///
/// It is advised to create / merge patches sequentially whenever possible. The concurrent
/// workflow should only be used for minor changes, for which the proof that a patch does not overlap
/// with concurrent patches is tractable.
///
/// [`snapshot`]: #tymethod.snapshot
/// [`fork`]: #method.fork
/// [`merge`]: #tymethod.merge
/// [interior-mut]: https://doc.rust-lang.org/book/ch15-05-interior-mutability.html
pub trait Database: Send + Sync + 'static {
/// Creates a new snapshot of the database from its current state.
fn snapshot(&self) -> Box<dyn Snapshot>;
/// Creates a new fork of the database from its current state.
fn fork(&self) -> Fork {
Fork {
patch: Patch {
snapshot: self.snapshot(),
changes: HashMap::new(),
changed_aggregated_addrs: HashMap::new(),
removed_aggregated_addrs: HashSet::new(),
},
working_patch: WorkingPatch::new(),
}
}
/// Atomically applies a sequence of patch changes to the database.
///
/// Note that this method may be called concurrently from different threads, the
/// onus to guarantee atomicity is on the implementor of the trait.
///
/// # Logical Safety
///
/// Merging several patches which are not created sequentially and contain
/// overlapping changes may result in the unexpected storage state and lead to the hard-to debug
/// errors, storage leaks etc. See the [trait docs](#merge-workflow) for more details.
///
/// # Errors
///
/// If this method encounters any form of I/O or other error during merging, an error variant
/// will be returned. In case of an error, the method guarantees no changes are applied to
/// the database.
fn merge(&self, patch: Patch) -> Result<()>;
/// Atomically applies a sequence of patch changes to the database with fsync.
///
/// Note that this method may be called concurrently from different threads, the
/// onus to guarantee atomicity is on the implementor of the trait.
///
/// # Logical Safety
///
/// Merging several patches which are not created sequentially and contain
/// overlapping changes may result in the unexpected storage state and lead to the hard-to debug
/// errors, storage leaks etc. See the [trait docs](#merge-workflow) for more details.
///
/// # Errors
///
/// If this method encounters any form of I/O or other error during merging, an error variant
/// will be returned. In case of an error, the method guarantees no changes are applied to
/// the database.
fn merge_sync(&self, patch: Patch) -> Result<()>;
}
/// Extension trait for `Database`.
pub trait DatabaseExt: Database {
/// Merges a patch into the database and creates a backup patch that reverses all the merged
/// changes.
///
/// # Safety
///
/// It is logically unsound to merge other patches to the database between the `merge_with_backup`
/// call and merging the backup patch. This may lead to merge artifacts and an inconsistent
/// database state.
///
/// An exception to this rule is creating backups for several merged patches
/// and then applying backups in the reverse order:
///
/// ```
/// # use merkledb::{access::{Access, CopyAccessExt}, Database, DatabaseExt, TemporaryDB};
/// let db = TemporaryDB::new();
/// let fork = db.fork();
/// fork.get_list("list").push(1_u32);
/// let backup1 = db.merge_with_backup(fork.into_patch()).unwrap();
/// let fork = db.fork();
/// fork.get_list("list").push(2_u32);
/// let backup2 = db.merge_with_backup(fork.into_patch()).unwrap();
/// let fork = db.fork();
/// fork.get_list("list").extend(vec![3_u32, 4]);
/// let backup3 = db.merge_with_backup(fork.into_patch()).unwrap();
///
/// fn enumerate_list<A: Access + Copy>(view: A) -> Vec<u32> {
/// view.get_list("list").iter().collect()
/// }
///
/// assert_eq!(enumerate_list(&db.snapshot()), vec![1, 2, 3, 4]);
/// // Rollback the most recent merge.
/// db.merge(backup3).unwrap();
/// assert_eq!(enumerate_list(&db.snapshot()), vec![1, 2]);
/// // ...Then the penultimate merge.
/// db.merge(backup2).unwrap();
/// assert_eq!(enumerate_list(&db.snapshot()), vec![1]);
/// // ...Then the oldest one.
/// db.merge(backup1).unwrap();
/// assert!(enumerate_list(&db.snapshot()).is_empty());
/// ```
///
/// # Performance notes
///
/// This method is linear w.r.t. patch size (i.e., the total number of changes in it) plus,
/// for each clear operation, the corresponding index size before clearing. As such,
/// the method may be inappropriate to use with large patches.
///
/// # Errors
///
/// Returns an error in the same situations as `Database::merge()`.
fn merge_with_backup(&self, patch: Patch) -> Result<Patch> {
// FIXME: does this work with migrations? (ECR-4005)
let snapshot = self.snapshot();
let changed_aggregated_addrs = patch.changed_aggregated_addrs.clone();
let mut rev_changes = HashMap::with_capacity(patch.changes.len());
for (name, changes) in &patch.changes {
let mut view_changes = changes.data.clone();
for (key, change) in &mut view_changes {
*change = snapshot.get(name, key).map_or(Change::Delete, Change::Put);
}
// Remember all elements that will be deleted.
if changes.is_cleared() {
let mut iter = snapshot.iter(name, &[]);
while let Some((key, value)) = iter.next() {
view_changes.insert(key.to_vec(), Change::Put(value.to_vec()));
}
}
rev_changes.insert(
name.to_owned(),
ViewChanges {
data: view_changes,
is_cleared: false,
namespace: changes.namespace.clone(),
},
);
}
self.merge(patch)?;
Ok(Patch {
snapshot: self.snapshot(),
changes: rev_changes,
changed_aggregated_addrs,
removed_aggregated_addrs: HashSet::new(),
})
}
}
impl<T: Database> DatabaseExt for T {}
/// A read-only snapshot of a storage backend.
///
/// A `Snapshot` instance is an immutable representation of a certain storage state.
/// It provides read isolation, so consistency is guaranteed even if the data in
/// the database changes between reads.
pub trait Snapshot: Send + Sync + 'static {
/// Returns a value corresponding to the specified address and key as a raw vector of bytes,
/// or `None` if it does not exist.
fn get(&self, name: &ResolvedAddress, key: &[u8]) -> Option<Vec<u8>>;
/// Returns `true` if the snapshot contains a value for the specified address and key.
///
/// The default implementation checks existence of the value using [`get`](#tymethod.get).
fn contains(&self, name: &ResolvedAddress, key: &[u8]) -> bool {
self.get(name, key).is_some()
}
/// Returns an iterator over the entries of the snapshot in ascending order starting from
/// the specified key. The iterator element type is `(&[u8], &[u8])`.
fn iter(&self, name: &ResolvedAddress, from: &[u8]) -> Iter<'_>;
}
/// A trait that defines a streaming iterator over storage view entries. Unlike
/// the standard [`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html)
/// trait, `Iterator` in Exonum is low-level and, therefore, operates with bytes.
pub trait Iterator {
/// Advances the iterator and returns a reference to the next key and value.
fn next(&mut self) -> Option<(&[u8], &[u8])>;
/// Returns a reference to the current key and value without advancing the iterator.
fn peek(&mut self) -> Option<(&[u8], &[u8])>;
}
impl Patch {
/// Iterates over changes in this patch.
pub(crate) fn into_changes(self) -> HashMap<ResolvedAddress, ViewChanges> {
self.changes
}
}
impl Snapshot for Patch {
fn get(&self, name: &ResolvedAddress, key: &[u8]) -> Option<Vec<u8>> {
self.changes
.get(name)
.map_or(Err(()), |changes| changes.get(key))
// At this point, `Err(_)` signifies that we need to retrieve data from the snapshot.
.unwrap_or_else(|()| self.snapshot.get(name, key))
}
fn contains(&self, name: &ResolvedAddress, key: &[u8]) -> bool {
self.changes
.get(name)
.map_or(Err(()), |changes| changes.contains(key))
// At this point, `Err(_)` signifies that we need to retrieve data from the snapshot.
.unwrap_or_else(|()| self.snapshot.contains(name, key))
}
fn iter(&self, name: &ResolvedAddress, from: &[u8]) -> Iter<'_> {
let maybe_changes = self.changes.get(name);
let changes_iter = maybe_changes.map(|changes| {
changes
.data
.range::<[u8], _>((Bound::Included(from), Bound::Unbounded))
});
let is_cleared = maybe_changes.map_or(false, ViewChanges::is_cleared);
if is_cleared {
// Ignore all changes from the snapshot.
Box::new(ChangesIter::new(changes_iter.unwrap()))
} else {
Box::new(ForkIter::new(self.snapshot.iter(name, from), changes_iter))
}
}
}
impl RawAccess for &'_ Patch {
type Changes = ();
fn snapshot(&self) -> &dyn Snapshot {
*self as &dyn Snapshot
}
fn changes(&self, _address: &ResolvedAddress) -> Self::Changes {}
}
impl AsReadonly for &'_ Patch {
type Readonly = Self;
fn as_readonly(&self) -> Self::Readonly {
self
}
}
impl Fork {
/// Finalizes all changes that were made after previous execution of the `flush` method.
/// If no `flush` method had been called before, finalizes all changes that were
/// made after creation of `Fork`.
pub fn flush(&mut self) {
let working_patch = mem::replace(&mut self.working_patch, WorkingPatch::new());
working_patch.merge_into(&mut self.patch);
}
/// Finishes a migration of indexes with the specified prefix.
pub(crate) fn flush_migration(&mut self, prefix: &str) {
assert_valid_name_component(prefix);
// Mutable `self` reference ensures that no indexes are instantiated in the client code.
self.flush(); // Flushing is necessary to keep `self.patch` up to date.
// Update aggregation attribution of indexes.
for namespace in self.patch.changed_aggregated_addrs.values_mut() {
if namespace == prefix {
namespace.clear();
}
}
// Move aggregated indexes info from the `prefix` namespace into the default namespace.
SystemSchema::new(&*self).merge_namespace(prefix);
let removed_addrs = IndexesPool::new(&*self).flush_migration(prefix);
for (addr, is_removed_from_aggregation) in removed_addrs {
self.patch.changed_aggregated_addrs.remove(&addr);
if is_removed_from_aggregation {
self.patch
.removed_aggregated_addrs
.insert(addr.name.clone());
}
self.patch.changes.entry(addr).or_default().clear();
}
}
/// Rolls back all changes that were made after the latest execution
/// of the `flush` method.
pub fn rollback(&mut self) {
self.working_patch = WorkingPatch::new();
}
/// Rolls back the migration with the specified name. This will remove all indexes
/// within the migration.
pub(crate) fn rollback_migration(&mut self, prefix: &str) {
assert_valid_name_component(prefix);
self.flush();
SystemSchema::new(&*self).remove_namespace(prefix);
let removed_addrs = IndexesPool::new(&*self).rollback_migration(prefix);
for addr in &removed_addrs {
self.patch.changed_aggregated_addrs.remove(addr);
self.patch.changes.remove(addr);
}
}
/// Converts the fork into `Patch` consuming the fork instance.
pub fn into_patch(mut self) -> Patch {
self.flush();
// Replacing `changed_aggregated_addrs` has a beneficial side-effect: if the patch
// returned by this method is converted back to a `Fork`, we won't need to update
// its state aggregator unless the *new* changes in the `Fork` concern aggregated indexes.
let changed_aggregated_addrs =
mem::replace(&mut self.patch.changed_aggregated_addrs, HashMap::new());
let updated_entries = changed_aggregated_addrs.into_iter().map(|(addr, ns)| {
let index_name = addr.name.clone();
let is_in_migration = !ns.is_empty();
let index_hash = get_object_hash(&self.patch, addr, is_in_migration);
(ns, index_name, index_hash)
});
SystemSchema::new(&self).update_state_aggregators(updated_entries);
let removed_aggregated_addrs =
mem::replace(&mut self.patch.removed_aggregated_addrs, HashSet::new());
SystemSchema::new(&self).remove_aggregated_indexes(removed_aggregated_addrs);
self.flush(); // flushes changes in the state aggregator
self.patch
}
/// Returns a readonly wrapper around the fork. Indexes created based on the readonly
/// version cannot be modified; on the other hand, it is possible to have multiple
/// copies of an index at the same time.
pub fn readonly(&self) -> ReadonlyFork<'_> {
ReadonlyFork(self)
}
}
impl From<Patch> for Fork {
/// Creates a fork based on the provided `patch` and `snapshot`.
///
/// Note: using created fork to modify data already present in `patch` may lead
/// to an inconsistent database state. Hence, this method is useful only if you
/// are sure that the fork and `patch` interacted with different indexes.
fn from(patch: Patch) -> Self {
Self {
patch,
working_patch: WorkingPatch::new(),
}
}
}
impl<'a> RawAccess for &'a Fork {
type Changes = ChangesMut<'a>;
fn snapshot(&self) -> &dyn Snapshot {
&self.patch
}
fn changes(&self, address: &ResolvedAddress) -> Self::Changes {
let changes = self.working_patch.take_view_changes(address);
ChangesMut {
changes,
key: address.clone(),
parent: WorkingPatchRef::Borrowed(&self.working_patch),
}
}
}
impl RawAccess for Rc<Fork> {
type Changes = ChangesMut<'static>;
fn snapshot(&self) -> &dyn Snapshot {
&self.patch
}
fn changes(&self, address: &ResolvedAddress) -> Self::Changes {
let changes = self.working_patch.take_view_changes(address);
ChangesMut {
changes,
key: address.clone(),
parent: WorkingPatchRef::Owned(Self::clone(self)),
}
}
}
/// Readonly wrapper for a `Fork`.
///
/// This wrapper allows to read from index state from the fork
/// in a type-safe manner (it is impossible to accidentally modify data in the index), and
/// without encountering runtime errors when attempting to concurrently get the same index
/// more than once.
///
/// Since the wrapper borrows the `Fork` immutably, it is still possible to access indexes
/// in the fork directly. In this scenario, the caller should be careful that `ReadonlyFork`
/// does not access the same indexes as the original `Fork`: this will result in a runtime
/// error (sort of like attempting both an exclusive and a shared borrow from a `RefCell`
/// or `RwLock`).
///
/// # Examples
///
/// ```
/// # use merkledb::{access::CopyAccessExt, Database, ReadonlyFork, TemporaryDB};
/// let db = TemporaryDB::new();
/// let fork = db.fork();
/// fork.get_list("list").push(1_u32);
/// let readonly: ReadonlyFork<'_> = fork.readonly();
/// let list = readonly.get_list::<_, u32>("list");
/// assert_eq!(list.get(0), Some(1));
/// let same_list = readonly.get_list::<_, u32>("list");
/// // ^-- Does not result in an error!
///
/// // Original fork is still accessible.
/// let mut map = fork.get_map("map");
/// map.put(&1_u32, "foo".to_string());
/// ```
///
/// There are no write methods in indexes instantiated from `ReadonlyFork`:
///
/// ```compile_fail
/// # use merkledb::{access::CopyAccessExt, Database, ReadonlyFork, TemporaryDB};
/// let db = TemporaryDB::new();
/// let fork = db.fork();
/// let readonly: ReadonlyFork<'_> = fork.readonly();
/// let mut list = readonly.get_list("list");
/// list.push(1_u32); // Won't compile: no `push` method in `ListIndex<ReadonlyFork, u32>`!
/// ```
#[derive(Debug, Clone, Copy)]
pub struct ReadonlyFork<'a>(&'a Fork);
impl<'a> AsReadonly for ReadonlyFork<'a> {
type Readonly = Self;
fn as_readonly(&self) -> Self::Readonly {
*self
}
}
impl<'a> AsReadonly for &'a Fork {
type Readonly = ReadonlyFork<'a>;
fn as_readonly(&self) -> Self::Readonly {
ReadonlyFork(*self)
}
}
impl<'a> RawAccess for ReadonlyFork<'a> {
type Changes = ChangesRef<'a>;
fn snapshot(&self) -> &dyn Snapshot {
&self.0.patch
}
fn changes(&self, address: &ResolvedAddress) -> Self::Changes {
ChangesRef {
inner: self.0.working_patch.clone_view_changes(address),
_lifetime: PhantomData,
}
}
}
/// Version of `ReadonlyFork` with a static lifetime. Can be produced from an `Rc<Fork>` using
/// the `AsReadonly` trait.
///
/// Beware that producing an instance increases the reference counter of the underlying fork.
/// If you need to obtain `Fork` from `Rc<Fork>` via [`Rc::try_unwrap`], make sure that all
/// `OwnedReadonlyFork` instances are dropped by this time.
///
/// [`Rc::try_unwrap`]: https://doc.rust-lang.org/std/rc/struct.Rc.html#method.try_unwrap
///
/// # Examples
///
/// ```
/// # use merkledb::{access::AccessExt, AsReadonly, Database, OwnedReadonlyFork, TemporaryDB};
/// # use std::rc::Rc;
/// let db = TemporaryDB::new();
/// let fork = Rc::new(db.fork());
/// fork.get_proof_list("list").extend(vec![1_u32, 2, 3]);
/// let ro_fork: OwnedReadonlyFork = fork.as_readonly();
/// let list = ro_fork.get_proof_list::<_, u32>("list");
/// assert_eq!(list.len(), 3);
/// ```
#[derive(Debug, Clone)]
pub struct OwnedReadonlyFork(Rc<Fork>);
impl RawAccess for OwnedReadonlyFork {
type Changes = ChangesRef<'static>;
fn snapshot(&self) -> &dyn Snapshot {
&self.0.patch
}
fn changes(&self, address: &ResolvedAddress) -> Self::Changes {
ChangesRef {
inner: self.0.working_patch.clone_view_changes(address),
_lifetime: PhantomData,
}
}
}
impl AsReadonly for OwnedReadonlyFork {
type Readonly = Self;
fn as_readonly(&self) -> Self::Readonly {
self.clone()
}
}
impl AsReadonly for Rc<Fork> {
type Readonly = OwnedReadonlyFork;
fn as_readonly(&self) -> Self::Readonly {
OwnedReadonlyFork(self.clone())
}
}
impl AsRef<dyn Snapshot> for dyn Snapshot {
fn as_ref(&self) -> &dyn Snapshot {
self
}
}
impl Snapshot for Box<dyn Snapshot> {
fn get(&self, name: &ResolvedAddress, key: &[u8]) -> Option<Vec<u8>> {
self.as_ref().get(name, key)
}
fn contains(&self, name: &ResolvedAddress, key: &[u8]) -> bool {
self.as_ref().contains(name, key)
}
fn iter(&self, name: &ResolvedAddress, from: &[u8]) -> Iter<'_> {
self.as_ref().iter(name, from)
}
}
impl<'a, T> ForkIter<'a, T>
where
T: StdIterator<Item = (&'a Vec<u8>, &'a Change)>,
{
pub fn new(snapshot: Iter<'a>, changes: Option<T>) -> Self {
ForkIter {
snapshot,
changes: changes.map(StdIterator::peekable),
}
}
#[allow(clippy::option_if_let_else)]
fn step(&mut self) -> NextIterValue {
use std::cmp::Ordering::{Equal, Greater, Less};
if let Some(ref mut changes) = self.changes {
match changes.peek() {
Some(&(k, change)) => match self.snapshot.peek() {
Some((key, ..)) => match *change {
Change::Put(..) => match k[..].cmp(key) {
Equal => NextIterValue::Replaced,
Less => NextIterValue::Inserted,
Greater => NextIterValue::Stored,
},
Change::Delete => match k[..].cmp(key) {
Equal => NextIterValue::Deleted,
Less => NextIterValue::MissDeleted,
Greater => NextIterValue::Stored,
},
},
None => match *change {
Change::Put(..) => NextIterValue::Inserted,
Change::Delete => NextIterValue::MissDeleted,
},
},
None => match self.snapshot.peek() {
Some(..) => NextIterValue::Stored,
None => NextIterValue::Finished,
},
}
} else {
match self.snapshot.peek() {
Some(..) => NextIterValue::Stored,
None => NextIterValue::Finished,
}
}
}
}
impl<'a, T> Iterator for ForkIter<'a, T>
where
T: StdIterator<Item = (&'a Vec<u8>, &'a Change)>,
{
fn next(&mut self) -> Option<(&[u8], &[u8])> {
loop {
match self.step() {
NextIterValue::Stored => return self.snapshot.next(),
NextIterValue::Replaced => {
self.snapshot.next();
return self.changes.as_mut().unwrap().next().map(|(key, change)| {
(
key.as_slice(),
match *change {
Change::Put(ref value) => value.as_slice(),
Change::Delete => unreachable!(),
},
)
});
}
NextIterValue::Inserted => {
return self.changes.as_mut().unwrap().next().map(|(key, change)| {
(
key.as_slice(),
match *change {
Change::Put(ref value) => value.as_slice(),
Change::Delete => unreachable!(),
},
)
});
}
NextIterValue::Deleted => {
self.changes.as_mut().unwrap().next();
self.snapshot.next();
}
NextIterValue::MissDeleted => {
self.changes.as_mut().unwrap().next();
}
NextIterValue::Finished => return None,
}
}
}
fn peek(&mut self) -> Option<(&[u8], &[u8])> {
loop {
match self.step() {
NextIterValue::Stored => return self.snapshot.peek(),
NextIterValue::Replaced | NextIterValue::Inserted => {
return self.changes.as_mut().unwrap().peek().map(|&(key, change)| {
(
key.as_slice(),
match *change {
Change::Put(ref value) => value.as_slice(),
Change::Delete => unreachable!(),
},
)
});
}
NextIterValue::Deleted => {
self.changes.as_mut().unwrap().next();
self.snapshot.next();
}
NextIterValue::MissDeleted => {
self.changes.as_mut().unwrap().next();
}
NextIterValue::Finished => return None,
}
}
}
}
impl fmt::Debug for dyn Database {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Database").finish()
}
}
impl fmt::Debug for dyn Snapshot {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Snapshot").finish()
}
}
impl fmt::Debug for dyn Iterator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Iterator").finish()
}
}
/// The current `MerkleDB` data layout version.
pub const DB_VERSION: u8 = 0;
/// Database metadata address.
pub const DB_METADATA: &str = "__DB_METADATA__";
/// Version attribute name.
pub const VERSION_NAME: &str = "version";
/// This function checks that the given database is compatible with the current `MerkleDB` version.
pub fn check_database(db: &mut dyn Database) -> Result<()> {
let fork = db.fork();
{
let addr = ResolvedAddress::system(DB_METADATA);
let mut view = View::new(&fork, addr);
if let Some(saved_version) = view.get::<_, u8>(VERSION_NAME) {
if saved_version != DB_VERSION {
return Err(Error::new(format!(
"Database version doesn't match: actual {}, expected {}",
saved_version, DB_VERSION
)));
}
return Ok(());
}
view.put(VERSION_NAME, DB_VERSION);
}
db.merge(fork.into_patch())
}
#[cfg(test)]
mod tests {
use super::{
AsReadonly, Change, Database, DatabaseExt, Fork, OwnedReadonlyFork, Patch, Rc,
ResolvedAddress, Snapshot, StdIterator, SystemSchema, View,
};
use crate::{access::CopyAccessExt, ObjectHash, TemporaryDB};
use std::{collections::HashSet, iter::FromIterator};
#[test]
fn readonly_indexes_are_timely_dropped() {
let db = TemporaryDB::new();
let fork = db.fork();
fork.get_list("list").push(1_u64);
{
// The code without an additional scope must not compile.
let _list = fork.readonly().get_list::<_, u64>("list");
}
fork.into_patch();
}
/// Asserts that a patch contains only the specified changes.
fn check_patch<'a, I>(patch: &Patch, changes: I)
where
I: IntoIterator<Item = (&'a str, &'a [u8], Change)>,
{
let mut patch_set: HashSet<_> = HashSet::new();
for (name, changes) in &patch.changes {
for (key, value) in &changes.data {
patch_set.insert((name.to_owned(), key.as_slice(), value.to_owned()));
}
}
let expected_set: HashSet<_> = changes
.into_iter()
.map(|(name, key, change)| (ResolvedAddress::system(name), key, change))
.collect();
assert_eq!(patch_set, expected_set);
}
#[test]
fn backup_data_is_correct() {
let db = TemporaryDB::new();
let fork = db.fork();
{
let mut view = View::new(&fork, "foo");
view.put(&vec![], vec![2]);
}
let backup = db.merge_with_backup(fork.into_patch()).unwrap();
check_patch(&backup, vec![("foo", &[] as &[u8], Change::Delete)]);
let snapshot = db.snapshot();
assert_eq!(snapshot.get(&"foo".into(), &[]), Some(vec![2]));
let fork = db.fork();
{
let mut view = View::new(&fork, "foo");
view.put(&vec![], vec![3]);
let mut view = View::new(&fork, "bar");
view.put(&vec![1], vec![4]);
let mut view = View::new(&fork, "bar2");
view.put(&vec![5], vec![6]);
}
let backup = db.merge_with_backup(fork.into_patch()).unwrap();
check_patch(
&backup,
vec![
("bar2", &[5_u8] as &[u8], Change::Delete),
("bar", &[1], Change::Delete),
("foo", &[], Change::Put(vec![2])),
],
);
// Check that the old snapshot still corresponds to the same DB state.
assert_eq!(snapshot.get(&"foo".into(), &[]), Some(vec![2]));
let snapshot = db.snapshot();
assert_eq!(snapshot.get(&"foo".into(), &[]), Some(vec![3]));
}
#[test]
fn rollback_via_backup_patches() {
let db = TemporaryDB::new();
let fork = db.fork();
{
let mut view = View::new(&fork, "foo");
view.put(&vec![], vec![2]);
}
db.merge(fork.into_patch()).unwrap();
let fork = db.fork();
{
let mut view = View::new(&fork, "foo");
view.put(&vec![], vec![3]);
let mut view = View::new(&fork, "bar");
view.put(&vec![1], vec![4]);
}
let backup = db.merge_with_backup(fork.into_patch()).unwrap();
let snapshot = db.snapshot();
assert_eq!(snapshot.get(&"foo".into(), &[]), Some(vec![3]));
assert_eq!(backup.get(&"foo".into(), &[]), Some(vec![2]));
assert_eq!(backup.get(&"bar".into(), &[1]), None);
db.merge(backup).unwrap();
let snapshot = db.snapshot();
assert_eq!(snapshot.get(&"foo".into(), &[]), Some(vec![2]));
assert_eq!(snapshot.get(&"bar".into(), &[1]), None);
// Check that DB continues working as usual after a rollback.
let fork = db.fork();
{
let mut view = View::new(&fork, "foo");
view.put(&vec![], vec![4]);
view.put(&vec![0, 0], vec![255]);
let mut view = View::new(&fork, "bar");
view.put(&vec![1], vec![253]);
}
let backup1 = db.merge_with_backup(fork.into_patch()).unwrap();
let snapshot = db.snapshot();
assert_eq!(snapshot.get(&"foo".into(), &[]), Some(vec![4]));
assert_eq!(snapshot.get(&"foo".into(), &[0, 0]), Some(vec![255]));
let fork = db.fork();
{
let mut view = View::new(&fork, "bar");
view.put(&vec![1], vec![254]);
}
let backup2 = db.merge_with_backup(fork.into_patch()).unwrap();
let snapshot = db.snapshot();
assert_eq!(snapshot.get(&"foo".into(), &[]), Some(vec![4]));
assert_eq!(snapshot.get(&"foo".into(), &[0, 0]), Some(vec![255]));
assert_eq!(snapshot.get(&"bar".into(), &[1]), Some(vec![254]));
// Check patches used as `Snapshot`s.
assert_eq!(backup1.get(&"bar".into(), &[1]), None);
assert_eq!(backup2.get(&"bar".into(), &[1]), Some(vec![253]));
assert_eq!(backup1.get(&"foo".into(), &[]), Some(vec![2]));
assert_eq!(backup2.get(&"foo".into(), &[]), Some(vec![4]));
// Backups should be applied in the reverse order.
db.merge(backup2).unwrap();
db.merge(backup1).unwrap();
let snapshot = db.snapshot();
assert_eq!(snapshot.get(&"foo".into(), &[]), Some(vec![2]));
assert_eq!(snapshot.get(&"foo".into(), &[0, 0]), None);
assert_eq!(snapshot.get(&"bar".into(), &[1]), None);
}
#[test]
fn backup_after_clearing_view() {
let db = TemporaryDB::new();
let fork = db.fork();
{
let mut view = View::new(&fork, "foo");
view.put(&vec![], vec![1]);
view.put(&vec![1], vec![2]);
}
db.merge(fork.into_patch()).unwrap();
let fork = db.fork();
{
let mut view = View::new(&fork, "foo");
view.clear();
view.put(&vec![1], vec![3]);
view.put(&vec![2], vec![4]);
}
let backup = db.merge_with_backup(fork.into_patch()).unwrap();
assert_eq!(backup.get(&"foo".into(), &[]), Some(vec![1]));
assert_eq!(backup.get(&"foo".into(), &[1]), Some(vec![2]));
assert_eq!(backup.get(&"foo".into(), &[2]), None);
db.merge(backup).unwrap();
let snapshot = db.snapshot();
assert_eq!(snapshot.get(&"foo".into(), &[]), Some(vec![1]));
assert_eq!(snapshot.get(&"foo".into(), &[1]), Some(vec![2]));
assert_eq!(snapshot.get(&"foo".into(), &[2]), None);
}
#[test]
fn backup_reverting_index_creation() {
let db = TemporaryDB::new();
let fork = db.fork();
fork.get_entry("foo").set(1_u32);
db.merge(fork.into_patch()).unwrap();
let fork = db.fork();
fork.get_entry(("foo", &1_u8)).set(2_u32);
let backup = db.merge_with_backup(fork.into_patch()).unwrap();
assert!(backup.index_type(("foo", &1_u8)).is_none());
assert!(backup.get_list::<_, u32>(("foo", &1_u8)).is_empty());
}
#[test]
fn updated_addrs_are_efficiently_updated() {
let db = TemporaryDB::new();
let mut fork = db.fork();
fork.get_proof_list("foo").push(1_u64);
fork.get_proof_map("bar").put(&1_u64, 2_u64);
fork.get_list("baz").push(3_u64);
fork.flush();
let changed_addrs: HashSet<_> = fork
.patch
.changed_aggregated_addrs
.iter()
.map(|(addr, ns)| {
assert!(ns.is_empty());
addr.name.as_str()
})
.collect();
assert_eq!(changed_addrs, HashSet::from_iter(vec!["foo", "bar"]));
let patch = fork.into_patch();
assert!(patch.changed_aggregated_addrs.is_empty());
let mut fork = Fork::from(patch);
fork.get_list("baz").push(3_u64);
fork.flush();
assert!(fork.patch.changed_aggregated_addrs.is_empty());
fork.get_proof_list("other_list").push(42_i32);
fork.get_proof_map::<_, u64, u64>("bar").clear();
fork.flush();
let changed_addrs: HashSet<_> = fork
.patch
.changed_aggregated_addrs
.iter()
.map(|(addr, _)| addr.name.as_str())
.collect();
assert_eq!(changed_addrs, HashSet::from_iter(vec!["bar", "other_list"]));
let patch = fork.into_patch();
let aggregator = SystemSchema::new(&patch).state_aggregator();
assert_eq!(
aggregator.get(&"foo".to_owned()).unwrap(),
patch.get_proof_list::<_, u64>("foo").object_hash()
);
assert_eq!(
aggregator.get(&"bar".to_owned()).unwrap(),
patch.get_proof_map::<_, u64, u64>("bar").object_hash()
);
assert_eq!(
aggregator.get(&"other_list".to_owned()).unwrap(),
patch.get_proof_list::<_, u64>("other_list").object_hash()
);
}
#[test]
fn borrows_from_owned_forks() {
use crate::{access::AccessExt, Entry};
let db = TemporaryDB::new();
let fork = Rc::new(db.fork());
let readonly: OwnedReadonlyFork = fork.as_readonly();
// Modify an index via `fork`.
fork.get_proof_list("list").extend(vec![1_i64, 2, 3]);
// Check that if both `CopyAccessExt` and `AccessExt` traits are in scope, the correct one
// is used for `Rc<Fork>`.
let mut entry: Entry<Rc<Fork>, _> = fork.get_entry("entry");
// Access the list via `readonly`.
let list = readonly.get_proof_list::<_, i64>("list");
assert_eq!(list.len(), 3);
assert_eq!(list.get(1), Some(2));
assert_eq!(list.iter_from(1).collect::<Vec<_>>(), vec![2, 3]);
entry.set("!".to_owned());
drop(entry);
let entry = readonly.get_entry::<_, String>("entry");
// Clone `readonly` access and get another `entry` instance.
let other_readonly = readonly;
let other_entry = other_readonly.get_entry::<_, String>("entry");
assert_eq!(entry.get().unwrap(), "!");
assert_eq!(other_entry.get().unwrap(), "!");
}
#[test]
fn concurrent_borrow_from_fork_and_readonly_fork() {
let db = TemporaryDB::new();
let fork = db.fork();
// This entry is phantom.
let _readonly_entry = fork.readonly().get_entry::<_, u32>(("entry", &1_u8));
// This one is not phantom, but it has the same `ResolvedAddress` as the phantom entry.
// Since phantom entries do not borrow changes from the `Fork`, this works fine.
let _entry = fork.get_entry::<_, u32>("entry");
}
#[test]
fn stale_read_from_phantom_index() {
let db = TemporaryDB::new();
let fork = db.fork();
// Phantom entries are unusual in that they can lead to stale reads (sort of; we assume
// that the database writer is smart enough to separate readonly and read-write parts
// of the `Fork`, e.g., via `Prefixed` accesses).
let phantom_entry = fork.readonly().get_entry::<_, u32>("entry");
let mut entry = fork.get_entry::<_, u32>("entry");
entry.set(1);
assert_eq!(phantom_entry.get(), None);
}
#[test]
#[should_panic(expected = "immutably while it's borrowed mutably")]
fn borrow_from_readonly_fork_after_index_is_created() {
let db = TemporaryDB::new();
let fork = db.fork();
let _entry = fork.get_entry::<_, u32>("entry");
// Since the index is already created, this should lead to a panic.
let _readonly_entry = fork.readonly().get_entry::<_, u32>("entry");
}
}
| 36.592182 | 103 | 0.583578 |
acc9030afb1991971abd7183a839b9f01a413c57 | 7,621 | //! Misc example is a catchall program for testing unrelated features.
//! It's not too instructive/coherent by itself, so please see other examples.
use anchor_lang::prelude::*;
use context::*;
use event::*;
use misc2::Auth;
mod account;
mod context;
mod event;
declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
#[constant]
pub const BASE: u128 = 1_000_000;
#[constant]
pub const DECIMALS: u8 = 6;
pub const NO_IDL: u16 = 55;
#[program]
pub mod misc {
use super::*;
pub const SIZE: u64 = 99;
#[state(SIZE)]
pub struct MyState {
pub v: Vec<u8>,
}
impl MyState {
pub fn new(_ctx: Context<Ctor>) -> Result<Self> {
Ok(Self { v: vec![] })
}
pub fn remaining_accounts(&mut self, ctx: Context<RemainingAccounts>) -> Result<()> {
if ctx.remaining_accounts.len() != 1 {
return Err(ProgramError::Custom(1).into()); // Arbitrary error.
}
Ok(())
}
}
pub fn initialize(ctx: Context<Initialize>, udata: u128, idata: i128) -> Result<()> {
ctx.accounts.data.udata = udata;
ctx.accounts.data.idata = idata;
Ok(())
}
pub fn initialize_no_rent_exempt(ctx: Context<InitializeNoRentExempt>) -> Result<()> {
Ok(())
}
pub fn initialize_skip_rent_exempt(ctx: Context<InitializeSkipRentExempt>) -> Result<()> {
Ok(())
}
pub fn test_owner(_ctx: Context<TestOwner>) -> Result<()> {
Ok(())
}
pub fn test_executable(_ctx: Context<TestExecutable>) -> Result<()> {
Ok(())
}
pub fn test_state_cpi(ctx: Context<TestStateCpi>, data: u64) -> Result<()> {
let cpi_program = ctx.accounts.misc2_program.clone();
let cpi_accounts = Auth {
authority: ctx.accounts.authority.clone(),
};
let ctx = ctx.accounts.cpi_state.context(cpi_program, cpi_accounts);
misc2::cpi::state::set_data(ctx, data)
}
pub fn test_u16(ctx: Context<TestU16>, data: u16) -> Result<()> {
ctx.accounts.my_account.data = data;
Ok(())
}
pub fn test_simulate(_ctx: Context<TestSimulate>, data: u32) -> Result<()> {
emit!(E1 { data });
emit!(E2 { data: 1234 });
emit!(E3 { data: 9 });
Ok(())
}
pub fn test_i8(ctx: Context<TestI8>, data: i8) -> Result<()> {
ctx.accounts.data.data = data;
Ok(())
}
pub fn test_i16(ctx: Context<TestI16>, data: i16) -> Result<()> {
ctx.accounts.data.data = data;
Ok(())
}
pub fn test_const_array_size(ctx: Context<TestConstArraySize>, data: u8) -> Result<()> {
ctx.accounts.data.data[0] = data;
Ok(())
}
pub fn test_close(_ctx: Context<TestClose>) -> Result<()> {
Ok(())
}
pub fn test_instruction_constraint(
_ctx: Context<TestInstructionConstraint>,
_nonce: u8,
) -> Result<()> {
Ok(())
}
pub fn test_pda_init(
ctx: Context<TestPdaInit>,
_domain: String,
_seed: Vec<u8>,
_bump: u8,
) -> Result<()> {
ctx.accounts.my_pda.data = 6;
Ok(())
}
pub fn test_pda_init_zero_copy(ctx: Context<TestPdaInitZeroCopy>) -> Result<()> {
let mut acc = ctx.accounts.my_pda.load_init()?;
acc.data = 9;
acc.bump = *ctx.bumps.get("my_pda").unwrap();
Ok(())
}
pub fn test_pda_mut_zero_copy(ctx: Context<TestPdaMutZeroCopy>) -> Result<()> {
let mut acc = ctx.accounts.my_pda.load_mut()?;
acc.data = 1234;
Ok(())
}
pub fn test_token_seeds_init(_ctx: Context<TestTokenSeedsInit>) -> Result<()> {
Ok(())
}
pub fn default<'info>(
_program_id: &Pubkey,
_accounts: &[AccountInfo<'info>],
_data: &[u8],
) -> Result<()> {
Err(ProgramError::Custom(1234).into())
}
pub fn test_init(ctx: Context<TestInit>) -> Result<()> {
ctx.accounts.data.data = 3;
Ok(())
}
pub fn test_init_zero_copy(ctx: Context<TestInitZeroCopy>) -> Result<()> {
let mut data = ctx.accounts.data.load_init()?;
data.data = 10;
data.bump = 2;
Ok(())
}
pub fn test_init_mint(ctx: Context<TestInitMint>) -> Result<()> {
assert!(ctx.accounts.mint.decimals == 6);
Ok(())
}
pub fn test_init_token(ctx: Context<TestInitToken>) -> Result<()> {
assert!(ctx.accounts.token.mint == ctx.accounts.mint.key());
Ok(())
}
pub fn test_composite_payer(ctx: Context<TestCompositePayer>) -> Result<()> {
ctx.accounts.composite.data.data = 1;
ctx.accounts.data.udata = 2;
ctx.accounts.data.idata = 3;
Ok(())
}
pub fn test_init_associated_token(ctx: Context<TestInitAssociatedToken>) -> Result<()> {
assert!(ctx.accounts.token.mint == ctx.accounts.mint.key());
Ok(())
}
pub fn test_validate_associated_token(
_ctx: Context<TestValidateAssociatedToken>,
) -> Result<()> {
Ok(())
}
pub fn test_fetch_all(ctx: Context<TestFetchAll>, filterable: Pubkey) -> Result<()> {
ctx.accounts.data.authority = ctx.accounts.authority.key();
ctx.accounts.data.filterable = filterable;
Ok(())
}
pub fn test_init_with_empty_seeds(ctx: Context<TestInitWithEmptySeeds>) -> Result<()> {
Ok(())
}
pub fn test_empty_seeds_constraint(ctx: Context<TestEmptySeedsConstraint>) -> Result<()> {
Ok(())
}
pub fn test_init_if_needed(ctx: Context<TestInitIfNeeded>, data: u16) -> Result<()> {
ctx.accounts.data.data = data;
Ok(())
}
pub fn test_init_if_needed_checks_owner(
ctx: Context<TestInitIfNeededChecksOwner>,
) -> Result<()> {
Ok(())
}
pub fn test_init_if_needed_checks_seeds(
ctx: Context<TestInitIfNeededChecksSeeds>,
seed_data: String,
) -> Result<()> {
Ok(())
}
pub fn test_init_mint_if_needed(
ctx: Context<TestInitMintIfNeeded>,
decimals: u8,
) -> Result<()> {
Ok(())
}
pub fn test_init_token_if_needed(ctx: Context<TestInitTokenIfNeeded>) -> Result<()> {
Ok(())
}
pub fn test_init_associated_token_if_needed(
ctx: Context<TestInitAssociatedTokenIfNeeded>,
) -> Result<()> {
Ok(())
}
pub fn init_with_space(ctx: Context<InitWithSpace>, data: u16) -> Result<()> {
Ok(())
}
pub fn test_multidimensional_array(
ctx: Context<TestMultidimensionalArray>,
data: [[u8; 10]; 10],
) -> Result<()> {
ctx.accounts.data.data = data;
Ok(())
}
pub fn test_no_rent_exempt(ctx: Context<NoRentExempt>) -> Result<()> {
Ok(())
}
pub fn test_enforce_rent_exempt(ctx: Context<EnforceRentExempt>) -> Result<()> {
Ok(())
}
pub fn init_decrease_lamports(ctx: Context<InitDecreaseLamports>) -> Result<()> {
**ctx.accounts.data.try_borrow_mut_lamports()? -= 1;
**ctx.accounts.user.try_borrow_mut_lamports()? += 1;
Ok(())
}
pub fn init_if_needed_checks_rent_exemption(
_ctx: Context<InitIfNeededChecksRentExemption>,
) -> Result<()> {
Ok(())
}
pub fn test_program_id_constraint(
_ctx: Context<TestProgramIdConstraint>,
_bump: u8,
_second_bump: u8,
) -> Result<()> {
Ok(())
}
pub fn test_program_id_constraint_find_pda(
_ctx: Context<TestProgramIdConstraintUsingFindPda>,
) -> Result<()> {
Ok(())
}
}
| 26.834507 | 94 | 0.574728 |
5619517aba21795443eab4aff298ef272907858d | 1,599 | use dprint_cli_core::logging::{LoggerTextItem, render_text_items_with_width};
pub struct TableText {
pub lines: Vec<String>,
pub hanging_indent: u16,
}
impl TableText {
pub fn render(&self, indent: u16, terminal_width: Option<u16>) -> String {
let text_items = self.get_logger_text_items(indent);
render_text_items_with_width(&text_items, terminal_width)
}
pub fn get_logger_text_items(&self, indent: u16) -> Vec<LoggerTextItem> {
let mut text_items = Vec::new();
for line in self.lines.iter() {
let mut text = String::new();
if indent > 0 { text.push_str(&" ".repeat(indent as usize)); }
text.push_str(&line);
text_items.push(LoggerTextItem::HangingText {
text,
indent: indent + self.hanging_indent,
});
}
text_items
}
}
pub fn get_table_text(items: Vec<(&str, &str)>) -> TableText {
let largest_name_len = get_largest_string_len(items.iter().map(|(key, _)| *key));
let lines = items.iter().map(|(key, value)| {
let mut text = String::new();
text.push_str(key);
text.push_str(&" ".repeat(largest_name_len - key.len() + 1));
text.push_str(value);
text
}).collect();
TableText {
lines,
hanging_indent: (largest_name_len + 1) as u16,
}
}
fn get_largest_string_len<'a>(items: impl Iterator<Item = &'a str>) -> usize {
let mut key_lens = items.map(|item| item.chars().count()).collect::<Vec<_>>();
key_lens.sort();
key_lens.pop().unwrap_or(0)
} | 31.98 | 85 | 0.602877 |
2f12a4b3bac5724af5982070ecfbfbf7a1664f4f | 31,394 | use num_bigint::BigInt as BigIntValue;
use std::any::Any;
use swc_atoms::JsWord;
use swc_common::Span;
use swc_ecma_ast::*;
use swc_ecma_visit_macros::define;
/// Visitable nodes.
pub trait Node: Any {}
impl<T: ?Sized> Node for T where T: Any {}
define!({
pub struct Class {
pub span: Span,
pub decorators: Vec<Decorator>,
pub body: Vec<ClassMember>,
pub super_class: Option<Box<Expr>>,
pub is_abstract: bool,
pub type_params: Option<TsTypeParamDecl>,
pub super_type_params: Option<TsTypeParamInstantiation>,
pub implements: Vec<TsExprWithTypeArgs>,
}
pub enum ClassMember {
Constructor(Constructor),
Method(ClassMethod),
PrivateMethod(PrivateMethod),
ClassProp(ClassProp),
PrivateProp(PrivateProp),
TsIndexSignature(TsIndexSignature),
}
pub struct ClassProp {
pub span: Span,
pub key: Box<Expr>,
pub value: Option<Box<Expr>>,
pub type_ann: Option<TsTypeAnn>,
pub is_static: bool,
pub decorators: Vec<Decorator>,
pub computed: bool,
pub accessibility: Option<Accessibility>,
pub is_abstract: bool,
pub is_optional: bool,
pub readonly: bool,
pub definite: bool,
}
pub struct PrivateProp {
pub span: Span,
pub key: PrivateName,
pub value: Option<Box<Expr>>,
pub type_ann: Option<TsTypeAnn>,
pub is_static: bool,
pub decorators: Vec<Decorator>,
pub computed: bool,
pub accessibility: Option<Accessibility>,
pub is_abstract: bool,
pub is_optional: bool,
pub readonly: bool,
pub definite: bool,
}
pub struct ClassMethod {
pub span: Span,
pub key: PropName,
pub function: Function,
pub kind: MethodKind,
pub is_static: bool,
pub accessibility: Option<Accessibility>,
pub is_abstract: bool,
pub is_optional: bool,
}
pub struct PrivateMethod {
pub span: Span,
pub key: PrivateName,
pub function: Function,
pub kind: MethodKind,
pub is_static: bool,
pub accessibility: Option<Accessibility>,
pub is_abstract: bool,
pub is_optional: bool,
}
pub struct Constructor {
pub span: Span,
pub key: PropName,
pub params: Vec<ParamOrTsParamProp>,
pub body: Option<BlockStmt>,
pub accessibility: Option<Accessibility>,
pub is_optional: bool,
}
pub struct Decorator {
pub span: Span,
pub expr: Box<Expr>,
}
pub enum MethodKind {
Method,
Getter,
Setter,
}
pub enum Decl {
Class(ClassDecl),
Fn(FnDecl),
Var(VarDecl),
TsInterface(TsInterfaceDecl),
TsTypeAlias(TsTypeAliasDecl),
TsEnum(TsEnumDecl),
TsModule(TsModuleDecl),
}
pub struct FnDecl {
pub ident: Ident,
pub declare: bool,
pub function: Function,
}
pub struct ClassDecl {
pub ident: Ident,
pub declare: bool,
pub class: Class,
}
pub struct VarDecl {
pub span: Span,
pub kind: VarDeclKind,
pub declare: bool,
pub decls: Vec<VarDeclarator>,
}
pub enum VarDeclKind {
Var,
Let,
Const,
}
pub struct VarDeclarator {
pub span: Span,
pub name: Pat,
pub init: Option<Box<Expr>>,
pub definite: bool,
}
pub enum Expr {
This(ThisExpr),
Array(ArrayLit),
Object(ObjectLit),
Fn(FnExpr),
Unary(UnaryExpr),
Update(UpdateExpr),
Bin(BinExpr),
Assign(AssignExpr),
Member(MemberExpr),
Cond(CondExpr),
Call(CallExpr),
New(NewExpr),
Seq(SeqExpr),
Ident(Ident),
Lit(Lit),
Tpl(Tpl),
TaggedTpl(TaggedTpl),
Arrow(ArrowExpr),
Class(ClassExpr),
Yield(YieldExpr),
MetaProp(MetaPropExpr),
Await(AwaitExpr),
Paren(ParenExpr),
JSXMember(JSXMemberExpr),
JSXNamespacedName(JSXNamespacedName),
JSXEmpty(JSXEmptyExpr),
JSXElement(Box<JSXElement>),
JSXFragment(JSXFragment),
TsTypeAssertion(TsTypeAssertion),
TsConstAssertion(TsConstAssertion),
TsNonNull(TsNonNullExpr),
TsTypeCast(TsTypeCastExpr),
TsAs(TsAsExpr),
PrivateName(PrivateName),
OptChain(OptChainExpr),
Invalid(Invalid),
}
pub struct ThisExpr {
pub span: Span,
}
pub struct ArrayLit {
pub span: Span,
pub elems: Vec<Option<ExprOrSpread>>,
}
pub struct ObjectLit {
pub span: Span,
pub props: Vec<PropOrSpread>,
}
pub enum PropOrSpread {
Spread(SpreadElement),
Prop(Box<Prop>),
}
pub struct SpreadElement {
pub dot3_token: Span,
pub expr: Box<Expr>,
}
pub struct UnaryExpr {
pub span: Span,
pub op: UnaryOp,
pub arg: Box<Expr>,
}
pub struct UpdateExpr {
pub span: Span,
pub op: UpdateOp,
pub prefix: bool,
pub arg: Box<Expr>,
}
pub struct BinExpr {
pub span: Span,
pub op: BinaryOp,
pub left: Box<Expr>,
pub right: Box<Expr>,
}
pub struct FnExpr {
pub ident: Option<Ident>,
pub function: Function,
}
pub struct ClassExpr {
pub ident: Option<Ident>,
pub class: Class,
}
pub struct AssignExpr {
pub span: Span,
pub op: AssignOp,
pub left: PatOrExpr,
pub right: Box<Expr>,
}
pub struct MemberExpr {
pub span: Span,
pub obj: ExprOrSuper,
pub prop: Box<Expr>,
pub computed: bool,
}
pub struct CondExpr {
pub span: Span,
pub test: Box<Expr>,
pub cons: Box<Expr>,
pub alt: Box<Expr>,
}
pub struct CallExpr {
pub span: Span,
pub callee: ExprOrSuper,
pub args: Vec<ExprOrSpread>,
pub type_args: Option<TsTypeParamInstantiation>,
}
pub struct NewExpr {
pub span: Span,
pub callee: Box<Expr>,
pub args: Option<Vec<ExprOrSpread>>,
pub type_args: Option<TsTypeParamInstantiation>,
}
pub struct SeqExpr {
pub span: Span,
pub exprs: Vec<Box<Expr>>,
}
pub struct ArrowExpr {
pub span: Span,
pub params: Vec<Pat>,
pub body: BlockStmtOrExpr,
pub is_async: bool,
pub is_generator: bool,
pub type_params: Option<TsTypeParamDecl>,
pub return_type: Option<TsTypeAnn>,
}
pub struct YieldExpr {
pub span: Span,
pub arg: Option<Box<Expr>>,
pub delegate: bool,
}
pub struct MetaPropExpr {
pub meta: Ident,
pub prop: Ident,
}
pub struct AwaitExpr {
pub span: Span,
pub arg: Box<Expr>,
}
pub struct Tpl {
pub span: Span,
pub exprs: Vec<Box<Expr>>,
pub quasis: Vec<TplElement>,
}
pub struct TaggedTpl {
pub span: Span,
pub tag: Box<Expr>,
pub exprs: Vec<Box<Expr>>,
pub quasis: Vec<TplElement>,
pub type_params: Option<TsTypeParamInstantiation>,
}
pub struct TplElement {
pub span: Span,
pub tail: bool,
pub cooked: Option<Str>,
pub raw: Str,
}
pub struct ParenExpr {
pub span: Span,
pub expr: Box<Expr>,
}
pub enum ExprOrSuper {
Super(Super),
Expr(Box<Expr>),
}
pub struct Super {
pub span: Span,
}
pub struct ExprOrSpread {
pub spread: Option<Span>,
pub expr: Box<Expr>,
}
pub enum BlockStmtOrExpr {
BlockStmt(BlockStmt),
Expr(Box<Expr>),
}
pub enum PatOrExpr {
Expr(Box<Expr>),
Pat(Box<Pat>),
}
pub struct OptChainExpr {
pub span: Span,
pub expr: Box<Expr>,
}
pub struct Function {
pub params: Vec<Param>,
pub decorators: Vec<Decorator>,
pub span: Span,
pub body: Option<BlockStmt>,
pub is_generator: bool,
pub is_async: bool,
pub type_params: Option<TsTypeParamDecl>,
pub return_type: Option<TsTypeAnn>,
}
pub struct Param {
pub span: Span,
pub decorators: Vec<Decorator>,
pub pat: Pat,
}
pub enum ParamOrTsParamProp {
TsParamProp(TsParamProp),
Param(Param),
}
pub struct Ident {
pub span: Span,
pub sym: JsWord,
pub type_ann: Option<TsTypeAnn>,
pub optional: bool,
}
pub struct PrivateName {
pub span: Span,
pub id: Ident,
}
pub enum JSXObject {
JSXMemberExpr(Box<JSXMemberExpr>),
Ident(Ident),
}
pub struct JSXMemberExpr {
pub obj: JSXObject,
pub prop: Ident,
}
pub struct JSXNamespacedName {
pub ns: Ident,
pub name: Ident,
}
pub struct JSXEmptyExpr {
pub span: Span,
}
pub struct JSXExprContainer {
pub span: Span,
pub expr: JSXExpr,
}
pub enum JSXExpr {
JSXEmptyExpr(JSXEmptyExpr),
Expr(Box<Expr>),
}
pub struct JSXSpreadChild {
pub span: Span,
pub expr: Box<Expr>,
}
pub enum JSXElementName {
Ident(Ident),
JSXMemberExpr(JSXMemberExpr),
JSXNamespacedName(JSXNamespacedName),
}
pub struct JSXOpeningElement {
pub name: JSXElementName,
pub span: Span,
pub attrs: Vec<JSXAttrOrSpread>,
pub self_closing: bool,
pub type_args: Option<TsTypeParamInstantiation>,
}
pub enum JSXAttrOrSpread {
JSXAttr(JSXAttr),
SpreadElement(SpreadElement),
}
pub struct JSXClosingElement {
pub span: Span,
pub name: JSXElementName,
}
pub struct JSXAttr {
pub span: Span,
pub name: JSXAttrName,
pub value: Option<JSXAttrValue>,
}
pub enum JSXAttrName {
Ident(Ident),
JSXNamespacedName(JSXNamespacedName),
}
pub enum JSXAttrValue {
Lit(Lit),
JSXExprContainer(JSXExprContainer),
JSXElement(Box<JSXElement>),
JSXFragment(JSXFragment),
}
pub struct JSXText {
pub span: Span,
pub value: JsWord,
pub raw: JsWord,
}
pub struct JSXElement {
pub span: Span,
pub opening: JSXOpeningElement,
pub children: Vec<JSXElementChild>,
pub closing: Option<JSXClosingElement>,
}
pub enum JSXElementChild {
JSXText(JSXText),
JSXExprContainer(JSXExprContainer),
JSXSpreadChild(JSXSpreadChild),
JSXElement(Box<JSXElement>),
JSXFragment(JSXFragment),
}
pub struct JSXFragment {
pub span: Span,
pub opening: JSXOpeningFragment,
pub children: Vec<JSXElementChild>,
pub closing: JSXClosingFragment,
}
pub struct JSXOpeningFragment {
pub span: Span,
}
pub struct JSXClosingFragment {
pub span: Span,
}
pub struct Invalid {
pub span: Span,
}
pub enum Lit {
Str(Str),
Bool(Bool),
Null(Null),
Num(Number),
BigInt(BigInt),
Regex(Regex),
JSXText(JSXText),
}
pub struct BigInt {
pub span: Span,
pub value: BigIntValue,
}
pub struct Str {
pub span: Span,
pub value: JsWord,
pub has_escape: bool,
}
pub struct Bool {
pub span: Span,
pub value: bool,
}
pub struct Null {
pub span: Span,
}
pub struct Regex {
pub span: Span,
pub exp: JsWord,
pub flags: JsWord,
}
pub struct Number {
pub span: Span,
pub value: f64,
}
pub enum Program {
Module(Module),
Script(Script),
}
pub struct Module {
pub span: Span,
pub body: Vec<ModuleItem>,
pub shebang: Option<JsWord>,
}
pub struct Script {
pub span: Span,
pub body: Vec<Stmt>,
pub shebang: Option<JsWord>,
}
pub enum ModuleItem {
ModuleDecl(ModuleDecl),
Stmt(Stmt),
}
pub enum ModuleDecl {
Import(ImportDecl),
ExportDecl(ExportDecl),
ExportNamed(NamedExport),
ExportDefaultDecl(ExportDefaultDecl),
ExportDefaultExpr(ExportDefaultExpr),
ExportAll(ExportAll),
TsImportEquals(TsImportEqualsDecl),
TsExportAssignment(TsExportAssignment),
TsNamespaceExport(TsNamespaceExportDecl),
}
pub struct ExportDefaultExpr {
pub span: Span,
pub expr: Box<Expr>,
}
pub struct ExportDecl {
pub span: Span,
pub decl: Decl,
}
pub struct ImportDecl {
pub span: Span,
pub specifiers: Vec<ImportSpecifier>,
pub src: Str,
pub type_only: bool,
}
pub struct ExportAll {
pub span: Span,
pub src: Str,
}
pub struct NamedExport {
pub span: Span,
pub specifiers: Vec<ExportSpecifier>,
pub src: Option<Str>,
pub type_only: bool,
}
pub struct ExportDefaultDecl {
pub span: Span,
pub decl: DefaultDecl,
}
pub enum DefaultDecl {
Class(ClassExpr),
Fn(FnExpr),
TsInterfaceDecl(TsInterfaceDecl),
}
pub enum ImportSpecifier {
Named(ImportNamedSpecifier),
Default(ImportDefaultSpecifier),
Namespace(ImportStarAsSpecifier),
}
pub struct ImportDefaultSpecifier {
pub span: Span,
pub local: Ident,
}
pub struct ImportStarAsSpecifier {
pub span: Span,
pub local: Ident,
}
pub struct ImportNamedSpecifier {
pub span: Span,
pub local: Ident,
pub imported: Option<Ident>,
}
pub enum ExportSpecifier {
Namespace(ExportNamespaceSpecifier),
Default(ExportDefaultSpecifier),
Named(ExportNamedSpecifier),
}
pub struct ExportNamespaceSpecifier {
pub span: Span,
pub name: Ident,
}
pub struct ExportDefaultSpecifier {
pub exported: Ident,
}
pub struct ExportNamedSpecifier {
pub span: Span,
pub orig: Ident,
pub exported: Option<Ident>,
}
pub enum BinaryOp {
EqEq,
NotEq,
EqEqEq,
NotEqEq,
Lt,
LtEq,
Gt,
GtEq,
LShift,
RShift,
ZeroFillRShift,
Add,
Sub,
Mul,
Div,
Mod,
BitOr,
BitXor,
BitAnd,
LogicalOr,
LogicalAnd,
In,
InstanceOf,
Exp,
NullishCoalescing,
}
pub enum AssignOp {
Assign,
AddAssign,
SubAssign,
MulAssign,
DivAssign,
ModAssign,
LShiftAssign,
RShiftAssign,
ZeroFillRShiftAssign,
BitOrAssign,
BitXorAssign,
BitAndAssign,
ExpAssign,
AndAssign,
OrAssign,
NullishAssign,
}
pub enum UpdateOp {
PlusPlus,
MinusMinus,
}
pub enum UnaryOp {
Minus,
Plus,
Bang,
Tilde,
TypeOf,
Void,
Delete,
}
pub enum Pat {
Ident(Ident),
Array(ArrayPat),
Rest(RestPat),
Object(ObjectPat),
Assign(AssignPat),
Invalid(Invalid),
Expr(Box<Expr>),
}
pub struct ArrayPat {
pub span: Span,
pub elems: Vec<Option<Pat>>,
pub optional: bool,
pub type_ann: Option<TsTypeAnn>,
}
pub struct ObjectPat {
pub span: Span,
pub props: Vec<ObjectPatProp>,
pub optional: bool,
pub type_ann: Option<TsTypeAnn>,
}
pub struct AssignPat {
pub span: Span,
pub left: Box<Pat>,
pub right: Box<Expr>,
pub type_ann: Option<TsTypeAnn>,
}
pub struct RestPat {
pub span: Span,
pub dot3_token: Span,
pub arg: Box<Pat>,
pub type_ann: Option<TsTypeAnn>,
}
pub enum ObjectPatProp {
KeyValue(KeyValuePatProp),
Assign(AssignPatProp),
Rest(RestPat),
}
pub struct KeyValuePatProp {
pub key: PropName,
pub value: Box<Pat>,
}
pub struct AssignPatProp {
pub span: Span,
pub key: Ident,
pub value: Option<Box<Expr>>,
}
pub enum Prop {
Shorthand(Ident),
KeyValue(KeyValueProp),
Assign(AssignProp),
Getter(GetterProp),
Setter(SetterProp),
Method(MethodProp),
}
pub struct KeyValueProp {
pub key: PropName,
pub value: Box<Expr>,
}
pub struct AssignProp {
pub key: Ident,
pub value: Box<Expr>,
}
pub struct GetterProp {
pub span: Span,
pub key: PropName,
pub type_ann: Option<TsTypeAnn>,
pub body: Option<BlockStmt>,
}
pub struct SetterProp {
pub span: Span,
pub key: PropName,
pub param: Pat,
pub body: Option<BlockStmt>,
}
pub struct MethodProp {
pub key: PropName,
pub function: Function,
}
pub enum PropName {
Ident(Ident),
Str(Str),
Num(Number),
Computed(ComputedPropName),
}
pub struct ComputedPropName {
pub span: Span,
pub expr: Box<Expr>,
}
pub struct BlockStmt {
pub span: Span,
pub stmts: Vec<Stmt>,
}
pub enum Stmt {
Block(BlockStmt),
Empty(EmptyStmt),
Debugger(DebuggerStmt),
With(WithStmt),
Return(ReturnStmt),
Labeled(LabeledStmt),
Break(BreakStmt),
Continue(ContinueStmt),
If(IfStmt),
Switch(SwitchStmt),
Throw(ThrowStmt),
Try(TryStmt),
While(WhileStmt),
DoWhile(DoWhileStmt),
For(ForStmt),
ForIn(ForInStmt),
ForOf(ForOfStmt),
Decl(Decl),
Expr(ExprStmt),
}
pub struct ExprStmt {
pub span: Span,
pub expr: Box<Expr>,
}
pub struct EmptyStmt {
pub span: Span,
}
pub struct DebuggerStmt {
pub span: Span,
}
pub struct WithStmt {
pub span: Span,
pub obj: Box<Expr>,
pub body: Box<Stmt>,
}
pub struct ReturnStmt {
pub span: Span,
pub arg: Option<Box<Expr>>,
}
pub struct LabeledStmt {
pub span: Span,
pub label: Ident,
pub body: Box<Stmt>,
}
pub struct BreakStmt {
pub span: Span,
pub label: Option<Ident>,
}
pub struct ContinueStmt {
pub span: Span,
pub label: Option<Ident>,
}
pub struct IfStmt {
pub span: Span,
pub test: Box<Expr>,
pub cons: Box<Stmt>,
pub alt: Option<Box<Stmt>>,
}
pub struct SwitchStmt {
pub span: Span,
pub discriminant: Box<Expr>,
pub cases: Vec<SwitchCase>,
}
pub struct ThrowStmt {
pub span: Span,
pub arg: Box<Expr>,
}
pub struct TryStmt {
pub span: Span,
pub block: BlockStmt,
pub handler: Option<CatchClause>,
pub finalizer: Option<BlockStmt>,
}
pub struct WhileStmt {
pub span: Span,
pub test: Box<Expr>,
pub body: Box<Stmt>,
}
pub struct DoWhileStmt {
pub span: Span,
pub test: Box<Expr>,
pub body: Box<Stmt>,
}
pub struct ForStmt {
pub span: Span,
pub init: Option<VarDeclOrExpr>,
pub test: Option<Box<Expr>>,
pub update: Option<Box<Expr>>,
pub body: Box<Stmt>,
}
pub struct ForInStmt {
pub span: Span,
pub left: VarDeclOrPat,
pub right: Box<Expr>,
pub body: Box<Stmt>,
}
pub struct ForOfStmt {
pub span: Span,
pub await_token: Option<Span>,
pub left: VarDeclOrPat,
pub right: Box<Expr>,
pub body: Box<Stmt>,
}
pub struct SwitchCase {
pub span: Span,
pub test: Option<Box<Expr>>,
pub cons: Vec<Stmt>,
}
pub struct CatchClause {
pub span: Span,
pub param: Option<Pat>,
pub body: BlockStmt,
}
pub enum VarDeclOrPat {
VarDecl(VarDecl),
Pat(Pat),
}
pub enum VarDeclOrExpr {
VarDecl(VarDecl),
Expr(Box<Expr>),
}
pub struct TsTypeAnn {
pub span: Span,
pub type_ann: Box<TsType>,
}
pub struct TsTypeParamDecl {
pub span: Span,
pub params: Vec<TsTypeParam>,
}
pub struct TsTypeParam {
pub span: Span,
pub name: Ident,
pub constraint: Option<Box<TsType>>,
pub default: Option<Box<TsType>>,
}
pub struct TsTypeParamInstantiation {
pub span: Span,
pub params: Vec<Box<TsType>>,
}
pub struct TsTypeCastExpr {
pub span: Span,
pub expr: Box<Expr>,
pub type_ann: TsTypeAnn,
}
pub struct TsParamProp {
pub span: Span,
pub decorators: Vec<Decorator>,
pub accessibility: Option<Accessibility>,
pub readonly: bool,
pub param: TsParamPropParam,
}
pub enum TsParamPropParam {
Ident(Ident),
Assign(AssignPat),
}
pub struct TsQualifiedName {
pub left: TsEntityName,
pub right: Ident,
}
pub enum TsEntityName {
TsQualifiedName(Box<TsQualifiedName>),
Ident(Ident),
}
pub enum TsSignatureDecl {
TsCallSignatureDecl(TsCallSignatureDecl),
TsConstructSignatureDecl(TsConstructSignatureDecl),
TsMethodSignature(TsMethodSignature),
TsFnType(TsFnType),
TsConstructorType(TsConstructorType),
}
pub enum TsTypeElement {
TsCallSignatureDecl(TsCallSignatureDecl),
TsConstructSignatureDecl(TsConstructSignatureDecl),
TsPropertySignature(TsPropertySignature),
TsMethodSignature(TsMethodSignature),
TsIndexSignature(TsIndexSignature),
}
pub struct TsCallSignatureDecl {
pub span: Span,
pub params: Vec<TsFnParam>,
pub type_ann: Option<TsTypeAnn>,
pub type_params: Option<TsTypeParamDecl>,
}
pub struct TsConstructSignatureDecl {
pub span: Span,
pub params: Vec<TsFnParam>,
pub type_ann: Option<TsTypeAnn>,
pub type_params: Option<TsTypeParamDecl>,
}
pub struct TsPropertySignature {
pub span: Span,
pub readonly: bool,
pub key: Box<Expr>,
pub computed: bool,
pub optional: bool,
pub init: Option<Box<Expr>>,
pub params: Vec<TsFnParam>,
pub type_ann: Option<TsTypeAnn>,
pub type_params: Option<TsTypeParamDecl>,
}
pub struct TsMethodSignature {
pub span: Span,
pub readonly: bool,
pub key: Box<Expr>,
pub computed: bool,
pub optional: bool,
pub params: Vec<TsFnParam>,
pub type_ann: Option<TsTypeAnn>,
pub type_params: Option<TsTypeParamDecl>,
}
pub struct TsIndexSignature {
pub params: Vec<TsFnParam>,
pub type_ann: Option<TsTypeAnn>,
pub readonly: bool,
pub span: Span,
}
pub enum TsType {
TsKeywordType(TsKeywordType),
TsThisType(TsThisType),
TsFnOrConstructorType(TsFnOrConstructorType),
TsTypeRef(TsTypeRef),
TsTypeQuery(TsTypeQuery),
TsTypeLit(TsTypeLit),
TsArrayType(TsArrayType),
TsTupleType(TsTupleType),
TsOptionalType(TsOptionalType),
TsRestType(TsRestType),
TsUnionOrIntersectionType(TsUnionOrIntersectionType),
TsConditionalType(TsConditionalType),
TsInferType(TsInferType),
TsParenthesizedType(TsParenthesizedType),
TsTypeOperator(TsTypeOperator),
TsIndexedAccessType(TsIndexedAccessType),
TsMappedType(TsMappedType),
TsLitType(TsLitType),
TsTypePredicate(TsTypePredicate),
TsImportType(TsImportType),
}
pub enum TsFnOrConstructorType {
TsFnType(TsFnType),
TsConstructorType(TsConstructorType),
}
pub struct TsKeywordType {
pub span: Span,
pub kind: TsKeywordTypeKind,
}
pub enum TsKeywordTypeKind {
TsAnyKeyword,
TsUnknownKeyword,
TsNumberKeyword,
TsObjectKeyword,
TsBooleanKeyword,
TsBigIntKeyword,
TsStringKeyword,
TsSymbolKeyword,
TsVoidKeyword,
TsUndefinedKeyword,
TsNullKeyword,
TsNeverKeyword,
}
pub struct TsThisType {
pub span: Span,
}
pub enum TsFnParam {
Ident(Ident),
Array(ArrayPat),
Rest(RestPat),
Object(ObjectPat),
}
pub struct TsFnType {
pub span: Span,
pub params: Vec<TsFnParam>,
pub type_params: Option<TsTypeParamDecl>,
pub type_ann: TsTypeAnn,
}
pub struct TsConstructorType {
pub span: Span,
pub params: Vec<TsFnParam>,
pub type_params: Option<TsTypeParamDecl>,
pub type_ann: TsTypeAnn,
}
pub struct TsTypeRef {
pub span: Span,
pub type_name: TsEntityName,
pub type_params: Option<TsTypeParamInstantiation>,
}
pub struct TsTypePredicate {
pub span: Span,
pub asserts: bool,
pub param_name: TsThisTypeOrIdent,
pub type_ann: Option<TsTypeAnn>,
}
pub enum TsThisTypeOrIdent {
TsThisType(TsThisType),
Ident(Ident),
}
pub struct TsTypeQuery {
pub span: Span,
pub expr_name: TsTypeQueryExpr,
}
pub enum TsTypeQueryExpr {
TsEntityName(TsEntityName),
Import(TsImportType),
}
pub struct TsImportType {
pub span: Span,
pub arg: Str,
pub qualifier: Option<TsEntityName>,
pub type_args: Option<TsTypeParamInstantiation>,
}
pub struct TsTypeLit {
pub span: Span,
pub members: Vec<TsTypeElement>,
}
pub struct TsArrayType {
pub span: Span,
pub elem_type: Box<TsType>,
}
pub struct TsTupleType {
pub span: Span,
pub elem_types: Vec<TsTupleElement>,
}
pub struct TsTupleElement {
pub span: Span,
pub label: Option<Ident>,
pub ty: TsType,
}
pub struct TsOptionalType {
pub span: Span,
pub type_ann: Box<TsType>,
}
pub struct TsRestType {
pub span: Span,
pub type_ann: Box<TsType>,
}
pub enum TsUnionOrIntersectionType {
TsUnionType(TsUnionType),
TsIntersectionType(TsIntersectionType),
}
pub struct TsUnionType {
pub span: Span,
pub types: Vec<Box<TsType>>,
}
pub struct TsIntersectionType {
pub span: Span,
pub types: Vec<Box<TsType>>,
}
pub struct TsConditionalType {
pub span: Span,
pub check_type: Box<TsType>,
pub extends_type: Box<TsType>,
pub true_type: Box<TsType>,
pub false_type: Box<TsType>,
}
pub struct TsInferType {
pub span: Span,
pub type_param: TsTypeParam,
}
pub struct TsParenthesizedType {
pub span: Span,
pub type_ann: Box<TsType>,
}
pub struct TsTypeOperator {
pub span: Span,
pub op: TsTypeOperatorOp,
pub type_ann: Box<TsType>,
}
pub enum TsTypeOperatorOp {
KeyOf,
Unique,
ReadOnly,
}
pub struct TsIndexedAccessType {
pub span: Span,
pub readonly: bool,
pub obj_type: Box<TsType>,
pub index_type: Box<TsType>,
}
pub enum TruePlusMinus {
True,
Plus,
Minus,
}
pub struct TsMappedType {
pub span: Span,
pub readonly: Option<TruePlusMinus>,
pub type_param: TsTypeParam,
pub optional: Option<TruePlusMinus>,
pub type_ann: Option<Box<TsType>>,
}
pub struct TsLitType {
pub span: Span,
pub lit: TsLit,
}
pub enum TsLit {
Number(Number),
Str(Str),
Bool(Bool),
Tpl(Tpl),
}
pub struct TsInterfaceDecl {
pub span: Span,
pub id: Ident,
pub declare: bool,
pub type_params: Option<TsTypeParamDecl>,
pub extends: Vec<TsExprWithTypeArgs>,
pub body: TsInterfaceBody,
}
pub struct TsInterfaceBody {
pub span: Span,
pub body: Vec<TsTypeElement>,
}
pub struct TsExprWithTypeArgs {
pub span: Span,
pub expr: TsEntityName,
pub type_args: Option<TsTypeParamInstantiation>,
}
pub struct TsTypeAliasDecl {
pub span: Span,
pub declare: bool,
pub id: Ident,
pub type_params: Option<TsTypeParamDecl>,
pub type_ann: Box<TsType>,
}
pub struct TsEnumDecl {
pub span: Span,
pub declare: bool,
pub is_const: bool,
pub id: Ident,
pub members: Vec<TsEnumMember>,
}
pub struct TsEnumMember {
pub span: Span,
pub id: TsEnumMemberId,
pub init: Option<Box<Expr>>,
}
pub enum TsEnumMemberId {
Ident(Ident),
Str(Str),
}
pub struct TsModuleDecl {
pub span: Span,
pub declare: bool,
pub global: bool,
pub id: TsModuleName,
pub body: Option<TsNamespaceBody>,
}
pub enum TsNamespaceBody {
TsModuleBlock(TsModuleBlock),
TsNamespaceDecl(TsNamespaceDecl),
}
pub struct TsModuleBlock {
pub span: Span,
pub body: Vec<ModuleItem>,
}
pub struct TsNamespaceDecl {
pub span: Span,
pub declare: bool,
pub global: bool,
pub id: Ident,
pub body: Box<TsNamespaceBody>,
}
pub enum TsModuleName {
Ident(Ident),
Str(Str),
}
pub struct TsImportEqualsDecl {
pub span: Span,
pub declare: bool,
pub is_export: bool,
pub id: Ident,
pub module_ref: TsModuleRef,
}
pub enum TsModuleRef {
TsEntityName(TsEntityName),
TsExternalModuleRef(TsExternalModuleRef),
}
pub struct TsExternalModuleRef {
pub span: Span,
pub expr: Str,
}
pub struct TsExportAssignment {
pub span: Span,
pub expr: Box<Expr>,
}
pub struct TsNamespaceExportDecl {
pub span: Span,
pub id: Ident,
}
pub struct TsAsExpr {
pub span: Span,
pub expr: Box<Expr>,
pub type_ann: Box<TsType>,
}
pub struct TsTypeAssertion {
pub span: Span,
pub expr: Box<Expr>,
pub type_ann: Box<TsType>,
}
pub struct TsNonNullExpr {
pub span: Span,
pub expr: Box<Expr>,
}
pub enum Accessibility {
Public,
Protected,
Private,
}
pub struct TsConstAssertion {
pub span: Span,
pub expr: Box<Expr>,
}
});
| 25.256637 | 64 | 0.565076 |
9c4ab19b84978152cefc6bc4d6d5aac07824fc10 | 1,338 | // Copyright (c) 2021, Roel Schut. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
use crate::*;
use crate::utils::convert::TryInstanceFrom;
#[derive(NativeClass)]
#[inherit(Sprite)]
pub struct PlayerBullet {
#[property(default = 100.0)]
speed: f32,
#[property(default = 1)]
damage: u8,
}
#[methods]
impl PlayerBullet {
fn new(_owner: &Sprite) -> Self {
PlayerBullet {
speed: 100.0,
damage: 1,
}
}
pub fn get_damage(&self) -> u8 { self.damage }
#[export]
fn _process(&self, owner: &Sprite, delta: f32) {
let mut pos = owner.global_position();
pos.x += self.speed * delta;
owner.set_global_position(pos);
if pos.x > 180.0 {
owner.queue_free();
}
}
}
impl TryInstanceFrom<Self, Sprite> for PlayerBullet {}
// impl<'l> TryFrom<Option<Ref<Node>>> for PlayerBullet {
// type Error = ();
//
// fn try_instance_from(node: Option<Ref<Node>>) -> Result<RefInstance<'l, Self, Shared>, Self::Error> {
// node.map(|node| unsafe { node.assume_safe() })
// .and_then(|node| node.cast::<Sprite>())
// .and_then(|node| node.cast_instance::<Self>())
// .ok_or(Self::Error)
// }
// } | 26.235294 | 108 | 0.578475 |
486564bde37dcb71c3b68f5cc743e812972ab0bf | 1,721 | // spell-checker:ignore getconf
use std::fmt::{self, Display, Formatter};
#[cfg(any(target_os = "linux", target_os = "macos"))]
use std::process::{Command, Output};
/// Operating system architecture in terms of how many bits compose the basic values it can deal with.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Bitness {
/// Unknown bitness (unable to determine).
Unknown,
/// 32-bit.
X32,
/// 64-bit.
X64,
}
impl Display for Bitness {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match *self {
Bitness::Unknown => write!(f, "unknown bitness"),
Bitness::X32 => write!(f, "32-bit"),
Bitness::X64 => write!(f, "64-bit"),
}
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub fn get() -> Bitness {
match &Command::new("getconf").arg("LONG_BIT").output() {
Ok(Output { stdout, .. }) if stdout == b"32\n" => Bitness::X32,
Ok(Output { stdout, .. }) if stdout == b"64\n" => Bitness::X64,
_ => Bitness::Unknown,
}
}
#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
mod tests {
use super::*;
use pretty_assertions::assert_ne;
#[test]
fn get_bitness() {
let b = get();
assert_ne!(b, Bitness::Unknown);
}
#[test]
fn display() {
let data = [
(Bitness::Unknown, "unknown bitness"),
(Bitness::X32, "32-bit"),
(Bitness::X64, "64-bit"),
];
for (bitness, expected) in &data {
assert_eq!(&bitness.to_string(), expected);
}
}
}
| 27.31746 | 102 | 0.558977 |
e4e548a7c63681869453f1490079ee9aa7ac5331 | 30,201 | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module supports translations of specifications as found in the move-model to
//! expressions which can be used in assumes/asserts in bytecode.
use codespan_reporting::diagnostic::Severity;
use itertools::Itertools;
use std::collections::{BTreeMap, BTreeSet};
use crate::{
ast::{
Condition, ConditionKind, Exp, ExpData, GlobalInvariant, LocalVarDecl, MemoryLabel,
Operation, Spec, TempIndex, TraceKind,
},
exp_generator::ExpGenerator,
exp_rewriter::ExpRewriterFunctions,
model::{FunctionEnv, GlobalId, Loc, NodeId, QualifiedInstId, SpecVarId, StructId},
pragmas::{
ABORTS_IF_IS_STRICT_PRAGMA, CONDITION_ABSTRACT_PROP, CONDITION_CONCRETE_PROP,
CONDITION_EXPORT_PROP, CONDITION_INJECTED_PROP,
},
symbol::Symbol,
ty::{PrimitiveType, Type},
};
/// A helper which reduces specification conditions to assume/assert statements.
pub struct SpecTranslator<'a, 'b, T: ExpGenerator<'a>> {
/// Whether we should autogenerate TRACE calls for top-level expressions of the VC.
auto_trace: bool,
/// The builder for the function we are currently translating.
/// Note this is not necessarily the same as the function for which we translate specs.
/// The builder must implement the expression generation trait.
builder: &'b mut T,
/// The function for which we translate specifications.
fun_env: &'b FunctionEnv<'a>,
/// The type instantiation of the function.
type_args: &'b [Type],
/// An optional substitution for parameters of the above function.
param_substitution: Option<&'b [TempIndex]>,
/// Whether we translate the expression in a post state.
in_post_state: bool,
/// An optional substitution for return vales.
ret_locals: &'b [TempIndex],
/// A set of locals which are declared by outer block, lambda, or quant expressions.
shadowed: Vec<BTreeSet<Symbol>>,
/// A map from let symbols to temporaries allocated for them.
let_locals: BTreeMap<Symbol, TempIndex>,
/// The translated spec.
result: TranslatedSpec,
/// Whether we are in "old" (pre-state) context
in_old: bool,
}
/// Represents a translated spec.
#[derive(Default)]
pub struct TranslatedSpec {
pub saved_memory: BTreeMap<QualifiedInstId<StructId>, MemoryLabel>,
pub saved_spec_vars: BTreeMap<QualifiedInstId<SpecVarId>, MemoryLabel>,
pub saved_params: BTreeMap<TempIndex, TempIndex>,
pub debug_traces: Vec<(NodeId, TraceKind, Exp)>,
pub pre: Vec<(Loc, Exp)>,
pub post: Vec<(Loc, Exp)>,
pub aborts: Vec<(Loc, Exp, Option<Exp>)>,
pub aborts_with: Vec<(Loc, Vec<Exp>)>,
pub emits: Vec<(Loc, Exp, Exp, Option<Exp>)>,
pub modifies: Vec<(Loc, Exp)>,
pub invariants: Vec<(Loc, GlobalId, Exp)>,
pub lets: Vec<(Loc, bool, TempIndex, Exp)>,
pub updates: Vec<(Loc, Exp, Exp)>,
}
impl TranslatedSpec {
/// Creates a boolean expression which describes the overall abort condition. This is
/// a disjunction of the individual abort conditions.
pub fn aborts_condition<'a, T: ExpGenerator<'a>>(&self, builder: &T) -> Option<Exp> {
builder.mk_join_bool(Operation::Or, self.aborts.iter().map(|(_, e, _)| e.clone()))
}
/// Creates a boolean expression which describes the overall condition which constraints
/// the abort code.
///
/// Let (P1, C1)..(Pj, Cj) be aborts_if with a code, Pk..Pl aborts_if without a code, and the
/// Cm..Cn standalone aborts codes from an aborts_with:
///
/// ```notrust
/// P1 && abort_code == C1 || .. || Pj && abort_code == Cj
/// || Pk || .. || Pl
/// || abort_code == Cm || .. || abort_code == Cn
/// ```
///
/// This characterizes the allowed value of the code. In the presence of aborts_if with code,
/// whenever the aborts condition is true, the code must also be the specified ones. Notice
/// that still allows any other member of the disjunction to make the overall condition true.
/// Specifically, if someone specifies `aborts_if P with C1; aborts_with C2`, then even if
/// P is true, C2 is allowed as an abort code.
pub fn aborts_code_condition<'a, T: ExpGenerator<'a>>(
&self,
builder: &T,
actual_code: &Exp,
) -> Option<Exp> {
let eq_code = |e: &Exp| builder.mk_eq(e.clone(), actual_code.clone());
builder.mk_join_bool(
Operation::Or,
self.aborts
.iter()
.map(|(_, exp, code)| {
builder
.mk_join_opt_bool(
Operation::And,
Some(exp.clone()),
code.as_ref().map(|c| eq_code(c)),
)
.unwrap()
})
.chain(
self.aborts_with
.iter()
.map(|(_, codes)| codes.iter())
.flatten()
.map(|c| eq_code(c)),
),
)
}
/// Returns true if there are any specs about the abort code.
pub fn has_aborts_code_specs(&self) -> bool {
!self.aborts_with.is_empty() || self.aborts.iter().any(|(_, _, c)| c.is_some())
}
/// Return an iterator of effective pre conditions.
pub fn pre_conditions<'a, T: ExpGenerator<'a>>(
&self,
_builder: &T,
) -> impl Iterator<Item = (Loc, Exp)> + '_ {
self.pre.iter().cloned()
}
/// Returns a sequence of EventStoreIncludes expressions which verify the `emits` clauses of a
/// function spec. While logically we could generate a single EventStoreIncludes, for better
/// error reporting we construct incrementally multiple EventStoreIncludes expressions with some
/// redundancy for each individual `emits, so we the see the exact failure at the right
/// emit condition.
pub fn emits_conditions<'a, T: ExpGenerator<'a>>(&self, builder: &T) -> Vec<(Loc, Exp)> {
let es_ty = Type::Primitive(PrimitiveType::EventStore);
let mut result = vec![];
for i in 0..self.emits.len() {
let loc = self.emits[i].0.clone();
let es = self.build_event_store(
builder,
builder.mk_call(&es_ty, Operation::EmptyEventStore, vec![]),
&self.emits[0..i + 1],
);
result.push((
loc,
builder.mk_bool_call(Operation::EventStoreIncludes, vec![es]),
));
}
result
}
pub fn emits_completeness_condition<'a, T: ExpGenerator<'a>>(&self, builder: &T) -> Exp {
let es_ty = Type::Primitive(PrimitiveType::EventStore);
let es = self.build_event_store(
builder,
builder.mk_call(&es_ty, Operation::EmptyEventStore, vec![]),
&self.emits,
);
builder.mk_bool_call(Operation::EventStoreIncludedIn, vec![es])
}
fn build_event_store<'a, T: ExpGenerator<'a>>(
&self,
builder: &T,
es: Exp,
emits: &[(Loc, Exp, Exp, Option<Exp>)],
) -> Exp {
if emits.is_empty() {
es
} else {
let (_, event, handle, cond) = &emits[0];
let mut args = vec![es, event.clone(), handle.clone()];
if let Some(c) = cond {
args.push(c.clone())
}
let es_ty = Type::Primitive(PrimitiveType::EventStore);
let extend_exp = builder.mk_call(&es_ty, Operation::ExtendEventStore, args);
self.build_event_store(builder, extend_exp, &emits[1..])
}
}
}
impl<'a, 'b, T: ExpGenerator<'a>> SpecTranslator<'a, 'b, T> {
/// Translates the specification of function `fun_env`. This can happen for a call of the
/// function or for its definition (parameter `for_call`). This will process all the
/// conditions found in the spec block of the function, dealing with references to `old(..)`,
/// and creating respective memory/spec var saves. If `for_call` is true, abort conditions
/// will be translated for the current state, otherwise they will be treated as in an `old`.
/// and creating respective memory/spec var saves. It also allows to provide type arguments
/// with which the specifications are instantiated, as well as a substitution for temporaries.
/// The later two parameters are used to instantiate a function specification for a given
/// call context.
pub fn translate_fun_spec(
auto_trace: bool,
for_call: bool,
builder: &'b mut T,
fun_env: &'b FunctionEnv<'a>,
type_args: &[Type],
param_substitution: Option<&'b [TempIndex]>,
ret_locals: &'b [TempIndex],
) -> TranslatedSpec {
let mut translator = SpecTranslator {
auto_trace,
builder,
fun_env,
type_args,
param_substitution,
ret_locals,
in_post_state: false,
shadowed: Default::default(),
result: Default::default(),
let_locals: Default::default(),
in_old: false,
};
translator.translate_spec(for_call);
translator.result
}
/// Translates a set of invariants with type instantiations. If there are any references to
/// `old(...)` they will be rewritten and respective memory/spec var saves will be generated.
pub fn translate_invariants(
auto_trace: bool,
builder: &'b mut T,
invariants: impl Iterator<Item = (&'b GlobalInvariant, Vec<Type>)>,
) -> TranslatedSpec {
let fun_env = builder.function_env().clone();
let mut translator = SpecTranslator {
auto_trace,
builder,
fun_env: &fun_env,
type_args: &[],
param_substitution: Default::default(),
ret_locals: Default::default(),
in_post_state: false,
shadowed: Default::default(),
result: Default::default(),
let_locals: Default::default(),
in_old: false,
};
// Clone invariants so `inst` lives for the entire loop
let invariants = invariants.collect_vec();
for (inv, inst) in &invariants {
translator.type_args = inst;
let exp = translator.translate_exp(&translator.auto_trace(&inv.loc, &inv.cond), false);
translator
.result
.invariants
.push((inv.loc.clone(), inv.id, exp));
}
translator.result
}
/// Translate one inline property. If there are any references to `old(...)` they
/// will be rewritten and respective memory/spec var saves will be generated.
pub fn translate_inline_property(builder: &'b mut T, prop: &Exp) -> (TranslatedSpec, Exp) {
let fun_env = builder.function_env().clone();
let mut translator = SpecTranslator {
auto_trace: false,
builder,
fun_env: &fun_env,
type_args: &[],
param_substitution: Default::default(),
ret_locals: Default::default(),
in_post_state: false,
shadowed: Default::default(),
result: Default::default(),
let_locals: Default::default(),
in_old: false,
};
let exp = translator.translate_exp(prop, false);
(translator.result, exp)
}
pub fn translate_invariants_by_id(
auto_trace: bool,
builder: &'b mut T,
inv_ids: impl Iterator<Item = (GlobalId, Vec<Type>)>,
) -> TranslatedSpec {
let global_env = builder.global_env();
SpecTranslator::translate_invariants(
auto_trace,
builder,
inv_ids.map(|(inv_id, inst)| (global_env.get_global_invariant(inv_id).unwrap(), inst)),
)
}
fn translate_spec(&mut self, for_call: bool) {
let fun_env = self.fun_env;
let env = fun_env.module_env.env;
let spec = fun_env.get_spec();
// A function which determines whether a condition is applicable in the context, which
// is `for_call` for the function being called, and `!for_call` if its verified.
// If a condition has the `[abstract]` property, it will only be included for calls,
// and if it has the `[concrete]` property only for verification. Also, conditions
// which are injected from a schema are only included on call site if they are also
// exported.
let is_applicable = |cond: &&Condition| {
let abstract_ = env
.is_property_true(&cond.properties, CONDITION_ABSTRACT_PROP)
.unwrap_or(false);
let concrete = env
.is_property_true(&cond.properties, CONDITION_CONCRETE_PROP)
.unwrap_or(false);
let injected = env
.is_property_true(&cond.properties, CONDITION_INJECTED_PROP)
.unwrap_or(false);
let exported = env
.is_property_true(&cond.properties, CONDITION_EXPORT_PROP)
.unwrap_or(false);
if for_call {
(!injected || exported) && (abstract_ || !concrete)
} else {
concrete || !abstract_
}
};
// First process `let` so subsequently expressions can refer to them.
self.translate_lets(false, spec);
// Next process requires
for cond in spec
.filter_kind(ConditionKind::Requires)
.filter(is_applicable)
{
self.in_post_state = false;
let exp = self.translate_exp(&self.auto_trace(&cond.loc, &cond.exp), false);
self.result.pre.push((cond.loc.clone(), exp));
}
// Next process updates. They come between pre and post conditions.
for cond in spec
.filter_kind(ConditionKind::Update)
.filter(is_applicable)
{
self.in_post_state = false;
let lhs =
self.translate_exp(&self.auto_trace(&cond.loc, &cond.additional_exps[0]), false);
let rhs = self.translate_exp(&self.auto_trace(&cond.loc, &cond.exp), false);
self.result.updates.push((cond.loc.clone(), lhs, rhs));
}
// Aborts conditions are translated in post state when they aren't handled for a call
// but for a definition. Otherwise, they are translated for a call of an opaque function
// and are evaluated in pre state.
self.in_post_state = !for_call;
for cond in spec
.filter_kind(ConditionKind::AbortsIf)
.filter(is_applicable)
{
let code_opt = if cond.additional_exps.is_empty() {
None
} else {
Some(self.translate_exp(&cond.additional_exps[0], self.in_post_state))
};
let exp =
self.translate_exp(&self.auto_trace(&cond.loc, &cond.exp), self.in_post_state);
self.result.aborts.push((cond.loc.clone(), exp, code_opt));
}
for cond in spec
.filter_kind(ConditionKind::AbortsWith)
.filter(is_applicable)
{
let codes = cond
.all_exps()
.map(|e| self.translate_exp(&self.auto_trace_no_loc(e), self.in_post_state))
.collect_vec();
self.result.aborts_with.push((cond.loc.clone(), codes));
}
// If there are no aborts_if and aborts_with, and the pragma `aborts_if_is_strict` is set,
// add an implicit aborts_if false.
if self.result.aborts.is_empty()
&& self.result.aborts_with.is_empty()
&& self
.fun_env
.is_pragma_true(ABORTS_IF_IS_STRICT_PRAGMA, || false)
{
self.result.aborts.push((
self.fun_env.get_loc().at_end(),
self.builder.mk_bool_const(false),
None,
));
}
// Translate modifies.
for cond in spec
.filter_kind(ConditionKind::Modifies)
.filter(is_applicable)
{
self.in_post_state = false;
for exp in cond.all_exps() {
// Auto trace the inner address expression.
let exp = match exp.as_ref() {
ExpData::Call(id, oper, args) if args.len() == 1 => ExpData::Call(
*id,
oper.clone(),
vec![self.auto_trace(&cond.loc, &args[0])],
)
.into_exp(),
_ => cond.exp.to_owned(),
};
let exp = self.translate_exp(&exp, false);
self.result.modifies.push((cond.loc.clone(), exp));
}
}
// Now translate `let update` which are evaluated in post state.
self.translate_lets(true, spec);
// Translate ensures.
for cond in spec
.filter_kind(ConditionKind::Ensures)
.filter(is_applicable)
{
self.in_post_state = true;
let exp = self.translate_exp(&self.auto_trace(&cond.loc, &cond.exp), false);
self.result.post.push((cond.loc.clone(), exp));
}
// Translate emits.
for cond in spec.filter_kind(ConditionKind::Emits).filter(is_applicable) {
self.in_post_state = true;
let event_exp = self.translate_exp(&self.auto_trace(&cond.loc, &cond.exp), false);
let handle_exp =
self.translate_exp(&self.auto_trace_no_loc(&cond.additional_exps[0]), false);
let cond_exp = if cond.additional_exps.len() > 1 {
Some(self.translate_exp(&self.auto_trace_no_loc(&cond.additional_exps[1]), false))
} else {
None
};
self.result
.emits
.push((cond.loc.clone(), event_exp, handle_exp, cond_exp));
}
}
fn translate_lets(&mut self, post_state: bool, spec: &Spec) {
for cond in &spec.conditions {
let sym = match &cond.kind {
ConditionKind::LetPost(sym) if post_state => sym,
ConditionKind::LetPre(sym) if !post_state => sym,
_ => continue,
};
let exp = self.translate_exp(&self.auto_trace(&cond.loc, &cond.exp), false);
let ty = self.builder.global_env().get_node_type(exp.node_id());
let temp = self.builder.add_local(ty.skip_reference().clone());
self.let_locals.insert(*sym, temp);
self.result
.lets
.push((cond.loc.clone(), post_state, temp, exp));
}
}
fn auto_trace(&self, loc: &Loc, exp: &Exp) -> Exp {
if self.auto_trace {
self.auto_trace_exp(loc, self.auto_trace_sub(exp), TraceKind::Auto)
} else {
exp.to_owned()
}
}
fn auto_trace_sub(&self, exp: &Exp) -> Exp {
ExpData::rewrite(exp.to_owned(), &mut |e| {
let (trace_this, e) = match e.as_ref() {
ExpData::Temporary(..)
| ExpData::Call(_, Operation::Old, ..)
| ExpData::Call(_, Operation::Result(_), ..) => (true, e),
ExpData::LocalVar(_, sym) => (self.let_locals.contains_key(sym), e),
ExpData::Call(id, Operation::Global(None), args) => (
true,
ExpData::Call(
*id,
Operation::Global(None),
vec![self.auto_trace_sub(&args[0])],
)
.into_exp(),
),
ExpData::Call(id, Operation::Exists(None), args) => (
true,
ExpData::Call(
*id,
Operation::Exists(None),
vec![self.auto_trace_sub(&args[0])],
)
.into_exp(),
),
_ => (false, e),
};
if trace_this {
let l = self.builder.global_env().get_node_loc(e.node_id());
Ok(self.auto_trace_exp(&l, e, TraceKind::SubAuto))
} else {
// descent
Err(e)
}
})
}
fn auto_trace_exp(&self, loc: &Loc, exp: Exp, kind: TraceKind) -> Exp {
let env = self.builder.global_env();
let id = exp.node_id();
let ty = env.get_node_type(id);
let new_id = env.new_node(loc.clone(), ty.clone());
env.set_node_instantiation(new_id, vec![ty]);
ExpData::Call(new_id, Operation::Trace(kind), vec![exp]).into_exp()
}
fn auto_trace_no_loc(&self, exp: &Exp) -> Exp {
self.auto_trace(&self.builder.global_env().get_node_loc(exp.node_id()), exp)
}
fn translate_exp(&mut self, exp: &Exp, in_old: bool) -> Exp {
self.in_old = in_old;
self.rewrite_exp(exp.to_owned())
}
fn is_shadowed(&self, sym: Symbol) -> bool {
self.shadowed.iter().any(|bs| bs.contains(&sym))
}
/// Apply parameter substitution if present.
fn apply_param_substitution(&self, idx: TempIndex) -> TempIndex {
if let Some(map) = self.param_substitution {
map[idx]
} else {
idx
}
}
fn save_memory(&mut self, qid: QualifiedInstId<StructId>) -> MemoryLabel {
let builder = &mut self.builder;
*self
.result
.saved_memory
.entry(qid)
.or_insert_with(|| builder.global_env().new_global_id())
}
fn save_param(&mut self, idx: TempIndex) -> TempIndex {
if let Some(saved) = self.result.saved_params.get(&idx) {
*saved
} else {
let saved = self
.builder
.new_temp(self.builder.get_local_type(idx).skip_reference().clone());
self.result.saved_params.insert(idx, saved);
saved
}
}
}
impl<'a, 'b, T: ExpGenerator<'a>> ExpRewriterFunctions for SpecTranslator<'a, 'b, T> {
fn rewrite_exp(&mut self, exp: Exp) -> Exp {
// Do some pre-processing of the expression before actual rewrite, reporting
// errors.
let env = self.builder.global_env();
let mut is_old = false;
match exp.as_ref() {
ExpData::Call(id, Operation::Old, args) => {
is_old = true;
// Generate an error if an `old` function is applied to a pure expression.
let arg = &args[0];
if arg.is_pure(self.builder.global_env()) {
let loc = self.builder.global_env().get_node_loc(*id);
// Compute labels for any sub-expressions which are included into this
// expression via substitution (from schema inclusion, for example). This
// is done via checking the location of the sub-expression. We also try
// to avoid to report a sub-expression which is a sub-expression of an
// already reported one.
let mut labels = vec![];
let loc_contained = |loc: &Loc, cont: &Loc| {
loc.file_id() == cont.file_id()
&& cont.span().start() >= loc.span().start()
&& cont.span().end() <= loc.span().end()
};
arg.visit_pre_post(&mut |up: bool, e: &ExpData| {
let sub_loc = self.builder.global_env().get_node_loc(e.node_id());
if !up
&& !loc_contained(&loc, &sub_loc)
&& !labels.iter().any(|(l, _)| loc_contained(l, &sub_loc))
{
labels.push((sub_loc, "substituted sub-expression".to_owned()))
}
});
self.builder.global_env().diag_with_labels(
Severity::Error,
&loc,
"`old(..)` applied to expression which does not depend on state",
labels,
)
}
}
ExpData::Call(id, Operation::Trace(_), args) => {
// Generate an error if a TRACE is applied to an expression where it is not
// allowed, i.e. if there are free LocalVar terms, excluding locals from lets.
let loc = env.get_node_loc(*id);
let has_free_vars = args[0]
.free_vars(env)
.iter()
.any(|(s, _)| !self.let_locals.contains_key(s));
if has_free_vars {
env.error(
&loc,
"`TRACE(..)` function cannot be used for expressions depending \
on quantified variables or spec function parameters",
)
}
}
_ => {}
}
if is_old {
self.in_old = true;
}
let exp = self.rewrite_exp_descent(exp);
if is_old {
self.in_old = false;
}
exp
}
fn rewrite_local_var(&mut self, id: NodeId, sym: Symbol) -> Option<Exp> {
if !self.is_shadowed(sym) {
if let Some(temp) = self.let_locals.get(&sym) {
// Need to create new node id since the replacement `temp` may
// differ w.r.t. references.
let env = self.builder.global_env();
let new_node_id =
env.new_node(env.get_node_loc(id), self.builder.get_local_type(*temp));
return Some(ExpData::Temporary(new_node_id, *temp).into_exp());
}
}
None
}
fn rewrite_temporary(&mut self, id: NodeId, idx: TempIndex) -> Option<Exp> {
// Compute the effective index.
let mut effective_idx = self.apply_param_substitution(idx);
let local_type = self.builder.get_local_type(effective_idx);
if self.in_old || (self.in_post_state && !local_type.is_mutable_reference()) {
// We access a param inside of old context, or a value which might have been
// mutated as we are in the post state. We need to create a temporary
// to save their value at function entry, and deliver this temporary here.
//
// Notice that a redundant copy of a value (i.e. one which is not mutated)
// is removed by copy propagation, so we do not need to
// care about optimizing this here.
effective_idx = self.save_param(effective_idx);
}
if effective_idx != idx {
let effective_type = self.builder.get_local_type(effective_idx);
let loc = self.builder.global_env().get_node_loc(id);
let new_id = self.builder.global_env().new_node(loc, effective_type);
Some(ExpData::Temporary(new_id, effective_idx).into_exp())
} else {
None
}
}
fn rewrite_call(&mut self, id: NodeId, oper: &Operation, args: &[Exp]) -> Option<Exp> {
use ExpData::*;
use Operation::*;
match oper {
Global(None) if self.in_old => Some(
Call(
id,
Global(Some(self.save_memory(self.builder.get_memory_of_node(id)))),
args.to_owned(),
)
.into_exp(),
),
Exists(None) if self.in_old => Some(
Call(
id,
Exists(Some(self.save_memory(self.builder.get_memory_of_node(id)))),
args.to_owned(),
)
.into_exp(),
),
Function(mid, fid, None) if self.in_old => {
let used_memory = {
let module_env = self.builder.global_env().get_module(*mid);
let decl = module_env.get_spec_fun(*fid);
// Unfortunately, the below clones are necessary, as we cannot borrow decl
// and at the same time mutate self later.
decl.used_memory.clone()
};
let inst = self.builder.global_env().get_node_instantiation(id);
let mut labels = vec![];
for mem in used_memory {
let mem = mem.instantiate(&inst);
labels.push(self.save_memory(mem));
}
Some(Call(id, Function(*mid, *fid, Some(labels)), args.to_owned()).into_exp())
}
Old => Some(args[0].to_owned()),
Result(n) => {
self.builder.set_loc_from_node(id);
Some(self.builder.mk_temporary(self.ret_locals[*n]))
}
Trace(kind) => {
let exp = args[0].to_owned();
let env = self.builder.global_env();
let loc = env.get_node_loc(id);
let trace_id = env.new_node(loc, env.get_node_type(exp.node_id()));
self.result
.debug_traces
.push((trace_id, *kind, exp.clone()));
Some(exp)
}
_ => None,
}
}
fn rewrite_node_id(&mut self, id: NodeId) -> Option<NodeId> {
if self.type_args.is_empty() {
None
} else {
ExpData::instantiate_node(self.builder.global_env(), id, self.type_args)
}
}
fn rewrite_enter_scope<'c>(&mut self, decls: impl Iterator<Item = &'c LocalVarDecl>) {
self.shadowed.push(decls.map(|d| d.name).collect())
}
fn rewrite_exit_scope(&mut self) {
self.shadowed.pop();
}
}
| 40.702156 | 100 | 0.546174 |
d79c81ba1dc5958ebc2ad5ddaa158e0ef34b2c10 | 1,034 | mod memory;
mod mmap;
pub use memory::ArrayReader;
pub use mmap::MMappedReader;
use serde::Serialize;
use std::io::{Read, Result, Seek};
#[derive(Debug, Serialize)]
pub struct Name {
pub id: usize,
pub instance: u32,
}
pub trait Reader: Seek + Read {
fn read_bool(&mut self) -> Result<bool>;
fn read_f32(&mut self) -> Result<f32>;
fn read_f64(&mut self) -> Result<f64>;
fn read_i16(&mut self) -> Result<i16>;
fn read_i32(&mut self) -> Result<i32>;
fn read_i64(&mut self) -> Result<i64>;
fn read_i8(&mut self) -> Result<i8>;
fn read_str(&mut self) -> Result<String>;
fn read_u128(&mut self) -> Result<u128>;
fn read_u16(&mut self) -> Result<u16>;
fn read_u32(&mut self) -> Result<u32>;
fn read_u64(&mut self) -> Result<u64>;
fn read_u8(&mut self) -> Result<u8>;
fn read_name(&mut self) -> Result<Name> {
Ok(Name {
id: self.read_u32()? as usize,
instance: self.read_u32()?,
})
}
fn skip_str(&mut self) -> Result<()>;
}
| 26.512821 | 45 | 0.598646 |
8fd2d77be3910475162bce8b5afd3619b3a2da59 | 48 | pub trait Deserialize {
fn deserialize();
}
| 12 | 23 | 0.666667 |
f7eca0d799b1372afeea2fe725ef261c7421fcc7 | 16,960 | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files.git)
// DO NOT EDIT
use crate::CellRenderer;
use crate::CellRendererMode;
use crate::IconSize;
use glib::object::Cast;
use glib::object::IsA;
use glib::object::ObjectType as ObjectType_;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use glib::StaticType;
use glib::ToValue;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
glib::wrapper! {
#[doc(alias = "GtkCellRendererPixbuf")]
pub struct CellRendererPixbuf(Object<ffi::GtkCellRendererPixbuf>) @extends CellRenderer;
match fn {
type_ => || ffi::gtk_cell_renderer_pixbuf_get_type(),
}
}
impl CellRendererPixbuf {
#[doc(alias = "gtk_cell_renderer_pixbuf_new")]
pub fn new() -> CellRendererPixbuf {
assert_initialized_main_thread!();
unsafe { CellRenderer::from_glib_none(ffi::gtk_cell_renderer_pixbuf_new()).unsafe_cast() }
}
// rustdoc-stripper-ignore-next
/// Creates a new builder-pattern struct instance to construct [`CellRendererPixbuf`] objects.
///
/// This method returns an instance of [`CellRendererPixbufBuilder`](crate::builders::CellRendererPixbufBuilder) which can be used to create [`CellRendererPixbuf`] objects.
pub fn builder() -> CellRendererPixbufBuilder {
CellRendererPixbufBuilder::default()
}
pub fn gicon(&self) -> Option<gio::Icon> {
glib::ObjectExt::property(self, "gicon")
}
pub fn set_gicon<P: IsA<gio::Icon>>(&self, gicon: Option<&P>) {
glib::ObjectExt::set_property(self, "gicon", &gicon)
}
#[doc(alias = "icon-name")]
pub fn icon_name(&self) -> Option<glib::GString> {
glib::ObjectExt::property(self, "icon-name")
}
#[doc(alias = "icon-name")]
pub fn set_icon_name(&self, icon_name: Option<&str>) {
glib::ObjectExt::set_property(self, "icon-name", &icon_name)
}
#[doc(alias = "icon-size")]
pub fn icon_size(&self) -> IconSize {
glib::ObjectExt::property(self, "icon-size")
}
#[doc(alias = "icon-size")]
pub fn set_icon_size(&self, icon_size: IconSize) {
glib::ObjectExt::set_property(self, "icon-size", &icon_size)
}
pub fn set_pixbuf(&self, pixbuf: Option<&gdk_pixbuf::Pixbuf>) {
glib::ObjectExt::set_property(self, "pixbuf", &pixbuf)
}
#[doc(alias = "pixbuf-expander-closed")]
pub fn pixbuf_expander_closed(&self) -> Option<gdk_pixbuf::Pixbuf> {
glib::ObjectExt::property(self, "pixbuf-expander-closed")
}
#[doc(alias = "pixbuf-expander-closed")]
pub fn set_pixbuf_expander_closed(&self, pixbuf_expander_closed: Option<&gdk_pixbuf::Pixbuf>) {
glib::ObjectExt::set_property(self, "pixbuf-expander-closed", &pixbuf_expander_closed)
}
#[doc(alias = "pixbuf-expander-open")]
pub fn pixbuf_expander_open(&self) -> Option<gdk_pixbuf::Pixbuf> {
glib::ObjectExt::property(self, "pixbuf-expander-open")
}
#[doc(alias = "pixbuf-expander-open")]
pub fn set_pixbuf_expander_open(&self, pixbuf_expander_open: Option<&gdk_pixbuf::Pixbuf>) {
glib::ObjectExt::set_property(self, "pixbuf-expander-open", &pixbuf_expander_open)
}
pub fn texture(&self) -> Option<gdk::Texture> {
glib::ObjectExt::property(self, "texture")
}
pub fn set_texture<P: IsA<gdk::Texture>>(&self, texture: Option<&P>) {
glib::ObjectExt::set_property(self, "texture", &texture)
}
#[doc(alias = "gicon")]
pub fn connect_gicon_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_gicon_trampoline<F: Fn(&CellRendererPixbuf) + 'static>(
this: *mut ffi::GtkCellRendererPixbuf,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) {
let f: &F = &*(f as *const F);
f(&from_glib_borrow(this))
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::gicon\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_gicon_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
#[doc(alias = "icon-name")]
pub fn connect_icon_name_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_icon_name_trampoline<F: Fn(&CellRendererPixbuf) + 'static>(
this: *mut ffi::GtkCellRendererPixbuf,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) {
let f: &F = &*(f as *const F);
f(&from_glib_borrow(this))
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::icon-name\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_icon_name_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
#[doc(alias = "icon-size")]
pub fn connect_icon_size_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_icon_size_trampoline<F: Fn(&CellRendererPixbuf) + 'static>(
this: *mut ffi::GtkCellRendererPixbuf,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) {
let f: &F = &*(f as *const F);
f(&from_glib_borrow(this))
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::icon-size\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_icon_size_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
#[doc(alias = "pixbuf")]
pub fn connect_pixbuf_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_pixbuf_trampoline<F: Fn(&CellRendererPixbuf) + 'static>(
this: *mut ffi::GtkCellRendererPixbuf,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) {
let f: &F = &*(f as *const F);
f(&from_glib_borrow(this))
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::pixbuf\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_pixbuf_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
#[doc(alias = "pixbuf-expander-closed")]
pub fn connect_pixbuf_expander_closed_notify<F: Fn(&Self) + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_pixbuf_expander_closed_trampoline<
F: Fn(&CellRendererPixbuf) + 'static,
>(
this: *mut ffi::GtkCellRendererPixbuf,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) {
let f: &F = &*(f as *const F);
f(&from_glib_borrow(this))
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::pixbuf-expander-closed\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_pixbuf_expander_closed_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
#[doc(alias = "pixbuf-expander-open")]
pub fn connect_pixbuf_expander_open_notify<F: Fn(&Self) + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_pixbuf_expander_open_trampoline<
F: Fn(&CellRendererPixbuf) + 'static,
>(
this: *mut ffi::GtkCellRendererPixbuf,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) {
let f: &F = &*(f as *const F);
f(&from_glib_borrow(this))
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::pixbuf-expander-open\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_pixbuf_expander_open_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
#[doc(alias = "texture")]
pub fn connect_texture_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_texture_trampoline<F: Fn(&CellRendererPixbuf) + 'static>(
this: *mut ffi::GtkCellRendererPixbuf,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) {
let f: &F = &*(f as *const F);
f(&from_glib_borrow(this))
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::texture\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_texture_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
}
impl Default for CellRendererPixbuf {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone, Default)]
// rustdoc-stripper-ignore-next
/// A [builder-pattern] type to construct [`CellRendererPixbuf`] objects.
///
/// [builder-pattern]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
#[must_use = "The builder must be built to be used"]
pub struct CellRendererPixbufBuilder {
gicon: Option<gio::Icon>,
icon_name: Option<String>,
icon_size: Option<IconSize>,
pixbuf: Option<gdk_pixbuf::Pixbuf>,
pixbuf_expander_closed: Option<gdk_pixbuf::Pixbuf>,
pixbuf_expander_open: Option<gdk_pixbuf::Pixbuf>,
texture: Option<gdk::Texture>,
cell_background: Option<String>,
cell_background_rgba: Option<gdk::RGBA>,
cell_background_set: Option<bool>,
height: Option<i32>,
is_expanded: Option<bool>,
is_expander: Option<bool>,
mode: Option<CellRendererMode>,
sensitive: Option<bool>,
visible: Option<bool>,
width: Option<i32>,
xalign: Option<f32>,
xpad: Option<u32>,
yalign: Option<f32>,
ypad: Option<u32>,
}
impl CellRendererPixbufBuilder {
// rustdoc-stripper-ignore-next
/// Create a new [`CellRendererPixbufBuilder`].
pub fn new() -> Self {
Self::default()
}
// rustdoc-stripper-ignore-next
/// Build the [`CellRendererPixbuf`].
#[must_use = "Building the object from the builder is usually expensive and is not expected to have side effects"]
pub fn build(self) -> CellRendererPixbuf {
let mut properties: Vec<(&str, &dyn ToValue)> = vec![];
if let Some(ref gicon) = self.gicon {
properties.push(("gicon", gicon));
}
if let Some(ref icon_name) = self.icon_name {
properties.push(("icon-name", icon_name));
}
if let Some(ref icon_size) = self.icon_size {
properties.push(("icon-size", icon_size));
}
if let Some(ref pixbuf) = self.pixbuf {
properties.push(("pixbuf", pixbuf));
}
if let Some(ref pixbuf_expander_closed) = self.pixbuf_expander_closed {
properties.push(("pixbuf-expander-closed", pixbuf_expander_closed));
}
if let Some(ref pixbuf_expander_open) = self.pixbuf_expander_open {
properties.push(("pixbuf-expander-open", pixbuf_expander_open));
}
if let Some(ref texture) = self.texture {
properties.push(("texture", texture));
}
if let Some(ref cell_background) = self.cell_background {
properties.push(("cell-background", cell_background));
}
if let Some(ref cell_background_rgba) = self.cell_background_rgba {
properties.push(("cell-background-rgba", cell_background_rgba));
}
if let Some(ref cell_background_set) = self.cell_background_set {
properties.push(("cell-background-set", cell_background_set));
}
if let Some(ref height) = self.height {
properties.push(("height", height));
}
if let Some(ref is_expanded) = self.is_expanded {
properties.push(("is-expanded", is_expanded));
}
if let Some(ref is_expander) = self.is_expander {
properties.push(("is-expander", is_expander));
}
if let Some(ref mode) = self.mode {
properties.push(("mode", mode));
}
if let Some(ref sensitive) = self.sensitive {
properties.push(("sensitive", sensitive));
}
if let Some(ref visible) = self.visible {
properties.push(("visible", visible));
}
if let Some(ref width) = self.width {
properties.push(("width", width));
}
if let Some(ref xalign) = self.xalign {
properties.push(("xalign", xalign));
}
if let Some(ref xpad) = self.xpad {
properties.push(("xpad", xpad));
}
if let Some(ref yalign) = self.yalign {
properties.push(("yalign", yalign));
}
if let Some(ref ypad) = self.ypad {
properties.push(("ypad", ypad));
}
glib::Object::new::<CellRendererPixbuf>(&properties)
.expect("Failed to create an instance of CellRendererPixbuf")
}
pub fn gicon(mut self, gicon: &impl IsA<gio::Icon>) -> Self {
self.gicon = Some(gicon.clone().upcast());
self
}
pub fn icon_name(mut self, icon_name: &str) -> Self {
self.icon_name = Some(icon_name.to_string());
self
}
pub fn icon_size(mut self, icon_size: IconSize) -> Self {
self.icon_size = Some(icon_size);
self
}
pub fn pixbuf(mut self, pixbuf: &gdk_pixbuf::Pixbuf) -> Self {
self.pixbuf = Some(pixbuf.clone());
self
}
pub fn pixbuf_expander_closed(mut self, pixbuf_expander_closed: &gdk_pixbuf::Pixbuf) -> Self {
self.pixbuf_expander_closed = Some(pixbuf_expander_closed.clone());
self
}
pub fn pixbuf_expander_open(mut self, pixbuf_expander_open: &gdk_pixbuf::Pixbuf) -> Self {
self.pixbuf_expander_open = Some(pixbuf_expander_open.clone());
self
}
pub fn texture(mut self, texture: &impl IsA<gdk::Texture>) -> Self {
self.texture = Some(texture.clone().upcast());
self
}
pub fn cell_background(mut self, cell_background: &str) -> Self {
self.cell_background = Some(cell_background.to_string());
self
}
pub fn cell_background_rgba(mut self, cell_background_rgba: &gdk::RGBA) -> Self {
self.cell_background_rgba = Some(cell_background_rgba.clone());
self
}
pub fn cell_background_set(mut self, cell_background_set: bool) -> Self {
self.cell_background_set = Some(cell_background_set);
self
}
pub fn height(mut self, height: i32) -> Self {
self.height = Some(height);
self
}
pub fn is_expanded(mut self, is_expanded: bool) -> Self {
self.is_expanded = Some(is_expanded);
self
}
pub fn is_expander(mut self, is_expander: bool) -> Self {
self.is_expander = Some(is_expander);
self
}
pub fn mode(mut self, mode: CellRendererMode) -> Self {
self.mode = Some(mode);
self
}
pub fn sensitive(mut self, sensitive: bool) -> Self {
self.sensitive = Some(sensitive);
self
}
pub fn visible(mut self, visible: bool) -> Self {
self.visible = Some(visible);
self
}
pub fn width(mut self, width: i32) -> Self {
self.width = Some(width);
self
}
pub fn xalign(mut self, xalign: f32) -> Self {
self.xalign = Some(xalign);
self
}
pub fn xpad(mut self, xpad: u32) -> Self {
self.xpad = Some(xpad);
self
}
pub fn yalign(mut self, yalign: f32) -> Self {
self.yalign = Some(yalign);
self
}
pub fn ypad(mut self, ypad: u32) -> Self {
self.ypad = Some(ypad);
self
}
}
impl fmt::Display for CellRendererPixbuf {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("CellRendererPixbuf")
}
}
| 33.784861 | 176 | 0.569693 |
50885e98d0b25916b957369bb9d2feb8e3f5fdbc | 1,474 | mod delete_blob_response;
pub use self::delete_blob_response::DeleteBlobResponse;
mod release_blob_lease_response;
pub use self::release_blob_lease_response::ReleaseBlobLeaseResponse;
mod change_blob_lease_response;
pub use self::change_blob_lease_response::ChangeBlobLeaseResponse;
mod renew_blob_lease_response;
pub use self::renew_blob_lease_response::RenewBlobLeaseResponse;
mod acquire_blob_lease_response;
pub use self::acquire_blob_lease_response::AcquireBlobLeaseResponse;
mod get_block_list_response;
pub use self::get_block_list_response::GetBlockListResponse;
mod put_block_list_response;
pub use self::put_block_list_response::PutBlockListResponse;
mod put_block_response;
pub use self::put_block_response::PutBlockResponse;
mod clear_page_response;
pub use self::clear_page_response::ClearPageResponse;
mod put_block_blob_response;
pub use self::put_block_blob_response::PutBlockBlobResponse;
mod list_blobs_response;
pub use self::list_blobs_response::ListBlobsResponse;
mod get_blob_response;
pub use self::get_blob_response::GetBlobResponse;
mod put_blob_response;
pub use self::put_blob_response::PutBlobResponse;
mod update_page_response;
pub use self::update_page_response::UpdatePageResponse;
mod break_blob_lease_response;
pub use self::break_blob_lease_response::BreakBlobLeaseResponse;
mod copy_blob_from_url_response;
pub use copy_blob_from_url_response::CopyBlobFromUrlResponse;
mod copy_blob_response;
pub use copy_blob_response::CopyBlobResponse;
| 42.114286 | 68 | 0.875848 |
4b8a88ab2ea4020d857bcb59bb1dc3d1e0eb68bd | 15,463 | // Copyright (c) 2018-2021 The MobileCoin Foundation
//! Serves blockchain-related API requests.
use grpcio::{RpcContext, RpcStatus, RpcStatusCode, UnarySink};
use mc_common::logger::{log, Logger};
use mc_consensus_api::{
blockchain,
consensus_common::{BlocksRequest, BlocksResponse, LastBlockInfoResponse},
consensus_common_grpc::BlockchainApi,
empty::Empty,
};
use mc_consensus_enclave::FeeMap;
use mc_ledger_db::Ledger;
use mc_transaction_core::{tokens::Mob, Token};
use mc_util_grpc::{rpc_logger, send_result, Authenticator};
use mc_util_metrics::{self, SVC_COUNTERS};
use protobuf::RepeatedField;
use std::{cmp, collections::HashMap, convert::From, iter::FromIterator, sync::Arc};
#[derive(Clone)]
pub struct BlockchainApiService<L: Ledger + Clone> {
/// Ledger Database.
ledger: L,
/// GRPC request authenticator.
authenticator: Arc<dyn Authenticator + Send + Sync>,
/// Maximal number of results to return in API calls that return multiple
/// results.
max_page_size: u16,
/// Minimum fee per token.
fee_map: FeeMap,
/// Logger.
logger: Logger,
}
impl<L: Ledger + Clone> BlockchainApiService<L> {
pub fn new(
ledger: L,
authenticator: Arc<dyn Authenticator + Send + Sync>,
fee_map: FeeMap,
logger: Logger,
) -> Self {
BlockchainApiService {
ledger,
authenticator,
max_page_size: 2000,
fee_map,
logger,
}
}
// Set the maximum number of items returned for a single request.
#[allow(dead_code)]
pub fn set_max_page_size(&mut self, max_page_size: u16) {
self.max_page_size = max_page_size;
}
/// Returns information about the last block.
fn get_last_block_info_helper(&mut self) -> Result<LastBlockInfoResponse, mc_ledger_db::Error> {
let num_blocks = self.ledger.num_blocks()?;
let mut resp = LastBlockInfoResponse::new();
resp.set_index(num_blocks - 1);
resp.set_mob_minimum_fee(
self.fee_map
.get_fee_for_token(&Mob::ID)
.expect("should always have a fee for MOB"),
);
resp.set_minimum_fees(HashMap::from_iter(
self.fee_map
.iter()
.map(|(token_id, fee)| (**token_id, *fee)),
));
Ok(resp)
}
/// Returns blocks in the range [offset, offset + limit).
///
/// If `limit` exceeds `max_page_size`, then only [offset, offset +
/// max_page_size) is returned. If `limit` exceeds the maximum index in
/// the database, then only [offset, max_index] is returned. This method
/// is a hack to expose the `get_blocks` implementation for unit testing.
fn get_blocks_helper(&mut self, offset: u64, limit: u32) -> Result<BlocksResponse, ()> {
let start_index = offset;
let end_index = offset + cmp::min(limit, self.max_page_size as u32) as u64;
// Get "persistence type" blocks.
let mut block_entities: Vec<mc_transaction_core::Block> = vec![];
for block_index in start_index..end_index {
match self.ledger.get_block(block_index as u64) {
Ok(block) => block_entities.push(block),
Err(mc_ledger_db::Error::NotFound) => {
// This is okay - it means we have reached the last block in the ledger in the
// previous loop iteration.
break;
}
Err(error) => {
log::error!(
self.logger,
"Error getting block {}: {:?}",
block_index,
error
);
break;
}
}
}
// Convert to "API type" blocks.
let blocks: Vec<blockchain::Block> = block_entities
.into_iter()
.map(|block| blockchain::Block::from(&block))
.collect();
let mut response = BlocksResponse::new();
response.set_blocks(RepeatedField::from_vec(blocks));
Ok(response)
}
}
impl<L: Ledger + Clone> BlockchainApi for BlockchainApiService<L> {
/// Gets the last block.
fn get_last_block_info(
&mut self,
ctx: RpcContext,
_request: Empty,
sink: UnarySink<LastBlockInfoResponse>,
) {
let _timer = SVC_COUNTERS.req(&ctx);
mc_common::logger::scoped_global_logger(&rpc_logger(&ctx, &self.logger), |logger| {
if let Err(err) = self.authenticator.authenticate_rpc(&ctx) {
return send_result(ctx, sink, err.into(), logger);
}
let resp = self
.get_last_block_info_helper()
.map_err(|_| RpcStatus::new(RpcStatusCode::INTERNAL));
send_result(ctx, sink, resp, logger);
});
}
/// Gets a range [offset, offset+limit) of Blocks.
fn get_blocks(
&mut self,
ctx: RpcContext,
request: BlocksRequest,
sink: UnarySink<BlocksResponse>,
) {
let _timer = SVC_COUNTERS.req(&ctx);
mc_common::logger::scoped_global_logger(&rpc_logger(&ctx, &self.logger), |logger| {
if let Err(err) = self.authenticator.authenticate_rpc(&ctx) {
return send_result(ctx, sink, err.into(), logger);
}
log::trace!(
logger,
"Received BlocksRequest for offset {} and limit {})",
request.offset,
request.limit
);
let resp = self
.get_blocks_helper(request.offset, request.limit)
.map_err(|_| RpcStatus::new(RpcStatusCode::INTERNAL));
send_result(ctx, sink, resp, logger);
});
}
}
#[cfg(test)]
mod tests {
use super::*;
use grpcio::{ChannelBuilder, Environment, Error as GrpcError, Server, ServerBuilder};
use mc_common::{logger::test_with_logger, time::SystemTimeProvider};
use mc_consensus_api::consensus_common_grpc::{self, BlockchainApiClient};
use mc_transaction_core::{BlockVersion, TokenId};
use mc_transaction_core_test_utils::{create_ledger, initialize_ledger, AccountKey};
use mc_util_grpc::{AnonymousAuthenticator, TokenAuthenticator};
use rand::{rngs::StdRng, SeedableRng};
use std::{
collections::HashMap,
iter::FromIterator,
sync::atomic::{AtomicUsize, Ordering::SeqCst},
time::Duration,
};
fn get_free_port() -> u16 {
static PORT_NR: AtomicUsize = AtomicUsize::new(0);
PORT_NR.fetch_add(1, SeqCst) as u16 + 30200
}
/// Starts the service on localhost and connects a client to it.
fn get_client_server<L: Ledger + Clone + 'static>(
instance: BlockchainApiService<L>,
) -> (BlockchainApiClient, Server) {
let service = consensus_common_grpc::create_blockchain_api(instance);
let env = Arc::new(Environment::new(1));
let mut server = ServerBuilder::new(env.clone())
.register_service(service)
.bind("127.0.0.1", get_free_port())
.build()
.unwrap();
server.start();
let (_, port) = server.bind_addrs().next().unwrap();
let ch = ChannelBuilder::new(env).connect(&format!("127.0.0.1:{}", port));
let client = BlockchainApiClient::new(ch);
(client, server)
}
#[test_with_logger]
// `get_last_block_info` should returns the last block.
fn test_get_last_block_info(logger: Logger) {
let fee_map =
FeeMap::try_from_iter([(Mob::ID, 12345), (TokenId::from(60), 10203040)]).unwrap();
let mut ledger_db = create_ledger();
let authenticator = Arc::new(AnonymousAuthenticator::default());
let mut rng: StdRng = SeedableRng::from_seed([1u8; 32]);
let account_key = AccountKey::random(&mut rng);
let block_entities = initialize_ledger(
BlockVersion::MAX,
&mut ledger_db,
10,
&account_key,
&mut rng,
);
let mut expected_response = LastBlockInfoResponse::new();
expected_response.set_index(block_entities.last().unwrap().index);
expected_response.set_mob_minimum_fee(12345);
expected_response.set_minimum_fees(HashMap::from_iter(vec![(0, 12345), (60, 10203040)]));
assert_eq!(
block_entities.last().unwrap().index,
ledger_db.num_blocks().unwrap() - 1
);
let mut blockchain_api_service =
BlockchainApiService::new(ledger_db, authenticator, fee_map, logger);
let block_response = blockchain_api_service.get_last_block_info_helper().unwrap();
assert_eq!(block_response, expected_response);
}
#[test_with_logger]
// `get_last_block_info` should reject unauthenticated responses when configured
// with an authenticator.
fn test_get_last_block_info_rejects_unauthenticated(logger: Logger) {
let ledger_db = create_ledger();
let authenticator = Arc::new(TokenAuthenticator::new(
[1; 32],
Duration::from_secs(60),
SystemTimeProvider::default(),
));
let blockchain_api_service =
BlockchainApiService::new(ledger_db, authenticator, FeeMap::default(), logger);
let (client, _server) = get_client_server(blockchain_api_service);
match client.get_last_block_info(&Empty::default()) {
Ok(response) => {
panic!("Unexpected response {:?}", response);
}
Err(GrpcError::RpcFailure(rpc_status)) => {
assert_eq!(rpc_status.code(), RpcStatusCode::UNAUTHENTICATED);
}
Err(err @ _) => {
panic!("Unexpected error {:?}", err);
}
}
}
#[test_with_logger]
// `get_blocks` should returns the correct range of blocks.
fn test_get_blocks_response_range(logger: Logger) {
let mut ledger_db = create_ledger();
let authenticator = Arc::new(AnonymousAuthenticator::default());
let mut rng: StdRng = SeedableRng::from_seed([1u8; 32]);
let account_key = AccountKey::random(&mut rng);
let block_entities = initialize_ledger(
BlockVersion::MAX,
&mut ledger_db,
10,
&account_key,
&mut rng,
);
let expected_blocks: Vec<blockchain::Block> = block_entities
.into_iter()
.map(|block_entity| blockchain::Block::from(&block_entity))
.collect();
let mut blockchain_api_service =
BlockchainApiService::new(ledger_db, authenticator, FeeMap::default(), logger);
{
// The empty range [0,0) should return an empty collection of Blocks.
let block_response = blockchain_api_service.get_blocks_helper(0, 0).unwrap();
assert_eq!(0, block_response.blocks.len());
}
{
// The singleton range [0,1) should return a single Block.
let block_response = blockchain_api_service.get_blocks_helper(0, 1).unwrap();
let blocks = block_response.blocks;
assert_eq!(1, blocks.len());
assert_eq!(expected_blocks.get(0).unwrap(), blocks.get(0).unwrap());
}
{
// The range [0,10) should return 10 Blocks.
let block_response = blockchain_api_service.get_blocks_helper(0, 10).unwrap();
let blocks = block_response.blocks;
assert_eq!(10, blocks.len());
assert_eq!(expected_blocks.get(0).unwrap(), blocks.get(0).unwrap());
assert_eq!(expected_blocks.get(7).unwrap(), blocks.get(7).unwrap());
assert_eq!(expected_blocks.get(9).unwrap(), blocks.get(9).unwrap());
}
}
#[test_with_logger]
// `get_blocks` should return the intersection of the request with the available
// data if a client requests data that does not exist.
fn test_get_blocks_request_out_of_bounds(logger: Logger) {
let mut ledger_db = create_ledger();
let authenticator = Arc::new(AnonymousAuthenticator::default());
let mut rng: StdRng = SeedableRng::from_seed([1u8; 32]);
let account_key = AccountKey::random(&mut rng);
let _blocks = initialize_ledger(
BlockVersion::MAX,
&mut ledger_db,
10,
&account_key,
&mut rng,
);
let mut blockchain_api_service =
BlockchainApiService::new(ledger_db, authenticator, FeeMap::default(), logger);
{
// The range [0, 1000) requests values that don't exist. The response should
// contain [0,10).
let block_response = blockchain_api_service.get_blocks_helper(0, 1000).unwrap();
assert_eq!(10, block_response.blocks.len());
}
}
#[test_with_logger]
// `get_blocks` should only return the "maximum" number of items if the
// requested range is larger.
fn test_get_blocks_max_size(logger: Logger) {
let mut ledger_db = create_ledger();
let authenticator = Arc::new(AnonymousAuthenticator::default());
let mut rng: StdRng = SeedableRng::from_seed([1u8; 32]);
let account_key = AccountKey::random(&mut rng);
let block_entities = initialize_ledger(
BlockVersion::MAX,
&mut ledger_db,
10,
&account_key,
&mut rng,
);
let expected_blocks: Vec<blockchain::Block> = block_entities
.into_iter()
.map(|block_entity| blockchain::Block::from(&block_entity))
.collect();
let mut blockchain_api_service =
BlockchainApiService::new(ledger_db, authenticator, FeeMap::default(), logger);
blockchain_api_service.set_max_page_size(5);
// The request exceeds the max_page_size, so only max_page_size items should be
// returned.
let block_response = blockchain_api_service.get_blocks_helper(0, 100).unwrap();
let blocks = block_response.blocks;
assert_eq!(5, blocks.len());
assert_eq!(expected_blocks.get(0).unwrap(), blocks.get(0).unwrap());
assert_eq!(expected_blocks.get(4).unwrap(), blocks.get(4).unwrap());
}
#[test_with_logger]
// `get_blocks` should reject unauthenticated responses when configured with an
// authenticator.
fn test_get_blocks_rejects_unauthenticated(logger: Logger) {
let ledger_db = create_ledger();
let authenticator = Arc::new(TokenAuthenticator::new(
[1; 32],
Duration::from_secs(60),
SystemTimeProvider::default(),
));
let blockchain_api_service =
BlockchainApiService::new(ledger_db, authenticator, FeeMap::default(), logger);
let (client, _server) = get_client_server(blockchain_api_service);
match client.get_blocks(&BlocksRequest::default()) {
Ok(response) => {
panic!("Unexpected response {:?}", response);
}
Err(GrpcError::RpcFailure(rpc_status)) => {
assert_eq!(rpc_status.code(), RpcStatusCode::UNAUTHENTICATED);
}
Err(err @ _) => {
panic!("Unexpected error {:?}", err);
}
}
}
}
| 37.081535 | 100 | 0.599625 |
1a1f5389820c8ef7a35bab04cde1a0a8a6cd9a66 | 865 | // unihernandez22
// https://codeforces.com/problemset/problem/580/A
use std::io;
fn main() {
io::stdin().read_line(&mut String::new()).unwrap();
let mut s = String::new();
io::stdin().read_line(&mut s).unwrap();
let words: Vec<i64> = s.split_whitespace().map(|x| x.parse().unwrap()).collect();
let mut iterable = words.iter();
let mut total = 1;
let mut max = 0;
let mut value = iterable.next();
let mut next = iterable.next();
while next != None {
if next.unwrap() >= value.unwrap() {
total += 1;
} else if total > max {
max = total;
total = 1;
} else {
total = 1;
}
value = next;
next = iterable.next()
}
if max < total {
max = total;
}
println!("{}", max);
}
| 23.378378 | 86 | 0.485549 |
e90db682adf019d60a943518cd3022b14af6f0bd | 385 | // enums1.rs
// Make me compile! Execute `rustlings hint enums1` for hints!
#[derive(Debug)]
enum Message {
// TODO: define a few types of messages as used below
ChangeColor,
Echo,
Move,
Quit
}
fn main() {
println!("{:?}", Message::Quit);
println!("{:?}", Message::Echo);
println!("{:?}", Message::Move);
println!("{:?}", Message::ChangeColor);
}
| 20.263158 | 62 | 0.584416 |
5dcf5538b47c72649bfa77198ffd0b5309678455 | 8,459 | //! A trait to represent a stream
use crate::transport::smtp::{client::mock::MockStream, error::Error};
#[cfg(feature = "native-tls")]
use native_tls::{TlsConnector, TlsStream};
#[cfg(feature = "rustls-tls")]
use rustls::{ClientConfig, ClientSession};
#[cfg(feature = "native-tls")]
use std::io::ErrorKind;
#[cfg(feature = "rustls-tls")]
use std::sync::Arc;
use std::{
io::{self, Read, Write},
net::{Ipv4Addr, Shutdown, SocketAddr, SocketAddrV4, TcpStream, ToSocketAddrs},
time::Duration,
};
/// Parameters to use for secure clients
#[derive(Clone)]
#[allow(missing_debug_implementations)]
pub struct TlsParameters {
/// A connector from `native-tls`
#[cfg(feature = "native-tls")]
connector: TlsConnector,
/// A client from `rustls`
#[cfg(feature = "rustls-tls")]
// TODO use the same in all transports of the client
connector: Box<ClientConfig>,
/// The domain name which is expected in the TLS certificate from the server
domain: String,
}
impl TlsParameters {
/// Creates a `TlsParameters`
#[cfg(feature = "native-tls")]
pub fn new(domain: String, connector: TlsConnector) -> Self {
Self { connector, domain }
}
/// Creates a `TlsParameters`
#[cfg(feature = "rustls-tls")]
pub fn new(domain: String, connector: ClientConfig) -> Self {
Self {
connector: Box::new(connector),
domain,
}
}
}
/// Represents the different types of underlying network streams
pub enum NetworkStream {
/// Plain TCP stream
Tcp(TcpStream),
/// Encrypted TCP stream
#[cfg(feature = "native-tls")]
Tls(Box<TlsStream<TcpStream>>),
#[cfg(feature = "rustls-tls")]
Tls(Box<rustls::StreamOwned<ClientSession, TcpStream>>),
/// Mock stream
Mock(MockStream),
}
impl NetworkStream {
/// Returns peer's address
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
match *self {
NetworkStream::Tcp(ref s) => s.peer_addr(),
#[cfg(feature = "native-tls")]
NetworkStream::Tls(ref s) => s.get_ref().peer_addr(),
#[cfg(feature = "rustls-tls")]
NetworkStream::Tls(ref s) => s.get_ref().peer_addr(),
NetworkStream::Mock(_) => Ok(SocketAddr::V4(SocketAddrV4::new(
Ipv4Addr::new(127, 0, 0, 1),
80,
))),
}
}
/// Shutdowns the connection
pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
match *self {
NetworkStream::Tcp(ref s) => s.shutdown(how),
#[cfg(feature = "native-tls")]
NetworkStream::Tls(ref s) => s.get_ref().shutdown(how),
#[cfg(feature = "rustls-tls")]
NetworkStream::Tls(ref s) => s.get_ref().shutdown(how),
NetworkStream::Mock(_) => Ok(()),
}
}
pub fn connect<T: ToSocketAddrs>(
server: T,
timeout: Option<Duration>,
tls_parameters: Option<&TlsParameters>,
) -> Result<NetworkStream, Error> {
fn try_connect_timeout<T: ToSocketAddrs>(
server: T,
timeout: Duration,
) -> Result<TcpStream, Error> {
let addrs = server.to_socket_addrs()?;
for addr in addrs {
let result = TcpStream::connect_timeout(&addr, timeout);
if result.is_ok() {
return result.map_err(|e| e.into());
}
}
Err(Error::Client("Could not connect"))
}
let tcp_stream = match timeout {
Some(t) => try_connect_timeout(server, t)?,
None => TcpStream::connect(server)?,
};
match tls_parameters {
#[cfg(feature = "native-tls")]
Some(context) => context
.connector
.connect(context.domain.as_ref(), tcp_stream)
.map(|tls| NetworkStream::Tls(Box::new(tls)))
.map_err(|e| Error::Io(io::Error::new(ErrorKind::Other, e))),
#[cfg(feature = "rustls-tls")]
Some(context) => {
let domain = webpki::DNSNameRef::try_from_ascii_str(&context.domain)?;
Ok(NetworkStream::Tls(Box::new(rustls::StreamOwned::new(
ClientSession::new(&Arc::new(*context.connector.clone()), domain),
tcp_stream,
))))
}
#[cfg(not(any(feature = "native-tls", feature = "rustls-tls")))]
Some(_) => panic!("TLS configuration without support"),
None => Ok(NetworkStream::Tcp(tcp_stream)),
}
}
#[allow(unused_variables, unreachable_code)]
pub fn upgrade_tls(&mut self, tls_parameters: &TlsParameters) -> Result<(), Error> {
*self = match *self {
#[cfg(feature = "native-tls")]
NetworkStream::Tcp(ref mut stream) => match tls_parameters
.connector
.connect(tls_parameters.domain.as_ref(), stream.try_clone().unwrap())
{
Ok(tls_stream) => NetworkStream::Tls(Box::new(tls_stream)),
Err(err) => return Err(Error::Io(io::Error::new(ErrorKind::Other, err))),
},
#[cfg(feature = "rustls-tls")]
NetworkStream::Tcp(ref mut stream) => {
let domain = webpki::DNSNameRef::try_from_ascii_str(&tls_parameters.domain)?;
NetworkStream::Tls(Box::new(rustls::StreamOwned::new(
ClientSession::new(&Arc::new(*tls_parameters.connector.clone()), domain),
stream.try_clone().unwrap(),
)))
}
#[cfg(not(any(feature = "native-tls", feature = "rustls-tls")))]
NetworkStream::Tcp(_) => panic!("STARTTLS without TLS support"),
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
NetworkStream::Tls(_) => return Ok(()),
NetworkStream::Mock(_) => return Ok(()),
};
Ok(())
}
pub fn is_encrypted(&self) -> bool {
match *self {
NetworkStream::Tcp(_) | NetworkStream::Mock(_) => false,
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
NetworkStream::Tls(_) => true,
}
}
pub fn set_read_timeout(&mut self, duration: Option<Duration>) -> io::Result<()> {
match *self {
NetworkStream::Tcp(ref mut stream) => stream.set_read_timeout(duration),
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
NetworkStream::Tls(ref mut stream) => stream.get_ref().set_read_timeout(duration),
NetworkStream::Mock(_) => Ok(()),
}
}
/// Set write timeout for IO calls
pub fn set_write_timeout(&mut self, duration: Option<Duration>) -> io::Result<()> {
match *self {
NetworkStream::Tcp(ref mut stream) => stream.set_write_timeout(duration),
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
NetworkStream::Tls(ref mut stream) => stream.get_ref().set_write_timeout(duration),
NetworkStream::Mock(_) => Ok(()),
}
}
}
impl Read for NetworkStream {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match *self {
NetworkStream::Tcp(ref mut s) => s.read(buf),
#[cfg(feature = "native-tls")]
NetworkStream::Tls(ref mut s) => s.read(buf),
#[cfg(feature = "rustls-tls")]
NetworkStream::Tls(ref mut s) => s.read(buf),
NetworkStream::Mock(ref mut s) => s.read(buf),
}
}
}
impl Write for NetworkStream {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
match *self {
NetworkStream::Tcp(ref mut s) => s.write(buf),
#[cfg(feature = "native-tls")]
NetworkStream::Tls(ref mut s) => s.write(buf),
#[cfg(feature = "rustls-tls")]
NetworkStream::Tls(ref mut s) => s.write(buf),
NetworkStream::Mock(ref mut s) => s.write(buf),
}
}
fn flush(&mut self) -> io::Result<()> {
match *self {
NetworkStream::Tcp(ref mut s) => s.flush(),
#[cfg(feature = "native-tls")]
NetworkStream::Tls(ref mut s) => s.flush(),
#[cfg(feature = "rustls-tls")]
NetworkStream::Tls(ref mut s) => s.flush(),
NetworkStream::Mock(ref mut s) => s.flush(),
}
}
}
| 36.619048 | 95 | 0.547937 |
e4904863a94bc195a66b4d28e5e84e9abeeb1663 | 13,082 | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Code that generates a test runner to run all the tests in a crate
use driver::session;
use front::config;
use std::vec;
use syntax::ast_util::*;
use syntax::attr::AttrMetaMethods;
use syntax::attr;
use syntax::codemap::{dummy_sp, Span, ExpnInfo, NameAndSpan};
use syntax::codemap;
use syntax::ext::base::ExtCtxt;
use syntax::fold::ast_fold;
use syntax::fold;
use syntax::opt_vec;
use syntax::print::pprust;
use syntax::{ast, ast_util};
struct Test {
span: Span,
path: ~[ast::Ident],
bench: bool,
ignore: bool,
should_fail: bool
}
struct TestCtxt {
sess: session::Session,
path: ~[ast::Ident],
ext_cx: @ExtCtxt,
testfns: ~[Test],
is_extra: bool,
config: ast::CrateConfig,
}
// Traverse the crate, collecting all the test functions, eliding any
// existing main functions, and synthesizing a main test harness
pub fn modify_for_testing(sess: session::Session,
crate: ast::Crate) -> ast::Crate {
// We generate the test harness when building in the 'test'
// configuration, either with the '--test' or '--cfg test'
// command line options.
let should_test = attr::contains_name(crate.config, "test");
if should_test {
generate_test_harness(sess, crate)
} else {
strip_test_functions(crate)
}
}
struct TestHarnessGenerator {
cx: @mut TestCtxt,
}
impl fold::ast_fold for TestHarnessGenerator {
fn fold_crate(&self, c: ast::Crate) -> ast::Crate {
let folded = fold::noop_fold_crate(c, self);
// Add a special __test module to the crate that will contain code
// generated for the test harness
ast::Crate {
module: add_test_module(self.cx, &folded.module),
.. folded
}
}
fn fold_item(&self, i: @ast::item) -> Option<@ast::item> {
self.cx.path.push(i.ident);
debug2!("current path: {}",
ast_util::path_name_i(self.cx.path.clone()));
if is_test_fn(self.cx, i) || is_bench_fn(i) {
match i.node {
ast::item_fn(_, purity, _, _, _)
if purity == ast::unsafe_fn => {
let sess = self.cx.sess;
sess.span_fatal(i.span,
"unsafe functions cannot be used for \
tests");
}
_ => {
debug2!("this is a test function");
let test = Test {
span: i.span,
path: self.cx.path.clone(),
bench: is_bench_fn(i),
ignore: is_ignored(self.cx, i),
should_fail: should_fail(i)
};
self.cx.testfns.push(test);
// debug2!("have {} test/bench functions",
// cx.testfns.len());
}
}
}
let res = fold::noop_fold_item(i, self);
self.cx.path.pop();
return res;
}
fn fold_mod(&self, m: &ast::_mod) -> ast::_mod {
// Remove any #[main] from the AST so it doesn't clash with
// the one we're going to add. Only if compiling an executable.
fn nomain(cx: @mut TestCtxt, item: @ast::item) -> @ast::item {
if !*cx.sess.building_library {
@ast::item {
attrs: do item.attrs.iter().filter_map |attr| {
if "main" != attr.name() {
Some(*attr)
} else {
None
}
}.collect(),
.. (*item).clone()
}
} else {
item
}
}
let mod_nomain = ast::_mod {
view_items: m.view_items.clone(),
items: m.items.iter().map(|i| nomain(self.cx, *i)).collect(),
};
fold::noop_fold_mod(&mod_nomain, self)
}
}
fn generate_test_harness(sess: session::Session, crate: ast::Crate)
-> ast::Crate {
let cx: @mut TestCtxt = @mut TestCtxt {
sess: sess,
ext_cx: ExtCtxt::new(sess.parse_sess, sess.opts.cfg.clone()),
path: ~[],
testfns: ~[],
is_extra: is_extra(&crate),
config: crate.config.clone(),
};
let ext_cx = cx.ext_cx;
ext_cx.bt_push(ExpnInfo {
call_site: dummy_sp(),
callee: NameAndSpan {
name: @"test",
span: None
}
});
let fold = TestHarnessGenerator {
cx: cx
};
let res = fold.fold_crate(crate);
ext_cx.bt_pop();
return res;
}
fn strip_test_functions(crate: ast::Crate) -> ast::Crate {
// When not compiling with --test we should not compile the
// #[test] functions
do config::strip_items(crate) |attrs| {
!attr::contains_name(attrs, "test") &&
!attr::contains_name(attrs, "bench")
}
}
fn is_test_fn(cx: @mut TestCtxt, i: @ast::item) -> bool {
let has_test_attr = attr::contains_name(i.attrs, "test");
fn has_test_signature(i: @ast::item) -> bool {
match &i.node {
&ast::item_fn(ref decl, _, _, ref generics, _) => {
let no_output = match decl.output.node {
ast::ty_nil => true,
_ => false
};
decl.inputs.is_empty()
&& no_output
&& !generics.is_parameterized()
}
_ => false
}
}
if has_test_attr && !has_test_signature(i) {
let sess = cx.sess;
sess.span_err(
i.span,
"functions used as tests must have signature fn() -> ()."
);
}
return has_test_attr && has_test_signature(i);
}
fn is_bench_fn(i: @ast::item) -> bool {
let has_bench_attr = attr::contains_name(i.attrs, "bench");
fn has_test_signature(i: @ast::item) -> bool {
match i.node {
ast::item_fn(ref decl, _, _, ref generics, _) => {
let input_cnt = decl.inputs.len();
let no_output = match decl.output.node {
ast::ty_nil => true,
_ => false
};
let tparm_cnt = generics.ty_params.len();
// NB: inadequate check, but we're running
// well before resolve, can't get too deep.
input_cnt == 1u
&& no_output && tparm_cnt == 0u
}
_ => false
}
}
return has_bench_attr && has_test_signature(i);
}
fn is_ignored(cx: @mut TestCtxt, i: @ast::item) -> bool {
do i.attrs.iter().any |attr| {
// check ignore(cfg(foo, bar))
"ignore" == attr.name() && match attr.meta_item_list() {
Some(ref cfgs) => attr::test_cfg(cx.config, cfgs.iter().map(|x| *x)),
None => true
}
}
}
fn should_fail(i: @ast::item) -> bool {
attr::contains_name(i.attrs, "should_fail")
}
fn add_test_module(cx: &TestCtxt, m: &ast::_mod) -> ast::_mod {
let testmod = mk_test_module(cx);
ast::_mod {
items: vec::append_one(m.items.clone(), testmod),
..(*m).clone()
}
}
/*
We're going to be building a module that looks more or less like:
mod __test {
#[!resolve_unexported]
extern mod extra (name = "extra", vers = "...");
fn main() {
#[main];
extra::test::test_main_static(::os::args(), tests)
}
static tests : &'static [extra::test::TestDescAndFn] = &[
... the list of tests in the crate ...
];
}
*/
fn mk_std(cx: &TestCtxt) -> ast::view_item {
let id_extra = cx.sess.ident_of("extra");
let vi = if cx.is_extra {
ast::view_item_use(
~[@nospan(ast::view_path_simple(id_extra,
path_node(~[id_extra]),
ast::DUMMY_NODE_ID))])
} else {
let mi = attr::mk_name_value_item_str(@"vers", @"0.9-pre");
ast::view_item_extern_mod(id_extra, None, ~[mi], ast::DUMMY_NODE_ID)
};
ast::view_item {
node: vi,
attrs: ~[],
vis: ast::public,
span: dummy_sp()
}
}
fn mk_test_module(cx: &TestCtxt) -> @ast::item {
// Link to extra
let view_items = ~[mk_std(cx)];
// A constant vector of test descriptors.
let tests = mk_tests(cx);
// The synthesized main function which will call the console test runner
// with our list of tests
let mainfn = (quote_item!(cx.ext_cx,
pub fn main() {
#[main];
extra::test::test_main_static(::std::os::args(), TESTS);
}
)).unwrap();
let testmod = ast::_mod {
view_items: view_items,
items: ~[mainfn, tests],
};
let item_ = ast::item_mod(testmod);
// This attribute tells resolve to let us call unexported functions
let resolve_unexported_attr =
attr::mk_attr(attr::mk_word_item(@"!resolve_unexported"));
let item = ast::item {
ident: cx.sess.ident_of("__test"),
attrs: ~[resolve_unexported_attr],
id: ast::DUMMY_NODE_ID,
node: item_,
vis: ast::public,
span: dummy_sp(),
};
debug2!("Synthetic test module:\n{}\n",
pprust::item_to_str(@item.clone(), cx.sess.intr()));
return @item;
}
fn nospan<T>(t: T) -> codemap::Spanned<T> {
codemap::Spanned { node: t, span: dummy_sp() }
}
fn path_node(ids: ~[ast::Ident]) -> ast::Path {
ast::Path {
span: dummy_sp(),
global: false,
segments: ids.move_iter().map(|identifier| ast::PathSegment {
identifier: identifier,
lifetime: None,
types: opt_vec::Empty,
}).collect()
}
}
fn path_node_global(ids: ~[ast::Ident]) -> ast::Path {
ast::Path {
span: dummy_sp(),
global: true,
segments: ids.move_iter().map(|identifier| ast::PathSegment {
identifier: identifier,
lifetime: None,
types: opt_vec::Empty,
}).collect()
}
}
fn mk_tests(cx: &TestCtxt) -> @ast::item {
// The vector of test_descs for this crate
let test_descs = mk_test_descs(cx);
(quote_item!(cx.ext_cx,
pub static TESTS : &'static [self::extra::test::TestDescAndFn] =
$test_descs
;
)).unwrap()
}
fn is_extra(crate: &ast::Crate) -> bool {
let items = attr::find_linkage_metas(crate.attrs);
match attr::last_meta_item_value_str_by_name(items, "name") {
Some(s) if "extra" == s => true,
_ => false
}
}
fn mk_test_descs(cx: &TestCtxt) -> @ast::Expr {
debug2!("building test vector from {} tests", cx.testfns.len());
let mut descs = ~[];
for test in cx.testfns.iter() {
descs.push(mk_test_desc_and_fn_rec(cx, test));
}
let inner_expr = @ast::Expr {
id: ast::DUMMY_NODE_ID,
node: ast::ExprVec(descs, ast::MutImmutable),
span: dummy_sp(),
};
@ast::Expr {
id: ast::DUMMY_NODE_ID,
node: ast::ExprVstore(inner_expr, ast::ExprVstoreSlice),
span: dummy_sp(),
}
}
fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> @ast::Expr {
let span = test.span;
let path = test.path.clone();
debug2!("encoding {}", ast_util::path_name_i(path));
let name_lit: ast::lit =
nospan(ast::lit_str(ast_util::path_name_i(path).to_managed()));
let name_expr = @ast::Expr {
id: ast::DUMMY_NODE_ID,
node: ast::ExprLit(@name_lit),
span: span
};
let fn_path = path_node_global(path);
let fn_expr = @ast::Expr {
id: ast::DUMMY_NODE_ID,
node: ast::ExprPath(fn_path),
span: span,
};
let t_expr = if test.bench {
quote_expr!(cx.ext_cx, self::extra::test::StaticBenchFn($fn_expr) )
} else {
quote_expr!(cx.ext_cx, self::extra::test::StaticTestFn($fn_expr) )
};
let ignore_expr = if test.ignore {
quote_expr!(cx.ext_cx, true )
} else {
quote_expr!(cx.ext_cx, false )
};
let fail_expr = if test.should_fail {
quote_expr!(cx.ext_cx, true )
} else {
quote_expr!(cx.ext_cx, false )
};
let e = quote_expr!(cx.ext_cx,
self::extra::test::TestDescAndFn {
desc: self::extra::test::TestDesc {
name: self::extra::test::StaticTestName($name_expr),
ignore: $ignore_expr,
should_fail: $fail_expr
},
testfn: $t_expr,
}
);
e
}
| 28.688596 | 81 | 0.539444 |
7a1828b6739f1291bd7788a564b108c2bce8f824 | 7,291 | // Copyright 2018 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.
pub mod nonce;
// Used in PRF as specified in IEEE Std 802.11-2016, 12.7.1.2.
use crate::Error;
use anyhow::ensure;
use mundane::hash::Digest;
#[allow(deprecated)]
use mundane::insecure::InsecureHmacSha1;
const VALID_PRF_BIT_SIZES: [usize; 6] = [128, 192, 256, 384, 512, 704];
// IEEE Std 802.11-2016, 12.7.1.2
// HMAC-SHA1 is considered insecure but is required to be used in IEEE 802.11's PRF.
#[allow(deprecated)]
pub(crate) fn prf(k: &[u8], a: &str, b: &[u8], bits: usize) -> Result<Vec<u8>, anyhow::Error> {
ensure!(VALID_PRF_BIT_SIZES.contains(&bits), Error::InvalidBitSize(bits));
let mut result = Vec::with_capacity(bits / 8);
let iterations = (bits + 159) / 160;
for i in 0..iterations {
let mut hmac: InsecureHmacSha1 = InsecureHmacSha1::insecure_new(k);
hmac.insecure_update(a.as_bytes());
hmac.insecure_update(&[0u8]);
hmac.insecure_update(b);
hmac.insecure_update(&[i as u8]);
result.extend_from_slice(&hmac.insecure_finish().bytes()[..]);
}
result.resize(bits / 8, 0);
Ok(result)
}
#[cfg(test)]
mod tests {
use super::*;
use hex::FromHex;
const VALID_BIT_SIZES: [usize; 6] = [128, 192, 256, 384, 512, 704];
// IEEE Std 802.11-2016, J.3.2, Test case 1
#[test]
fn test_prf_test_case_1() {
let key = Vec::from_hex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b").unwrap();
let actual = prf(&key[..], "prefix", "Hi There".as_bytes(), 512);
assert_eq!(actual.is_ok(), true);
let expected = Vec::from_hex("bcd4c650b30b9684951829e0d75f9d54b862175ed9f00606e17d8da35402ffee75df78c3d31e0f889f012120c0862beb67753e7439ae242edb8373698356cf5a").unwrap();
assert_eq!(actual.unwrap(), expected);
}
// IEEE Std 802.11-2016, J.3.2, Test case 2
#[test]
fn test_prf_test_case_2() {
let key = "Jefe".as_bytes();
let actual = prf(&key[..], "prefix", "what do ya want for nothing?".as_bytes(), 512);
assert_eq!(actual.is_ok(), true);
let expected = Vec::from_hex("51f4de5b33f249adf81aeb713a3c20f4fe631446fabdfa58244759ae58ef9009a99abf4eac2ca5fa87e692c440eb40023e7babb206d61de7b92f41529092b8fc").unwrap();
assert_eq!(actual.unwrap(), expected);
}
// IEEE Std 802.11-2016, J.3.2, Test case 3
#[test]
fn test_prf_test_case_3() {
let key = Vec::from_hex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
let data: [u8; 50] = [0xdd; 50];
let actual = prf(&key[..], "prefix", &data[..], 512);
assert_eq!(actual.is_ok(), true);
let expected = Vec::from_hex("e1ac546ec4cb636f9976487be5c86be17a0252ca5d8d8df12cfb0473525249ce9dd8d177ead710bc9b590547239107aef7b4abd43d87f0a68f1cbd9e2b6f7607").unwrap();
assert_eq!(actual.unwrap(), expected);
}
// IEEE Std 802.11-2016, J.6.5, Test case 1
#[test]
fn test_prf_test_case_65_1() {
let key = Vec::from_hex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b").unwrap();
let actual = prf(&key[..], "prefix", "Hi There".as_bytes(), 192);
assert_eq!(actual.is_ok(), true);
let expected = Vec::from_hex("bcd4c650b30b9684951829e0d75f9d54b862175ed9f00606").unwrap();
assert_eq!(actual.unwrap(), expected);
}
// IEEE Std 802.11-2016, J.6.5, Test case 2
#[test]
fn test_prf_test_case_65_2() {
let key = "Jefe".as_bytes();
let actual = prf(&key[..], "prefix-2", "what do ya want for nothing?".as_bytes(), 256);
assert_eq!(actual.is_ok(), true);
let expected =
Vec::from_hex("47c4908e30c947521ad20be9053450ecbea23d3aa604b77326d8b3825ff7475c")
.unwrap();
assert_eq!(actual.unwrap(), expected);
}
// IEEE Std 802.11-2016, J.6.5, Test case 3
#[test]
fn test_prf_test_case_65_3() {
let key = Vec::from_hex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
let actual = prf(
&key[..],
"prefix-3",
"Test Using Larger Than Block-Size Key - Hash Key First".as_bytes(),
384,
);
assert_eq!(actual.is_ok(), true);
let expected = Vec::from_hex("0ab6c33ccf70d0d736f4b04c8a7373255511abc5073713163bd0b8c9eeb7e1956fa066820a73ddee3f6d3bd407e0682a").unwrap();
assert_eq!(actual.unwrap(), expected);
}
// IEEE Std 802.11-2016, J.6.5, Test case 4
#[test]
fn test_prf_test_case_65_4() {
let key = Vec::from_hex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b").unwrap();
let actual = prf(&key[..], "prefix-4", "Hi There Again".as_bytes(), 512);
assert_eq!(actual.is_ok(), true);
let expected = Vec::from_hex("248cfbc532ab38ffa483c8a2e40bf170eb542a2e0916d7bf6d97da2c4c5ca877736c53a65b03fa4b3745ce7613f6ad68e0e4a798b7cf691c96176fd634a59a49").unwrap();
assert_eq!(actual.unwrap(), expected);
}
#[test]
fn test_prf_empty_key() {
let key: [u8; 0] = [];
let actual = prf(&key[..], "something is happening", "Lorem ipsum".as_bytes(), 256);
assert_eq!(actual.is_ok(), true);
let expected =
Vec::from_hex("5b154287399baeabd7d2c9682989e0933b3fdef8211ae7ae0c6586bb1e38de7c")
.unwrap();
assert_eq!(actual.unwrap(), expected);
}
#[test]
fn test_prf_empty_prefix() {
let key = Vec::from_hex("aaaa").unwrap();
let actual = prf(&key[..], "", "Lorem ipsum".as_bytes(), 256);
assert_eq!(actual.is_ok(), true);
let expected =
Vec::from_hex("1317523ae07f212fc4139ce9ebafe31ecf7c59cb07c7a7f04131afe7a59de60c")
.unwrap();
assert_eq!(actual.unwrap(), expected);
}
#[test]
fn test_prf_empty_data() {
let key = Vec::from_hex("aaaa").unwrap();
let actual = prf(&key[..], "some prefix", "".as_bytes(), 192);
assert_eq!(actual.is_ok(), true);
let expected = Vec::from_hex("785e095774cfea480c267e74130cb86d1e3fc80095b66554").unwrap();
assert_eq!(actual.unwrap(), expected);
}
#[test]
fn test_prf_all_empty() {
let key: [u8; 0] = [];
let actual = prf(&key[..], "", "".as_bytes(), 128);
assert_eq!(actual.is_ok(), true);
let expected = Vec::from_hex("310354661a5962d5b8cb76032d5a97e8").unwrap();
assert_eq!(actual.unwrap(), expected);
}
#[test]
fn test_prf_valid_bit_sizes() {
for bits in &VALID_BIT_SIZES {
let result = prf("".as_bytes(), "", "".as_bytes(), *bits as usize);
assert_eq!(result.is_ok(), true, "expected success with valid bit size: {:?}", *bits);
}
}
#[test]
fn test_prf_invalid_bit_sizes() {
for bits in 0..2048_usize {
if VALID_BIT_SIZES.contains(&bits) {
continue;
}
let result = prf("".as_bytes(), "", "".as_bytes(), bits as usize);
assert_eq!(result.is_err(), true, "expected failure with wrong bit size: {:?}", bits);
}
}
}
| 38.172775 | 205 | 0.632424 |
2129df773dac651bfb6ea8317de8b34e291d0d53 | 100 | pub mod models;
pub mod operations;
#[allow(dead_code)]
pub const API_VERSION: &str = "2021-10-15";
| 20 | 43 | 0.72 |
72f1c36b01fe7a77ca6105d7333d90dd75056f9e | 10,593 | use crate::tokio::sync::mpsc::{channel, Receiver, Sender};
use crate::{error::Error, relay::RelayMessage, router::SenderPair};
use core::fmt::Formatter;
use ockam_core::compat::{string::String, vec::Vec};
use ockam_core::{Address, AddressSet};
/// Messages sent from the Node to the Executor
#[derive(Debug)]
pub enum NodeMessage {
/// Start a new worker and store the send handle
StartWorker {
/// The set of addresses in use by this worker
addrs: AddressSet,
/// Pair of senders to the worker relay (msgs and ctrl)
senders: SenderPair,
/// A bare worker runs no relay state
bare: bool,
/// Reply channel for command confirmation
reply: Sender<NodeReplyResult>,
},
/// Return a list of all worker addresses
ListWorkers(Sender<NodeReplyResult>),
/// Add an existing address to a cluster
SetCluster(Address, String, Sender<NodeReplyResult>),
/// Stop an existing worker
StopWorker(Address, Sender<NodeReplyResult>),
/// Start a new processor
StartProcessor(Address, SenderPair, Sender<NodeReplyResult>),
/// Stop an existing processor
StopProcessor(Address, Sender<NodeReplyResult>),
/// Stop the node (and all workers)
StopNode(ShutdownType, Sender<NodeReplyResult>),
/// Immediately stop the node runtime
AbortNode,
/// Let the router know a particular address has stopped
StopAck(Address),
/// Request the sender for a worker address
SenderReq(Address, Sender<NodeReplyResult>),
/// Register a new router for a route id type
Router(u8, Address, Sender<NodeReplyResult>),
/// Message the router to set an address as "ready"
SetReady(Address),
/// Check whether an address has been marked as "ready"
CheckReady(Address, Sender<NodeReplyResult>),
}
impl core::fmt::Display for NodeMessage {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
match self {
NodeMessage::StartWorker { .. } => write!(f, "StartWorker"),
NodeMessage::ListWorkers(_) => write!(f, "ListWorkers"),
NodeMessage::SetCluster(_, _, _) => write!(f, "SetCluster"),
NodeMessage::StopWorker(_, _) => write!(f, "StopWorker"),
NodeMessage::StartProcessor(_, _, _) => write!(f, "StartProcessor"),
NodeMessage::StopProcessor(_, _) => write!(f, "StopProcessor"),
NodeMessage::StopNode(_, _) => write!(f, "StopNode"),
NodeMessage::AbortNode => write!(f, "AbortNode"),
NodeMessage::StopAck(_) => write!(f, "StopAck"),
NodeMessage::SenderReq(_, _) => write!(f, "SenderReq"),
NodeMessage::Router(_, _, _) => write!(f, "Router"),
NodeMessage::SetReady(_) => write!(f, "SetReady"),
NodeMessage::CheckReady(_, _) => write!(f, "CheckReady"),
}
}
}
impl NodeMessage {
/// Create a start worker message
///
/// * `senders`: message and command senders for the relay
///
/// * `bare`: indicate whether this worker address has a full
/// relay behind it that can respond to shutdown commands.
/// Setting this to `true` will disable stop ACK support in the
/// router
pub fn start_worker(
addrs: AddressSet,
senders: SenderPair,
bare: bool,
) -> (Self, Receiver<NodeReplyResult>) {
let (reply, rx) = channel(1);
(
Self::StartWorker {
addrs,
senders,
bare,
reply,
},
rx,
)
}
/// Create a start worker message
pub fn start_processor(
address: Address,
senders: SenderPair,
) -> (Self, Receiver<NodeReplyResult>) {
let (tx, rx) = channel(1);
(Self::StartProcessor(address, senders, tx), rx)
}
/// Create a stop worker message and reply receiver
pub fn stop_processor(address: Address) -> (Self, Receiver<NodeReplyResult>) {
let (tx, rx) = channel(1);
(Self::StopProcessor(address, tx), rx)
}
/// Create a list worker message and reply receiver
pub fn list_workers() -> (Self, Receiver<NodeReplyResult>) {
let (tx, rx) = channel(1);
(Self::ListWorkers(tx), rx)
}
/// Create a set cluster message and reply receiver
pub fn set_cluster(addr: Address, label: String) -> (Self, Receiver<NodeReplyResult>) {
let (tx, rx) = channel(1);
(Self::SetCluster(addr, label, tx), rx)
}
/// Create a stop worker message and reply receiver
pub fn stop_worker(address: Address) -> (Self, Receiver<NodeReplyResult>) {
let (tx, rx) = channel(1);
(Self::StopWorker(address, tx), rx)
}
/// Create a stop node message
pub fn stop_node(tt: ShutdownType) -> (Self, Receiver<NodeReplyResult>) {
let (tx, rx) = channel(1);
(Self::StopNode(tt, tx), rx)
}
/// Create a sender request message and reply receiver
pub fn sender_request(route: Address) -> (Self, Receiver<NodeReplyResult>) {
let (tx, rx) = channel(1);
(Self::SenderReq(route, tx), rx)
}
/// Create a SetReady message and reply receiver
pub fn set_ready(addr: Address) -> Self {
Self::SetReady(addr)
}
/// Create a GetReady message and reply receiver
pub fn get_ready(addr: Address) -> (Self, Receiver<NodeReplyResult>) {
let (tx, rx) = channel(1);
(Self::CheckReady(addr, tx), rx)
}
}
/// The reply/result of a Node
pub type NodeReplyResult = Result<NodeReply, NodeError>;
/// Successful return values from a router command
#[derive(Debug)]
pub enum NodeReply {
/// Success with no payload
Ok,
/// A list of worker addresses
Workers(Vec<Address>),
/// Message sender to a specific worker
Sender {
/// The address a message is being sent to
addr: Address,
/// The relay sender
sender: Sender<RelayMessage>,
/// Indicate whether the relay message needs to be constructed
/// with router wrapping.
wrap: bool,
},
/// Indicate the 'ready' state of an address
State(bool),
}
/// Failure states from a router command
#[derive(Debug)]
pub enum NodeError {
/// No such address existst (for either workers or processors)
NoSuchAddress(Address),
/// Worker already exists
WorkerExists(Address),
/// Router already exists
RouterExists,
/// Command rejected
Rejected(Reason),
}
/// The reason why a command was rejected
#[derive(Debug, Copy, Clone)]
pub enum Reason {
/// Rejected because the node is currently shutting down
NodeShutdown,
/// Rejected because the worker is currently shutting down
WorkerShutdown,
/// Message was addressed to an invalid address
InvalidAddress,
}
/// Specify the type of node shutdown
///
/// For most users `ShutdownType::Graceful()` is recommended. The
/// `Default` implementation uses a 1 second timeout.
#[derive(Debug, Copy, Clone)]
#[non_exhaustive]
pub enum ShutdownType {
/// Execute a graceful shutdown given a maximum timeout
///
/// The following steps will be taken by the internal router
/// during graceful shutdown procedure:
///
/// * Signal clusterless workers to stop
/// * Wait for shutdown ACK hooks from worker set
/// * Signal worker clusters in reverse-creation order to stop
/// * Wait for shutdown ACK hooks from each cluster before moving onto the
/// next
/// * All shutdown-signalled workers may process their entire mailbox,
/// while not allowing new messages to be queued
///
/// Graceful shutdown procedure will be pre-maturely terminated
/// when reaching the timeout (failover into `Immediate`
/// strategy). **A given timeout of `0` will wait forever!**
Graceful(u8),
/// Immediately shutdown workers and run shutdown hooks
///
/// This strategy can lead to data loss:
///
/// * Unhandled mailbox messages will be dropped
/// * Shutdown hooks may not be able to send messages
///
/// This strategy is not recommended for general use, but will be
/// selected as a failover, if the `Graceful` strategy reaches its
/// timeout limit.
Immediate,
}
impl Default for ShutdownType {
fn default() -> Self {
Self::Graceful(1)
}
}
impl NodeReply {
/// Return [NodeReply::Ok]
pub fn ok() -> NodeReplyResult {
Ok(NodeReply::Ok)
}
/// Return [NodeReply::State]
pub fn state(b: bool) -> NodeReplyResult {
Ok(NodeReply::State(b))
}
/// Return [NodeError::NoSuchWorker]
pub fn no_such_address(a: Address) -> NodeReplyResult {
Err(NodeError::NoSuchAddress(a))
}
/// Return [NodeError::WorkerExists] for the given address
pub fn worker_exists(a: Address) -> NodeReplyResult {
Err(NodeError::WorkerExists(a))
}
/// Return [NodeError::RouterExists]
pub fn router_exists() -> NodeReplyResult {
Err(NodeError::RouterExists)
}
/// Return [NodeReply::Rejected(reason)]
pub fn rejected(reason: Reason) -> NodeReplyResult {
Err(NodeError::Rejected(reason))
}
/// Return [NodeReply::Workers] for the given addresses
pub fn workers(v: Vec<Address>) -> NodeReplyResult {
Ok(Self::Workers(v))
}
/// Return [NodeReply::Sender] for the given information
pub fn sender(addr: Address, sender: Sender<RelayMessage>, wrap: bool) -> NodeReplyResult {
Ok(NodeReply::Sender { addr, sender, wrap })
}
/// Consume the wrapper and return [NodeReply::Sender]
pub fn take_sender(self) -> Result<(Address, Sender<RelayMessage>, bool), Error> {
match self {
Self::Sender { addr, sender, wrap } => Ok((addr, sender, wrap)),
_ => Err(Error::InternalIOFailure),
}
}
/// Consume the wrapper and return [NodeReply::Workers]
pub fn take_workers(self) -> Result<Vec<Address>, Error> {
match self {
Self::Workers(w) => Ok(w),
_ => Err(Error::InternalIOFailure),
}
}
/// Consume the wrapper and return [NodeReply::State]
pub fn take_state(self) -> Result<bool, Error> {
match self {
Self::State(b) => Ok(b),
_ => Err(Error::InternalIOFailure),
}
}
/// Returns Ok if self is [NodeReply::Ok]
pub fn is_ok(self) -> Result<(), Error> {
match self {
Self::Ok => Ok(()),
_ => Err(Error::InternalIOFailure),
}
}
}
| 33.735669 | 95 | 0.6172 |
fc19c9de76bdadd1bd1c9ecb804e40ad1f2ccb45 | 591 | use castflip::experimental::EncastArg;
use crate::{IData1, IVals1};
#[test]
fn idata1() {
let idata1 = IData1::gen();
let ne_vals_from_ne = IVals1 {
val1_i8: i8::encast( &idata1.ne_bytes[ 0 .. 1]).unwrap(),
val2_i8: i8::encast( &idata1.ne_bytes[ 1 .. 2]).unwrap(),
val_i16: i16::encast( &idata1.ne_bytes[ 2 .. 4]).unwrap(),
val_i32: i32::encast( &idata1.ne_bytes[ 4 .. 8]).unwrap(),
val_i64: i64::encast( &idata1.ne_bytes[ 8 .. 16]).unwrap(),
val_i128: i128::encast(&idata1.ne_bytes[16 .. 32]).unwrap(),
};
assert_eq!(ne_vals_from_ne, idata1.ne_vals);
}
| 29.55 | 61 | 0.632826 |
ff81f1164396a7f4f45f04b507015e11608f9908 | 21,682 | // 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 not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#![allow(non_camel_case_types)]
#[cfg(feature = "mesalock_sgx")]
use std::prelude::v1::*;
use crate::deps::c_void;
use crate::deps::cmp;
use crate::deps::errno;
use crate::deps::libc;
use crate::deps::sgx_aes_gcm_128bit_tag_t;
use crate::deps::sgx_key_128bit_t;
use crate::deps::size_t;
use crate::deps::CStr;
use crate::deps::{c_char, c_int};
use crate::deps::{int32_t, int64_t};
use crate::deps::{SysError, SysResult};
pub type SGX_FILE = *mut c_void;
extern "C" {
//
// sgx_tprotected_fs.h
//
pub fn sgx_fopen(
filename: *const c_char,
mode: *const c_char,
key: *const sgx_key_128bit_t,
) -> SGX_FILE;
pub fn sgx_fopen_auto_key(filename: *const c_char, mode: *const c_char) -> SGX_FILE;
pub fn sgx_fwrite(ptr: *const c_void, size: size_t, count: size_t, stream: SGX_FILE) -> size_t;
pub fn sgx_fread(ptr: *mut c_void, size: size_t, count: size_t, stream: SGX_FILE) -> size_t;
pub fn sgx_ftell(stream: SGX_FILE) -> int64_t;
pub fn sgx_fseek(stream: SGX_FILE, offset: int64_t, origin: c_int) -> int32_t;
pub fn sgx_fflush(stream: SGX_FILE) -> int32_t;
pub fn sgx_ferror(stream: SGX_FILE) -> int32_t;
pub fn sgx_feof(stream: SGX_FILE) -> int32_t;
pub fn sgx_clearerr(stream: SGX_FILE);
pub fn sgx_fclose(stream: SGX_FILE) -> int32_t;
pub fn sgx_remove(filename: *const c_char) -> int32_t;
#[cfg(feature = "mesalock_sgx")]
pub fn sgx_fexport_auto_key(filename: *const c_char, key: *mut sgx_key_128bit_t) -> int32_t;
#[cfg(feature = "mesalock_sgx")]
pub fn sgx_fimport_auto_key(filename: *const c_char, key: *const sgx_key_128bit_t) -> int32_t;
pub fn sgx_fclear_cache(stream: SGX_FILE) -> int32_t;
pub fn sgx_get_current_meta_gmac(
stream: SGX_FILE,
out_gmac: *mut sgx_aes_gcm_128bit_tag_t,
) -> int32_t;
pub fn sgx_rename_meta(stream: SGX_FILE, old: *const c_char, new: *const c_char) -> int32_t;
}
fn max_len() -> usize {
u32::max_value() as usize
}
unsafe fn rsgx_fopen(filename: &CStr, mode: &CStr, key: &sgx_key_128bit_t) -> SysResult<SGX_FILE> {
let file = sgx_fopen(
filename.as_ptr(),
mode.as_ptr(),
key as *const sgx_key_128bit_t,
);
if file.is_null() {
Err(errno())
} else {
Ok(file)
}
}
unsafe fn rsgx_fopen_auto_key(filename: &CStr, mode: &CStr) -> SysResult<SGX_FILE> {
let file = sgx_fopen_auto_key(filename.as_ptr(), mode.as_ptr());
if file.is_null() {
Err(errno())
} else {
Ok(file)
}
}
unsafe fn rsgx_fwrite(stream: SGX_FILE, buf: &[u8]) -> SysResult<usize> {
if stream.is_null() {
return Err(libc::EINVAL);
}
let write_size = cmp::min(buf.len(), max_len());
let ret_size = sgx_fwrite(buf.as_ptr() as *const c_void, 1, write_size, stream);
if ret_size != write_size {
Err(rsgx_ferror(stream))
} else {
Ok(ret_size)
}
}
unsafe fn rsgx_fread(stream: SGX_FILE, buf: &mut [u8]) -> SysResult<usize> {
if stream.is_null() {
return Err(libc::EINVAL);
}
let read_size = cmp::min(buf.len(), max_len());
let ret_size = sgx_fread(buf.as_mut_ptr() as *mut c_void, 1, read_size, stream);
if ret_size != read_size {
let is_eof = rsgx_feof(stream)?;
if is_eof {
Ok(ret_size)
} else {
Err(rsgx_ferror(stream))
}
} else {
Ok(ret_size)
}
}
unsafe fn rsgx_ftell(stream: SGX_FILE) -> SysResult<i64> {
if stream.is_null() {
return Err(libc::EINVAL);
}
let pos = sgx_ftell(stream);
if pos == -1 {
Err(errno())
} else {
Ok(pos)
}
}
unsafe fn rsgx_fseek(stream: SGX_FILE, offset: i64, origin: i32) -> SysError {
if stream.is_null() {
return Err(libc::EINVAL);
}
let ret = sgx_fseek(stream, offset, origin);
if ret == 0 {
Ok(())
} else {
Err(rsgx_ferror(stream))
}
}
unsafe fn rsgx_fflush(stream: SGX_FILE) -> SysError {
let ret = sgx_fflush(stream);
if ret == 0 {
Ok(())
} else if ret == libc::EOF {
Err(rsgx_ferror(stream))
} else {
Err(ret)
}
}
unsafe fn rsgx_ferror(stream: SGX_FILE) -> i32 {
let mut err = sgx_ferror(stream);
if err == -1 {
err = libc::EINVAL;
}
err
}
unsafe fn rsgx_feof(stream: SGX_FILE) -> SysResult<bool> {
if stream.is_null() {
return Err(libc::EINVAL);
}
if sgx_feof(stream) == 1 {
Ok(true)
} else {
Ok(false)
}
}
unsafe fn rsgx_clearerr(stream: SGX_FILE) {
sgx_clearerr(stream)
}
unsafe fn rsgx_fclose(stream: SGX_FILE) -> SysError {
if stream.is_null() {
return Err(libc::EINVAL);
}
let ret = sgx_fclose(stream);
if ret == 0 {
Ok(())
} else {
Err(libc::EIO)
}
}
unsafe fn rsgx_fclear_cache(stream: SGX_FILE) -> SysError {
if stream.is_null() {
return Err(libc::EINVAL);
}
let ret = sgx_fclear_cache(stream);
if ret == 0 {
Ok(())
} else {
Err(rsgx_ferror(stream))
}
}
unsafe fn rsgx_get_current_meta_gmac(
stream: SGX_FILE,
out_gmac: &mut sgx_aes_gcm_128bit_tag_t,
) -> SysError {
if stream.is_null() {
return Err(libc::EINVAL);
}
let ret = sgx_get_current_meta_gmac(stream, out_gmac as *mut sgx_aes_gcm_128bit_tag_t);
if ret == 0 {
Ok(())
} else {
Err(rsgx_ferror(stream))
}
}
unsafe fn rsgx_rename_meta(stream: SGX_FILE, old: &CStr, new: &CStr) -> SysError {
if stream.is_null() {
return Err(libc::EINVAL);
}
let ret = sgx_rename_meta(stream, old.as_ptr(), new.as_ptr());
if ret == 0 {
Ok(())
} else {
Err(rsgx_ferror(stream))
}
}
unsafe fn rsgx_remove(filename: &CStr) -> SysError {
let ret = sgx_remove(filename.as_ptr());
if ret == 0 {
Ok(())
} else {
Err(errno())
}
}
#[cfg(feature = "mesalock_sgx")]
unsafe fn rsgx_fexport_auto_key(filename: &CStr, key: &mut sgx_key_128bit_t) -> SysError {
let ret = sgx_fexport_auto_key(filename.as_ptr(), key as *mut sgx_key_128bit_t);
if ret == 0 {
Ok(())
} else {
Err(errno())
}
}
#[cfg(feature = "mesalock_sgx")]
unsafe fn rsgx_fimport_auto_key(filename: &CStr, key: &sgx_key_128bit_t) -> SysError {
let ret = sgx_fimport_auto_key(filename.as_ptr(), key as *const sgx_key_128bit_t);
if ret == 0 {
Ok(())
} else {
Err(errno())
}
}
pub struct SgxFileStream {
stream: SGX_FILE,
}
impl SgxFileStream {
///
/// The open function creates or opens a protected file.
///
/// # Description
///
/// open is similar to the C file API fopen. It creates a new Protected File or opens an existing
/// Protected File created with a previous call to open. Regular files cannot be opened with this API.
///
/// # Parameters
///
/// **filename**
///
/// The name of the file to be created or opened.
///
/// **mode**
///
/// The file open mode string. Allowed values are any combination of ‘r’, ‘w’ or ‘a’, with possible ‘+’
/// and possible ‘b’ (since string functions are currently not sup- ported, ‘b’ is meaningless).
///
/// **key**
///
/// The encryption key of the file. This key is used as a key derivation key, used for deriving encryption
/// keys for the file. If the file is created with open, you should protect this key and provide it as
/// input every time the file is opened.
///
/// # Requirements
///
/// Header: sgx_tprotected_fs.edl
///
/// Library: libsgx_tprotected_fs.a
///
/// # Return value
///
/// If the function succeeds, it returns a valid file pointer, which can be used by all the other functions
/// in the Protected FS API, otherwise, error code is returned.
///
pub fn open(filename: &CStr, mode: &CStr, key: &sgx_key_128bit_t) -> SysResult<SgxFileStream> {
unsafe { rsgx_fopen(filename, mode, key).map(|f| SgxFileStream { stream: f }) }
}
///
/// The open_auto_key function creates or opens a protected file.
///
/// # Description
///
/// open_auto_key is similar to the C file API fopen. It creates a new Protected File or opens an existing
/// Protected File created with a previous call to open_auto_key. Regular files cannot be opened with this API.
///
/// # Parameters
///
/// **filename**
///
/// The name of the file to be created or opened.
///
/// **mode**
///
/// The file open mode string. Allowed values are any combination of ‘r’, ‘w’ or ‘a’, with possible ‘+’
/// and possible ‘b’ (since string functions are currently not sup- ported, ‘b’ is meaningless).
///
/// # Requirements
///
/// Header: sgx_tprotected_fs.edl
///
/// Library: libsgx_tprotected_fs.a
///
/// # Return value
///
/// If the function succeeds, it returns a valid file pointer, which can be used by all the other functions
/// in the Protected FS API, otherwise, error code is returned.
///
pub fn open_auto_key(filename: &CStr, mode: &CStr) -> SysResult<SgxFileStream> {
unsafe { rsgx_fopen_auto_key(filename, mode).map(|f| SgxFileStream { stream: f }) }
}
///
/// The read function reads the requested amount of data from the file, and extends the file pointer by that amount.
///
/// # Description
///
/// read is similar to the file API fread. In case of an error, error can be called to get the error code.
///
/// # Parameters
///
/// **buf**
///
/// A pointer to a buffer to receive the data read from the file.
///
/// # Requirements
///
/// Header: sgx_tprotected_fs.edl
///
/// Library: libsgx_tprotected_fs.a
///
/// # Return value
///
/// If the function succeeds, the number of bytes read is returned (zero indicates end of file).
/// otherwise, error code is returned.
///
pub fn read(&self, buf: &mut [u8]) -> SysResult<usize> {
unsafe { rsgx_fread(self.stream, buf) }
}
///
/// The write function writes the given amount of data to the file, and extends the file pointer by that amount.
///
/// # Description
///
/// write is similar to the file API fwrite. In case of an error, error can be called to get the error code.
///
/// # Parameters
///
/// **buf**
///
/// A pointer to a buffer, that contains the data to write to the file.
///
/// # Requirements
///
/// Header: sgx_tprotected_fs.edl
///
/// Library: libsgx_tprotected_fs.a
///
/// # Return value
///
/// If the function succeeds, the number of bytes written is returned (zero indicates nothing was written).
/// otherwise, error code is returned.
///
pub fn write(&self, buf: &[u8]) -> SysResult<usize> {
unsafe { rsgx_fwrite(self.stream, buf) }
}
///
/// The tell function obtains the current value of the file position indicator for the stream pointed to by stream.
///
/// # Description
///
/// tell is similar to the C file API ftell.
///
/// # Requirements
///
/// Header: sgx_tprotected_fs.edl
///
/// Library: libsgx_tprotected_fs.a
///
/// # Return value
///
/// If the function succeeds, it returns the current value of the position indicator of the file.
/// otherwise, error code is returned.
///
pub fn tell(&self) -> SysResult<i64> {
unsafe { rsgx_ftell(self.stream) }
}
///
/// The seek function sets the current value of the position indicator of the file.
///
/// # Description
///
/// seek is similar to the C file API fseek.
///
/// # Parameters
///
/// **offset**
///
/// The new required value, relative to the origin parameter.
///
/// **origin**
///
/// The origin from which to calculate the offset (Start, ENd or Current).
///
/// # Requirements
///
/// Header: sgx_tprotected_fs.edl
///
/// Library: libsgx_tprotected_fs.a
///
/// # Return value
///
/// If the function failed, error code is returned.
///
pub fn seek(&self, offset: i64, origin: SeekFrom) -> SysError {
let whence = match origin {
SeekFrom::Start => libc::SEEK_SET,
SeekFrom::End => libc::SEEK_END,
SeekFrom::Current => libc::SEEK_CUR,
};
unsafe { rsgx_fseek(self.stream, offset, whence) }
}
///
/// The flush function forces a cache flush, and if it returns successfully, it is guaranteed
/// that your changes are committed to a file on the disk.
///
/// # Description
///
/// flush is similar to the C file API fflush. This function flushes all the modified data from
/// the cache and writes it to a file on the disk. In case of an error, error can be called to
/// get the error code. Note that this function does not clear the cache, but only flushes the
/// changes to the actual file on the disk. Flushing also happens automatically when the cache
/// is full and page eviction is required.
///
/// # Requirements
///
/// Header: sgx_tprotected_fs.edl
///
/// Library: libsgx_tprotected_fs.a
///
/// # Return value
///
/// If the function failed, error code is returned.
///
pub fn flush(&self) -> SysError {
unsafe { rsgx_fflush(self.stream) }
}
///
/// The error function returns the latest operation error code.
///
/// # Description
///
/// error is similar to the C file API ferror. In case the latest operation failed because
/// the file is in a bad state, SGX_ERROR_FILE_BAD_STATUS will be returned.
///
/// # Requirements
///
/// Header: sgx_tprotected_fs.edl
///
/// Library: libsgx_tprotected_fs.a
///
/// # Return value
///
/// The latest operation error code is returned. 0 indicates that no errors occurred.
///
/*
pub fn error(&self) -> i32 {
unsafe{ rsgx_ferror(self.stream) }
}
*/
///
/// The is_eof function tells the caller if the file's position indicator hit the end of the
/// file in a previous read operation.
///
/// # Description
///
/// is_eof is similar to the C file API feof.
///
/// # Requirements
///
/// Header: sgx_tprotected_fs.edl
///
/// Library: libsgx_tprotected_fs.a
///
/// # Return value
///
/// true - End of file was not reached. false - End of file was reached.
///
pub fn is_eof(&self) -> bool {
unsafe { rsgx_feof(self.stream).unwrap() }
}
///
/// The clearerr function attempts to repair a bad file status, and also clears the end-of-file flag.
///
/// # Description
///
/// clearerr is similar to the C file API clearerr. This function attempts to repair errors resulted
/// from the underlying file system, like write errors to the disk (resulting in a full cache thats
/// cannot be emptied). Call error or is_eof after a call to this function to learn if it was successful
/// or not.
///
/// clearerr does not repair errors resulting from a corrupted file, like decryption errors, or from
/// memory corruption, etc.
///
/// # Requirements
///
/// Header: sgx_tprotected_fs.edl
///
/// Library: libsgx_tprotected_fs.a
///
/// # Return value
///
/// None
///
pub fn clearerr(&self) {
unsafe { rsgx_clearerr(self.stream) }
}
///
/// The clear_cache function is used for clearing the internal file cache. The function scrubs all
/// the data from the cache, and releases all the allocated cache memory.
///
/// # Description
///
/// clear_cache is used to scrub all the data from the cache and release all the allocated cache
/// memory. If modified data is found in the cache, it will be written to the file on disk before
/// being scrubbed.
///
/// This function is especially useful if you do not trust parts of your own enclave (for example,
/// external libraries you linked against, etc.) and want to make sure there is as little sensitive
/// data in the memory as possible before transferring control to the code they do not trust.
/// Note, however, that the SGX_FILE structure itself still holds sensitive data. To remove all
/// such data related to the file from memory completely, you should close the file handle.
///
/// # Requirements
///
/// Header: sgx_tprotected_fs.edl
///
/// Library: libsgx_tprotected_fs.a
///
/// # Return value
///
/// If the function failed, error code is returned.
///
pub fn clear_cache(&self) -> SysError {
unsafe { rsgx_fclear_cache(self.stream) }
}
pub fn get_current_meta_gmac(&self, meta_gmac: &mut sgx_aes_gcm_128bit_tag_t) -> SysError {
unsafe { rsgx_get_current_meta_gmac(self.stream, meta_gmac) }
}
pub fn rename_meta(&self, old_name: &CStr, new_name: &CStr) -> SysError {
unsafe { rsgx_rename_meta(self.stream, old_name, new_name) }
}
}
///
/// The remove function deletes a file from the file system.
///
/// # Description
///
/// remove is similar to the C file API remove.
///
/// # Parameters
///
/// **filename**
///
/// The name of the file to delete.
///
/// # Requirements
///
/// Header: sgx_tprotected_fs.edl
///
/// Library: libsgx_tprotected_fs.a
///
/// # Return value
///
/// If the function failed, error code is returned.
///
pub fn remove(filename: &CStr) -> SysError {
unsafe { rsgx_remove(filename) }
}
///
/// The export_auto_key function is used for exporting the latest key used for the file encryption.
///
/// # Description
///
/// export_auto_key is used to export the last key that was used in the encryption of the file.
/// With this key you can import the file in a different enclave or system.
///
/// # Parameters
///
/// **filename**
///
/// The name of the file to be exported. This should be the name of a file created with the open_auto_key API.
///
/// # Requirements
///
/// Header: sgx_tprotected_fs.edl
///
/// Library: libsgx_tprotected_fs.a
///
/// # Return value
///
/// If the function succeeds, it returns the latest encryption key.
/// otherwise, error code is returned.
///
#[cfg(feature = "mesalock_sgx")]
pub fn export_auto_key(filename: &CStr) -> SysResult<sgx_key_128bit_t> {
let mut key: sgx_key_128bit_t = Default::default();
unsafe { rsgx_fexport_auto_key(filename, &mut key).map(|_| key) }
}
///
/// The import_auto_key function is used for importing a Protected FS auto key file created on
/// a different enclave or platform.
///
/// # Description
///
/// import_auto_key is used for importing a Protected FS file. After this call returns successfully,
/// the file can be opened normally with export_auto_key.
///
/// # Parameters
///
/// **filename**
///
/// The name of the file to be imported. This should be the name of a file created with the
/// open_auto_key API, on a different enclave or system.
///
/// **key**
///
/// he encryption key, exported with a call to export_auto_key in the source enclave or system.
///
/// # Requirements
///
/// Header: sgx_tprotected_fs.edl
///
/// Library: libsgx_tprotected_fs.a
///
/// # Return value
///
/// otherwise, error code is returned.
///
#[cfg(feature = "mesalock_sgx")]
pub fn import_auto_key(filename: &CStr, key: &sgx_key_128bit_t) -> SysError {
unsafe { rsgx_fimport_auto_key(filename, key) }
}
impl Drop for SgxFileStream {
fn drop(&mut self) {
// Note that errors are ignored when closing a file descriptor. The
// reason for this is that if an error occurs we don't actually know if
// the file descriptor was closed or not, and if we retried (for
// something like EINTR), we might close another valid file descriptor
// (opened after we closed ours.
let _ = unsafe { rsgx_fclose(self.stream) };
}
}
/// Enumeration of possible methods to seek within an I/O object.
#[derive(Copy, PartialEq, Eq, Clone, Debug)]
pub enum SeekFrom {
/// Set the offset to the provided number of bytes.
Start,
/// Set the offset to the size of this object plus the specified number of
/// bytes.
///
/// It is possible to seek beyond the end of an object, but it's an error to
/// seek before byte 0.
End,
/// Set the offset to the current position plus the specified number of
/// bytes.
///
/// It is possible to seek beyond the end of an object, but it's an error to
/// seek before byte 0.
Current,
}
| 29.181696 | 120 | 0.619685 |
14bc33abde715a40ee291a00d706ae5d0efde309 | 1,363 | use super::*;
use std::fmt;
mod backtrace;
mod errno;
mod error;
mod to_errno;
pub use self::backtrace::{ErrorBacktrace, ResultExt};
pub use self::errno::Errno;
pub use self::errno::Errno::*;
pub use self::error::{Error, ErrorLocation};
pub use self::to_errno::ToErrno;
pub type Result<T> = std::result::Result<T, Error>;
macro_rules! errno {
($errno_expr: expr, $error_msg: expr) => {{
let inner_error = {
let errno: Errno = $errno_expr;
let msg: &'static str = $error_msg;
(errno, msg)
};
let error = Error::embedded(inner_error, Some(ErrorLocation::new(file!(), line!())));
error
}};
($error_expr: expr) => {{
let inner_error = $error_expr;
let error = Error::boxed(inner_error, Some(ErrorLocation::new(file!(), line!())));
error
}};
}
macro_rules! return_errno {
($errno_expr: expr, $error_msg: expr) => {{
return Err(errno!($errno_expr, $error_msg));
}};
($error_expr: expr) => {{
return Err(errno!($error_expr));
}};
}
// return Err(errno) if libc return -1
macro_rules! try_libc {
($ret: expr) => {{
let ret = unsafe { $ret };
if ret < 0 {
let errno = unsafe { libc::errno() };
return_errno!(Errno::from(errno as u32), "libc error");
}
ret
}};
}
| 25.240741 | 93 | 0.564197 |
0eb1136c3c46dd278165c467ec3b6a4fe7040b1f | 1,236 | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Support code for encoding and decoding types.
#![feature(core, collections, unicode, io, std_misc, path, hash, os)]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/rustc-serialize/")]
#![cfg_attr(test, deny(warnings))]
#![cfg_attr(test, feature(test, hash))]
#[cfg(test)] extern crate test;
#[cfg(test)] extern crate rand;
extern crate unicode;
pub use self::serialize::{Decoder, Encoder, Decodable, Encodable,
DecoderHelpers, EncoderHelpers};
mod serialize;
mod collection_impls;
pub mod base64;
pub mod hex;
pub mod json;
mod rustc_serialize {
pub use serialize::*;
}
| 32.526316 | 85 | 0.709547 |
76c59e99b3f65b1852703a4ae709a56e85006110 | 1,102 | //! Requires selenium running on port 4444:
//!
//! java -jar selenium-server-standalone-3.141.59.jar
//!
//! Run as follows:
//!
//! cargo run --example tokio_async
use thirtyfour::prelude::*;
use tokio;
#[tokio::main]
async fn main() -> WebDriverResult<()> {
let caps = DesiredCapabilities::chrome();
let driver = WebDriver::new("http://localhost:4444/wd/hub", &caps).await?;
// Navigate to https://wikipedia.org.
driver.get("https://wikipedia.org").await?;
let elem_form = driver.find_element(By::Id("search-form")).await?;
// Find element from element.
let elem_text = elem_form.find_element(By::Id("searchInput")).await?;
// Type in the search terms.
elem_text.send_keys("selenium").await?;
// Click the search button.
let elem_button = elem_form.find_element(By::Css("button[type='submit']")).await?;
elem_button.click().await?;
// Look for header to implicitly wait for the page to load.
driver.find_element(By::ClassName("firstHeading")).await?;
assert_eq!(driver.title().await?, "Selenium - Wikipedia");
Ok(())
}
| 29.783784 | 86 | 0.660617 |
d931ea88cdf41a5d69a6c58366044e8677b741af | 3,786 | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::identifier::{IdentStr, Identifier, ALLOWED_IDENTIFIERS};
use crate::test_helpers::assert_canonical_encode_decode;
use once_cell::sync::Lazy;
use proptest::prelude::*;
use regex::Regex;
use serde_json;
use std::borrow::Borrow;
#[test]
fn valid_identifiers() {
let valid_identifiers = [
"foo",
"FOO",
"Foo",
"foo0",
"FOO_0",
"_Foo1",
"FOO2_",
"foo_bar_baz",
"_0",
"__",
"____________________",
// TODO: <SELF> is an exception. It should be removed once CompiledScript goes away.
"<SELF>",
];
for identifier in &valid_identifiers {
assert!(
Identifier::is_valid(identifier),
"Identifier '{}' should be valid",
identifier
);
}
}
#[test]
fn invalid_identifiers() {
let invalid_identifiers = [
"",
"_",
"0",
"01",
"9876",
"0foo",
":foo",
"fo\\o",
"fo/o",
"foo.",
"foo-bar",
"foo\u{1f389}",
];
for identifier in &invalid_identifiers {
assert!(
!Identifier::is_valid(identifier),
"Identifier '{}' should be invalid",
identifier
);
}
}
proptest! {
#[test]
fn invalid_identifiers_proptest(identifier in invalid_identifier_strategy()) {
// This effectively checks that if a string doesn't match the ALLOWED_IDENTIFIERS regex, it
// will be rejected by the is_valid validator. Note that the converse is checked by the
// Arbitrary impl for Identifier.
prop_assert!(!Identifier::is_valid(&identifier));
}
#[test]
fn identifier_string_roundtrip(identifier in any::<Identifier>()) {
let s = identifier.clone().into_string();
let id2 = Identifier::new(s).expect("identifier should parse correctly");
prop_assert_eq!(identifier, id2);
}
#[test]
fn identifier_ident_str_equivalence(identifier in any::<Identifier>()) {
let s = identifier.clone().into_string();
let ident_str = IdentStr::new(&s).expect("identifier should parse correctly");
prop_assert_eq!(ident_str, identifier.as_ident_str());
prop_assert_eq!(ident_str, identifier.as_ref());
prop_assert_eq!(ident_str, identifier.borrow());
prop_assert_eq!(ident_str.to_owned(), identifier);
}
#[test]
fn serde_json_roundtrip(identifier in any::<Identifier>()) {
let ser = serde_json::to_string(&identifier).expect("should serialize correctly");
let id2 = serde_json::from_str(&ser).expect("should deserialize correctly");
prop_assert_eq!(identifier, id2);
}
#[test]
fn identifier_canonical_serialization(identifier in any::<Identifier>()) {
assert_canonical_encode_decode(identifier);
}
}
fn invalid_identifier_strategy() -> impl Strategy<Value = String> {
static ALLOWED_IDENTIFIERS_REGEX: Lazy<Regex> = Lazy::new(|| {
// Need to add anchors to ensure the entire string is matched.
Regex::new(&format!("^(?:{})$", ALLOWED_IDENTIFIERS)).unwrap()
});
".*".prop_filter("Valid identifiers should not be generated", |s| {
// Most strings won't match the regex above, so local rejects are OK.
!ALLOWED_IDENTIFIERS_REGEX.is_match(s)
})
}
/// Ensure that Identifier instances serialize into strings directly, with no wrapper.
#[test]
fn serde_serialize_no_wrapper() {
let foobar = Identifier::new("foobar").expect("should parse correctly");
let s = serde_json::to_string(&foobar).expect("Identifier should serialize correctly");
assert_eq!(s, "\"foobar\"");
}
| 31.289256 | 99 | 0.622557 |
ccfce645310c2a9cc1578c25b3679665e145e102 | 4,039 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under both the MIT license found in the
* LICENSE-MIT file in the root directory of this source tree and the Apache
* License, Version 2.0 found in the LICENSE-APACHE file in the root directory
* of this source tree.
*/
//! Provides a macro `define_stats!` for creation of stats. This crate requires the caller to
//! schedule aggregation of stats by calling schedule_stats_aggregation and executing the returned
//! future.
#![deny(warnings, missing_docs, clippy::all, rustdoc::broken_intra_doc_links)]
pub mod macros;
mod noop_stats;
pub mod thread_local_aggregator;
pub mod prelude {
//! A "prelude" of `stats` crate.
//!
//! This prelude is similar to the standard library's prelude in that you'll
//! almost always want to import its entire contents, but unlike the standard
//! library's prelude you'll have to do so manually:
//!
//! ```
//! # #![allow(unused)]
//! use stats::prelude::*;
//! ```
pub use crate::{define_stats, define_stats_struct};
pub use stats_traits::{
dynamic_stat_types::{
DynamicCounter, DynamicHistogram, DynamicSingletonCounter, DynamicTimeseries,
},
stat_types::{
Counter, CounterStatic, Histogram, HistogramStatic, Timeseries, TimeseriesStatic,
},
};
}
use std::sync::RwLock;
use lazy_static::lazy_static;
use stats_traits::{
stat_types::BoxSingletonCounter,
stats_manager::{BoxStatsManager, StatsManagerFactory},
};
pub use self::thread_local_aggregator::schedule_stats_aggregation_preview;
lazy_static! {
static ref STATS_MANAGER_FACTORY: RwLock<Option<Box<dyn StatsManagerFactory + Send + Sync>>> =
RwLock::new(None);
}
/// This function must be called exactly once before accessing any of the stats,
/// otherwise it will panic.
/// If it won't be called a default stats manager factory will be assumed that
/// does nothing. (Facebook only: the default will use fb303 counters)
pub fn register_stats_manager_factory(factory: impl StatsManagerFactory + Send + Sync + 'static) {
let mut global_factory = STATS_MANAGER_FACTORY.write().expect("poisoned lock");
assert!(
global_factory.is_none(),
"Called stats::stats_manager::register_stats_manager_factory more than once"
);
global_factory.replace(Box::new(factory));
}
#[doc(hidden)]
/// You probably don't have to use this function, it is made public so that it
/// might be used by the macros in this crate. It reads the globally registered
/// StatsManagerFactory and creates a new instance of StatsManager.
pub fn create_stats_manager() -> BoxStatsManager {
if let Some(factory) = STATS_MANAGER_FACTORY
.read()
.expect("poisoned lock")
.as_ref()
{
return factory.create();
}
// We get here only if register_stats_manager_factory was not called yet
// but we have to keep in mind this is a race so first get hold of write
// lock and check if the factory is still unset.
let mut write_lock = STATS_MANAGER_FACTORY.write().expect("poisoned lock");
let factory = write_lock.get_or_insert_with(get_default_stats_manager_factory);
factory.create()
}
fn get_default_stats_manager_factory() -> Box<dyn StatsManagerFactory + Send + Sync> {
#[cfg(fbcode_build)]
{
Box::new(::stats_facebook::ThreadLocalStatsFactory)
}
#[cfg(not(fbcode_build))]
{
Box::new(crate::noop_stats::NoopStatsFactory)
}
}
#[doc(hidden)]
/// You probably don't have to use this function, it is made public so that it
/// might be used by the macros in this crate. It creates a new SingletonCounter.
pub fn create_singleton_counter(name: String) -> BoxSingletonCounter {
#[cfg(fbcode_build)]
{
Box::new(::stats_facebook::singleton_counter::ServiceDataSingletonCounter::new(name))
}
#[cfg(not(fbcode_build))]
{
let _ = name;
Box::new(crate::noop_stats::Noop)
}
}
| 34.818966 | 98 | 0.698688 |
1e0fe993454f670aefd6bc54af3767c7843f339f | 10,686 | use super::duration_to_str;
use super::page::Page;
use super::MetaData;
use crate::db::Pool;
use crate::docbuilder::Limits;
use chrono::{DateTime, NaiveDateTime, Utc};
use iron::prelude::*;
use router::Router;
use serde::ser::{Serialize, SerializeStruct, Serializer};
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Build {
id: i32,
rustc_version: String,
cratesfyi_version: String,
build_status: bool,
build_time: DateTime<Utc>,
output: Option<String>,
}
impl Serialize for Build {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("Build", 7)?;
state.serialize_field("id", &self.id)?;
state.serialize_field("rustc_version", &self.rustc_version)?;
state.serialize_field("cratesfyi_version", &self.cratesfyi_version)?;
state.serialize_field("build_status", &self.build_status)?;
state.serialize_field("build_time", &self.build_time.format("%+").to_string())?; // RFC 3339
state.serialize_field("build_time_relative", &duration_to_str(self.build_time))?;
state.serialize_field("output", &self.output)?;
state.end()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct BuildsPage {
metadata: Option<MetaData>,
builds: Vec<Build>,
build_details: Option<Build>,
limits: Limits,
}
impl Serialize for BuildsPage {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("Buildspage", 4)?;
state.serialize_field("metadata", &self.metadata)?;
state.serialize_field("builds", &self.builds)?;
state.serialize_field("build_details", &self.build_details)?;
state.serialize_field("limits", &self.limits.for_website())?;
state.end()
}
}
pub fn build_list_handler(req: &mut Request) -> IronResult<Response> {
let router = extension!(req, Router);
let name = cexpect!(router.find("name"));
let version = cexpect!(router.find("version"));
let req_build_id: i32 = router.find("id").unwrap_or("0").parse().unwrap_or(0);
let conn = extension!(req, Pool).get()?;
let limits = ctry!(Limits::for_crate(&conn, name));
let query = ctry!(conn.query(
"SELECT crates.name,
releases.version,
releases.description,
releases.rustdoc_status,
releases.target_name,
builds.id,
builds.rustc_version,
builds.cratesfyi_version,
builds.build_status,
builds.build_time,
builds.output
FROM builds
INNER JOIN releases ON releases.id = builds.rid
INNER JOIN crates ON releases.crate_id = crates.id
WHERE crates.name = $1 AND releases.version = $2
ORDER BY id DESC",
&[&name, &version]
));
let mut build_details = None;
// FIXME: getting builds.output may cause performance issues when release have tons of builds
let mut build_list = query
.into_iter()
.map(|row| {
let id: i32 = row.get(5);
let build = Build {
id,
rustc_version: row.get(6),
cratesfyi_version: row.get(7),
build_status: row.get(8),
build_time: DateTime::from_utc(row.get::<_, NaiveDateTime>(9), Utc),
output: row.get(10),
};
if id == req_build_id {
build_details = Some(build.clone());
}
build
})
.collect::<Vec<Build>>();
if req.url.path().join("/").ends_with(".json") {
use iron::headers::{
AccessControlAllowOrigin, CacheControl, CacheDirective, ContentType, Expires, HttpDate,
};
use iron::status;
// Remove build output from build list for json output
for build in build_list.as_mut_slice() {
build.output = None;
}
let mut resp = Response::with((status::Ok, serde_json::to_string(&build_list).unwrap()));
resp.headers
.set(ContentType("application/json".parse().unwrap()));
resp.headers.set(Expires(HttpDate(time::now())));
resp.headers.set(CacheControl(vec![
CacheDirective::NoCache,
CacheDirective::NoStore,
CacheDirective::MustRevalidate,
]));
resp.headers.set(AccessControlAllowOrigin::Any);
Ok(resp)
} else {
let builds_page = BuildsPage {
metadata: MetaData::from_crate(&conn, &name, &version),
builds: build_list,
build_details,
limits,
};
Page::new(builds_page)
.set_true("show_package_navigation")
.set_true("package_navigation_builds_tab")
.to_resp("builds")
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::Utc;
use serde_json::json;
#[test]
fn serialize_build() {
let time = Utc::now();
let mut build = Build {
id: 22,
rustc_version: "rustc 1.43.0 (4fb7144ed 2020-04-20)".to_string(),
cratesfyi_version: "docsrs 0.6.0 (3dd32ec 2020-05-01)".to_string(),
build_status: true,
build_time: time,
output: None,
};
let correct_json = json!({
"id": 22,
"rustc_version": "rustc 1.43.0 (4fb7144ed 2020-04-20)",
"cratesfyi_version": "docsrs 0.6.0 (3dd32ec 2020-05-01)",
"build_time": time.format("%+").to_string(),
"build_time_relative": duration_to_str(time),
"output": null,
"build_status": true
});
assert_eq!(correct_json, serde_json::to_value(&build).unwrap());
build.output = Some("some random stuff".to_string());
let correct_json = json!({
"id": 22,
"rustc_version": "rustc 1.43.0 (4fb7144ed 2020-04-20)",
"cratesfyi_version": "docsrs 0.6.0 (3dd32ec 2020-05-01)",
"build_time": time.format("%+").to_string(),
"build_time_relative": duration_to_str(time),
"output": "some random stuff",
"build_status": true
});
assert_eq!(correct_json, serde_json::to_value(&build).unwrap());
}
#[test]
fn serialize_build_page() {
let time = Utc::now();
let build = Build {
id: 22,
rustc_version: "rustc 1.43.0 (4fb7144ed 2020-04-20)".to_string(),
cratesfyi_version: "docsrs 0.6.0 (3dd32ec 2020-05-01)".to_string(),
build_status: true,
build_time: time,
output: None,
};
let limits = Limits::default();
let mut builds = BuildsPage {
metadata: Some(MetaData {
name: "serde".to_string(),
version: "1.0.0".to_string(),
description: Some("serde does stuff".to_string()),
target_name: None,
rustdoc_status: true,
default_target: "x86_64-unknown-linux-gnu".to_string(),
}),
builds: vec![build.clone()],
build_details: Some(build.clone()),
limits: limits.clone(),
};
let correct_json = json!({
"metadata": {
"name": "serde",
"version": "1.0.0",
"description": "serde does stuff",
"target_name": null,
"rustdoc_status": true,
"default_target": "x86_64-unknown-linux-gnu"
},
"builds": [{
"id": 22,
"rustc_version": "rustc 1.43.0 (4fb7144ed 2020-04-20)",
"cratesfyi_version": "docsrs 0.6.0 (3dd32ec 2020-05-01)",
"build_time": time.format("%+").to_string(),
"build_time_relative": duration_to_str(time),
"output": null,
"build_status": true
}],
"build_details": {
"id": 22,
"rustc_version": "rustc 1.43.0 (4fb7144ed 2020-04-20)",
"cratesfyi_version": "docsrs 0.6.0 (3dd32ec 2020-05-01)",
"build_time": time.format("%+").to_string(),
"build_time_relative": duration_to_str(time),
"output": null,
"build_status": true
},
"limits": limits.for_website(),
});
assert_eq!(correct_json, serde_json::to_value(&builds).unwrap());
builds.metadata = None;
let correct_json = json!({
"metadata": null,
"builds": [{
"id": 22,
"rustc_version": "rustc 1.43.0 (4fb7144ed 2020-04-20)",
"cratesfyi_version": "docsrs 0.6.0 (3dd32ec 2020-05-01)",
"build_time": time.format("%+").to_string(),
"build_time_relative": duration_to_str(time),
"output": null,
"build_status": true
}],
"build_details": {
"id": 22,
"rustc_version": "rustc 1.43.0 (4fb7144ed 2020-04-20)",
"cratesfyi_version": "docsrs 0.6.0 (3dd32ec 2020-05-01)",
"build_time": time.format("%+").to_string(),
"build_time_relative": duration_to_str(time),
"output": null,
"build_status": true
},
"limits": limits.for_website(),
});
assert_eq!(correct_json, serde_json::to_value(&builds).unwrap());
builds.builds = Vec::new();
let correct_json = json!({
"metadata": null,
"builds": [],
"build_details": {
"id": 22,
"rustc_version": "rustc 1.43.0 (4fb7144ed 2020-04-20)",
"cratesfyi_version": "docsrs 0.6.0 (3dd32ec 2020-05-01)",
"build_time": time.format("%+").to_string(),
"build_time_relative": duration_to_str(time),
"output": null,
"build_status": true
},
"limits": limits.for_website()
});
assert_eq!(correct_json, serde_json::to_value(&builds).unwrap());
builds.build_details = None;
let correct_json = json!({
"metadata": null,
"builds": [],
"build_details": null,
"limits": limits.for_website(),
});
assert_eq!(correct_json, serde_json::to_value(&builds).unwrap());
}
}
| 34.694805 | 100 | 0.539491 |
fb05c196317a4f6575dc4a0af18a5dd8ada1c1ac | 7,620 | // Copyright 2014-2020 bluss and ndarray developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use alloc::vec::Vec;
use crate::dimension;
use crate::error::{from_kind, ErrorKind, ShapeError};
use crate::imp_prelude::*;
/// Stack arrays along the new axis.
///
/// ***Errors*** if the arrays have mismatching shapes.
/// ***Errors*** if `arrays` is empty, if `axis` is out of bounds,
/// if the result is larger than is possible to represent.
///
/// ```
/// extern crate ndarray;
///
/// use ndarray::{arr2, arr3, stack, Axis};
///
/// # fn main() {
///
/// let a = arr2(&[[2., 2.],
/// [3., 3.]]);
/// assert!(
/// stack(Axis(0), &[a.view(), a.view()])
/// == Ok(arr3(&[[[2., 2.],
/// [3., 3.]],
/// [[2., 2.],
/// [3., 3.]]]))
/// );
/// # }
/// ```
pub fn stack<A, D>(
axis: Axis,
arrays: &[ArrayView<A, D>],
) -> Result<Array<A, D::Larger>, ShapeError>
where
A: Clone,
D: Dimension,
D::Larger: RemoveAxis,
{
#[allow(deprecated)]
stack_new_axis(axis, arrays)
}
/// Concatenate arrays along the given axis.
///
/// ***Errors*** if the arrays have mismatching shapes, apart from along `axis`.
/// (may be made more flexible in the future).<br>
/// ***Errors*** if `arrays` is empty, if `axis` is out of bounds,
/// if the result is larger than is possible to represent.
///
/// ```
/// use ndarray::{arr2, Axis, concatenate};
///
/// let a = arr2(&[[2., 2.],
/// [3., 3.]]);
/// assert!(
/// concatenate(Axis(0), &[a.view(), a.view()])
/// == Ok(arr2(&[[2., 2.],
/// [3., 3.],
/// [2., 2.],
/// [3., 3.]]))
/// );
/// ```
pub fn concatenate<A, D>(axis: Axis, arrays: &[ArrayView<A, D>]) -> Result<Array<A, D>, ShapeError>
where
A: Clone,
D: RemoveAxis,
{
if arrays.is_empty() {
return Err(from_kind(ErrorKind::Unsupported));
}
let mut res_dim = arrays[0].raw_dim();
if axis.index() >= res_dim.ndim() {
return Err(from_kind(ErrorKind::OutOfBounds));
}
let common_dim = res_dim.remove_axis(axis);
if arrays
.iter()
.any(|a| a.raw_dim().remove_axis(axis) != common_dim)
{
return Err(from_kind(ErrorKind::IncompatibleShape));
}
let stacked_dim = arrays.iter().fold(0, |acc, a| acc + a.len_of(axis));
res_dim.set_axis(axis, stacked_dim);
let new_len = dimension::size_of_shape_checked(&res_dim)?;
// start with empty array with precomputed capacity
// append's handling of empty arrays makes sure `axis` is ok for appending
res_dim.set_axis(axis, 0);
let mut res = unsafe {
// Safety: dimension is size 0 and vec is empty
Array::from_shape_vec_unchecked(res_dim, Vec::with_capacity(new_len))
};
for array in arrays {
res.append(axis, array.clone())?;
}
debug_assert_eq!(res.len_of(axis), stacked_dim);
Ok(res)
}
#[deprecated(note="Use under the name stack instead.", since="0.15.0")]
/// Stack arrays along the new axis.
///
/// ***Errors*** if the arrays have mismatching shapes.
/// ***Errors*** if `arrays` is empty, if `axis` is out of bounds,
/// if the result is larger than is possible to represent.
///
/// ```
/// extern crate ndarray;
///
/// use ndarray::{arr2, arr3, stack_new_axis, Axis};
///
/// # fn main() {
///
/// let a = arr2(&[[2., 2.],
/// [3., 3.]]);
/// assert!(
/// stack_new_axis(Axis(0), &[a.view(), a.view()])
/// == Ok(arr3(&[[[2., 2.],
/// [3., 3.]],
/// [[2., 2.],
/// [3., 3.]]]))
/// );
/// # }
/// ```
pub fn stack_new_axis<A, D>(
axis: Axis,
arrays: &[ArrayView<A, D>],
) -> Result<Array<A, D::Larger>, ShapeError>
where
A: Clone,
D: Dimension,
D::Larger: RemoveAxis,
{
if arrays.is_empty() {
return Err(from_kind(ErrorKind::Unsupported));
}
let common_dim = arrays[0].raw_dim();
// Avoid panic on `insert_axis` call, return an Err instead of it.
if axis.index() > common_dim.ndim() {
return Err(from_kind(ErrorKind::OutOfBounds));
}
let mut res_dim = common_dim.insert_axis(axis);
if arrays.iter().any(|a| a.raw_dim() != common_dim) {
return Err(from_kind(ErrorKind::IncompatibleShape));
}
res_dim.set_axis(axis, arrays.len());
let new_len = dimension::size_of_shape_checked(&res_dim)?;
// start with empty array with precomputed capacity
// append's handling of empty arrays makes sure `axis` is ok for appending
res_dim.set_axis(axis, 0);
let mut res = unsafe {
// Safety: dimension is size 0 and vec is empty
Array::from_shape_vec_unchecked(res_dim, Vec::with_capacity(new_len))
};
for array in arrays {
res.append(axis, array.clone().insert_axis(axis))?;
}
debug_assert_eq!(res.len_of(axis), arrays.len());
Ok(res)
}
/// Stack arrays along the new axis.
///
/// Uses the [`stack`][1] function, calling `ArrayView::from(&a)` on each
/// argument `a`.
///
/// [1]: fn.stack.html
///
/// ***Panics*** if the `stack` function would return an error.
///
/// ```
/// extern crate ndarray;
///
/// use ndarray::{arr2, arr3, stack, Axis};
///
/// # fn main() {
///
/// let a = arr2(&[[2., 2.],
/// [3., 3.]]);
/// assert!(
/// stack![Axis(0), a, a]
/// == arr3(&[[[2., 2.],
/// [3., 3.]],
/// [[2., 2.],
/// [3., 3.]]])
/// );
/// # }
/// ```
#[macro_export]
macro_rules! stack {
($axis:expr, $( $array:expr ),+ ) => {
$crate::stack($axis, &[ $($crate::ArrayView::from(&$array) ),* ]).unwrap()
}
}
/// Concatenate arrays along the given axis.
///
/// Uses the [`concatenate`][1] function, calling `ArrayView::from(&a)` on each
/// argument `a`.
///
/// [1]: fn.concatenate.html
///
/// ***Panics*** if the `concatenate` function would return an error.
///
/// ```
/// extern crate ndarray;
///
/// use ndarray::{arr2, concatenate, Axis};
///
/// # fn main() {
///
/// let a = arr2(&[[2., 2.],
/// [3., 3.]]);
/// assert!(
/// concatenate![Axis(0), a, a]
/// == arr2(&[[2., 2.],
/// [3., 3.],
/// [2., 2.],
/// [3., 3.]])
/// );
/// # }
/// ```
#[macro_export]
macro_rules! concatenate {
($axis:expr, $( $array:expr ),+ ) => {
$crate::concatenate($axis, &[ $($crate::ArrayView::from(&$array) ),* ]).unwrap()
}
}
/// Stack arrays along the new axis.
///
/// Uses the [`stack_new_axis`][1] function, calling `ArrayView::from(&a)` on each
/// argument `a`.
///
/// [1]: fn.stack_new_axis.html
///
/// ***Panics*** if the `stack` function would return an error.
///
/// ```
/// extern crate ndarray;
///
/// use ndarray::{arr2, arr3, stack_new_axis, Axis};
///
/// # fn main() {
///
/// let a = arr2(&[[2., 2.],
/// [3., 3.]]);
/// assert!(
/// stack_new_axis![Axis(0), a, a]
/// == arr3(&[[[2., 2.],
/// [3., 3.]],
/// [[2., 2.],
/// [3., 3.]]])
/// );
/// # }
/// ```
#[macro_export]
#[deprecated(note="Use under the name stack instead.", since="0.15.0")]
macro_rules! stack_new_axis {
($axis:expr, $( $array:expr ),+ ) => {
$crate::stack_new_axis($axis, &[ $($crate::ArrayView::from(&$array) ),* ]).unwrap()
}
}
| 27.117438 | 99 | 0.535564 |
5d1d873b87af99682a18a9df316dba7de9c455c7 | 713 | pub const USER_STACK_SIZE: usize = 0x4000;
pub const KERNEL_STACK_SIZE: usize = 0x4000;
pub const KERNEL_HEAP_SIZE: usize = 0x20_0000;
#[cfg(feature = "board_qemu")]
pub const MEMORY_END: usize = 0x80A00000;
#[cfg(feature = "board_lrv")]
pub const MEMORY_END: usize = 0x100A00000;
pub const PAGE_SIZE: usize = 0x1000;
pub const PAGE_SIZE_BITS: usize = 0xc;
pub const TRAMPOLINE: usize = usize::MAX - PAGE_SIZE + 1;
pub const TRAP_CONTEXT: usize = TRAMPOLINE - PAGE_SIZE;
pub const USER_TRAP_BUFFER: usize = TRAP_CONTEXT - PAGE_SIZE;
#[cfg(feature = "board_qemu")]
pub const CLOCK_FREQ: usize = 12500000;
#[cfg(feature = "board_lrv")]
pub const CLOCK_FREQ: usize = 10_000_000;
pub const CPU_NUM: usize = 4;
| 28.52 | 61 | 0.744741 |
feee5aa5561a8d1d8bf31c209ab50f708d47b78e | 5,780 | #[cfg(test)]
mod trivial {
use crate::types::KllFile;
#[test]
fn define() {
let result = dbg!(KllFile::from_str("myDefine => myCDefine;\n"));
assert!(result.is_ok());
}
#[test]
fn quoted() {
let result = dbg!(KllFile::from_str("\"Foo Bar\" = \"Baz Cubed\";\n"));
assert!(result.is_ok());
}
#[test]
fn array() {
let result = dbg!(KllFile::from_str("Name_Foo[0] = myKeymapFile;\n"));
assert!(result.is_ok());
}
#[test]
fn capability() {
let result = dbg!(KllFile::from_str(
"myCapability => myCFunction(arg1:1, arg2:2);\n"
));
assert!(result.is_ok());
}
#[test]
fn scancode() {
let result = dbg!(KllFile::from_str("S100 : U\"A\";\n"));
assert!(result.is_ok());
}
#[test]
fn pixelmap() {
let result = dbg!(KllFile::from_str("P[5](30:8) : S13;\n"));
assert!(result.is_ok());
}
#[test]
fn position() {
let result = dbg!(KllFile::from_str("P[30] <= x:20,rx:15;\n"));
assert!(result.is_ok());
}
#[test]
fn animation() {
let result = dbg!(KllFile::from_str(
"A[MyEyesAreBleeding] <= start, loop:3;\n"
));
assert!(result.is_ok());
}
#[test]
fn frame() {
let result = dbg!(KllFile::from_str("A[Bleeed, 5] <= P[2](255,255,255);\n"));
assert!(result.is_ok());
}
#[test]
fn result() {
let result = dbg!(KllFile::from_str("S100 : P[23](+43,+21,-40);\n"));
assert!(result.is_ok());
}
}
#[allow(non_snake_case)]
#[cfg(test)]
mod examples {
use crate::types::KllFile;
use std::fs;
#[test]
fn assignment() {
let test = fs::read_to_string("examples/assignment.kll").unwrap();
let result = dbg!(KllFile::from_str(&test));
assert!(result.is_ok());
}
#[test]
fn capabilities() {
let test = fs::read_to_string("examples/capabilitiesExample.kll").unwrap();
let result = dbg!(KllFile::from_str(&test));
assert!(result.is_ok());
}
#[test]
fn colemak() {
let test = fs::read_to_string("examples/colemak.kll").unwrap();
let result = dbg!(KllFile::from_str(&test));
assert!(result.is_ok());
}
#[test]
fn defaultmap() {
let test = fs::read_to_string("examples/defaultMapExample.kll").unwrap();
let result = dbg!(KllFile::from_str(&test));
assert!(result.is_ok());
}
#[test]
fn example() {
let test = fs::read_to_string("examples/example.kll").unwrap();
let result = dbg!(KllFile::from_str(&test));
assert!(result.is_ok());
}
#[test]
fn example2() {
let test = fs::read_to_string("examples/example2.kll").unwrap();
let result = dbg!(KllFile::from_str(&test));
assert!(result.is_ok());
}
#[test]
fn hhkbpro2() {
let test = fs::read_to_string("examples/hhkbpro2.kll").unwrap();
let result = dbg!(KllFile::from_str(&test));
assert!(result.is_ok());
}
/* TODO
#[test]
fn leds() {
let test = fs::read_to_string("examples/leds.kll").unwrap();
let result = dbg!(KllFile::from_str(&test));
assert!(result.is_ok());
}
#[test]
fn leds2() {
let test = fs::read_to_string("examples/leds2.kll").unwrap();
let result = dbg!(KllFile::from_str(&test));
assert!(result.is_ok());
}
*/
#[test]
fn mapping() {
let test = fs::read_to_string("examples/mapping.kll").unwrap();
let result = dbg!(KllFile::from_str(&test));
assert!(result.is_ok());
}
#[test]
fn md1map() {
let test = fs::read_to_string("examples/md1Map.kll").unwrap();
let result = dbg!(KllFile::from_str(&test));
assert!(result.is_ok());
}
#[test]
fn nonetest() {
let test = fs::read_to_string("examples/nonetest.kll").unwrap();
let result = dbg!(KllFile::from_str(&test));
assert!(result.is_ok());
}
#[test]
fn simple1() {
let test = fs::read_to_string("examples/simple1.kll").unwrap();
let result = dbg!(KllFile::from_str(&test));
assert!(result.is_ok());
}
/* TODO
#[test]
fn simple2() {
let test = fs::read_to_string("examples/simple2.kll").unwrap();
let result = dbg!(KllFile::from_str(&test));
assert!(result.is_ok());
}
*/
#[test]
fn simpleExample() {
let test = fs::read_to_string("examples/simpleExample.kll").unwrap();
let result = dbg!(KllFile::from_str(&test));
assert!(result.is_ok());
}
/* TODO
#[test]
fn state_scheduling() {
let test = fs::read_to_string("examples/state_scheduling.kll").unwrap();
let result = dbg!(KllFile::from_str(&test));
assert!(result.is_ok());
}
*/
/* TODO
#[test]
fn triggers() {
let test = fs::read_to_string("examples/triggers.kll").unwrap();
let result = dbg!(KllFile::from_str(&test));
assert!(result.is_ok());
}
*/
#[test]
fn utf8() {
let test = fs::read_to_string("examples/utf8.kll").unwrap();
let result = dbg!(KllFile::from_str(&test));
assert!(result.is_ok());
}
}
#[cfg(test)]
mod processing {
use crate::types::{KllFile, Statement};
#[test]
fn scancode_implied_state() {
let result = dbg!(KllFile::from_str("S100 : U\"A\";\n"));
assert!(result.is_ok());
match &result.unwrap().statements[0] {
Statement::Keymap(mapping) => {
dbg!(mapping.implied_state());
}
_ => {}
}
}
}
| 25.462555 | 85 | 0.531142 |
61cc9531652a24d814f73ccddbf0b37adbab29ed | 28,968 | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![allow(unused_mut)]
use cli::{
association_address, client_proxy::ClientProxy, AccountAddress, CryptoHash,
TransactionArgument, TransactionPayload,
};
use libra_config::config::{NodeConfig, RoleType};
use libra_crypto::{ed25519::*, test_utils::KeyPair, HashValue, SigningKey};
use libra_logger::prelude::*;
use libra_swarm::swarm::LibraNode;
use libra_swarm::{swarm::LibraSwarm, utils};
use libra_tools::tempdir::TempPath;
use libra_types::block_info::BlockInfo;
use libra_types::ledger_info::LedgerInfo;
use libra_types::waypoint::Waypoint;
use num_traits::cast::FromPrimitive;
use rust_decimal::Decimal;
use std::fs::{self, File};
use std::io::Read;
use std::str::FromStr;
use std::{thread, time};
struct TestEnvironment {
validator_swarm: LibraSwarm,
full_node_swarm: Option<LibraSwarm>,
faucet_key: (KeyPair<Ed25519PrivateKey, Ed25519PublicKey>, String),
mnemonic_file: TempPath,
}
impl TestEnvironment {
fn new(num_validators: usize) -> Self {
::libra_logger::init_for_e2e_testing();
let validator_swarm =
LibraSwarm::configure_swarm(num_validators, RoleType::Validator, None, None, None)
.unwrap();
let mnemonic_file = libra_tools::tempdir::TempPath::new();
mnemonic_file
.create_as_file()
.expect("could not create temporary mnemonic_file_path");
let mut key_file = File::open(&validator_swarm.config.faucet_key_path)
.expect("Unable to create faucet key file");
let mut serialized_key = Vec::new();
key_file
.read_to_end(&mut serialized_key)
.expect("Unable to read serialized faucet key");
let keypair = lcs::from_bytes(&serialized_key).expect("Unable to deserialize faucet key");
let keypair_path = validator_swarm
.config
.faucet_key_path
.to_str()
.expect("Unable to read faucet path")
.to_string();
Self {
validator_swarm,
full_node_swarm: None,
faucet_key: (keypair, keypair_path),
mnemonic_file,
}
}
fn setup_full_node_swarm(&mut self, num_full_nodes: usize) {
self.full_node_swarm = Some(
LibraSwarm::configure_swarm(
num_full_nodes,
RoleType::FullNode,
None,
None,
Some(String::from(
self.validator_swarm
.dir
.as_ref()
.join("0")
.to_str()
.expect("Failed to convert std::fs::Path to String"),
)),
)
.unwrap(),
);
}
fn launch_swarm(&mut self, role: RoleType) {
let mut swarm = match role {
RoleType::Validator => &mut self.validator_swarm,
RoleType::FullNode => self.full_node_swarm.as_mut().unwrap(),
};
let num_attempts = 5;
for _ in 0..num_attempts {
match swarm.launch_attempt(role, false) {
Ok(_) => {
return;
}
Err(err) => {
error!("Error launching swarm: {}", err);
}
}
}
panic!("Max out {} attempts to launch test swarm", num_attempts);
}
fn get_ac_client(&self, port: u16, waypoint: Option<Waypoint>) -> ClientProxy {
let mnemonic_file_path = self
.mnemonic_file
.path()
.to_path_buf()
.canonicalize()
.expect("Unable to get canonical path of mnemonic_file_path")
.to_str()
.unwrap()
.to_string();
ClientProxy::new(
"localhost",
port,
&self.faucet_key.1,
false,
/* faucet server */ None,
Some(mnemonic_file_path),
waypoint,
)
.unwrap()
}
fn get_validator_ac_client(
&self,
node_index: usize,
waypoint: Option<Waypoint>,
) -> ClientProxy {
let port = self.validator_swarm.get_ac_port(node_index);
self.get_ac_client(port, waypoint)
}
fn get_full_node_ac_client(
&self,
node_index: usize,
waypoint: Option<Waypoint>,
) -> ClientProxy {
match &self.full_node_swarm {
Some(swarm) => {
let port = swarm.get_ac_port(node_index);
self.get_ac_client(port, waypoint)
}
None => {
panic!("Full Node swarm is not initialized");
}
}
}
fn get_validator(&self, node_index: usize) -> Option<&LibraNode> {
self.validator_swarm.get_validator(node_index)
}
}
fn setup_swarm_and_client_proxy(
num_nodes: usize,
client_port_index: usize,
) -> (TestEnvironment, ClientProxy) {
let mut env = TestEnvironment::new(num_nodes);
env.launch_swarm(RoleType::Validator);
let ac_client = env.get_validator_ac_client(client_port_index, None);
(env, ac_client)
}
fn test_smoke_script(mut client_proxy: ClientProxy) {
client_proxy.create_next_account(false).unwrap();
client_proxy
.mint_coins(&["mintb", "0", "10"], true)
.unwrap();
assert_eq!(
Decimal::from_f64(10.0),
Decimal::from_str(&client_proxy.get_balance(&["b", "0"]).unwrap()).ok()
);
client_proxy.create_next_account(false).unwrap();
client_proxy.mint_coins(&["mintb", "1", "1"], true).unwrap();
client_proxy
.transfer_coins(&["tb", "0", "1", "3"], true)
.unwrap();
assert_eq!(
Decimal::from_f64(7.0),
Decimal::from_str(&client_proxy.get_balance(&["b", "0"]).unwrap()).ok()
);
assert_eq!(
Decimal::from_f64(4.0),
Decimal::from_str(&client_proxy.get_balance(&["b", "1"]).unwrap()).ok()
);
client_proxy.create_next_account(false).unwrap();
client_proxy
.mint_coins(&["mintb", "2", "15"], true)
.unwrap();
assert_eq!(
Decimal::from_f64(15.0),
Decimal::from_str(&client_proxy.get_balance(&["b", "2"]).unwrap()).ok()
);
}
#[test]
fn test_execute_custom_module_and_script() {
let (_swarm, mut client_proxy) = setup_swarm_and_client_proxy(1, 0);
client_proxy.create_next_account(false).unwrap();
client_proxy
.mint_coins(&["mintb", "0", "50"], true)
.unwrap();
assert_eq!(
Decimal::from_f64(50.0),
Decimal::from_str(&client_proxy.get_balance(&["b", "0"]).unwrap()).ok()
);
let recipient_address = client_proxy.create_next_account(false).unwrap().address;
client_proxy.mint_coins(&["mintb", "1", "1"], true).unwrap();
let module_path =
utils::workspace_root().join("testsuite/tests/libratest/dev_modules/module.mvir");
let unwrapped_module_path = module_path.to_str().unwrap();
let module_params = &["compile", "0", unwrapped_module_path, "module"];
let module_compiled_path = client_proxy.compile_program(module_params).unwrap();
client_proxy
.publish_module(&["publish", "0", &module_compiled_path[..]])
.unwrap();
let script_path =
utils::workspace_root().join("testsuite/tests/libratest/dev_modules/script.mvir");
let unwrapped_script_path = script_path.to_str().unwrap();
let script_params = &["execute", "0", unwrapped_script_path, "script"];
let script_compiled_path = client_proxy.compile_program(script_params).unwrap();
let formatted_recipient_address = format!("0x{}", recipient_address);
client_proxy
.execute_script(&[
"execute",
"0",
&script_compiled_path[..],
&formatted_recipient_address[..],
"10",
])
.unwrap();
assert_eq!(
Decimal::from_f64(49.999_990),
Decimal::from_str(&client_proxy.get_balance(&["b", "0"]).unwrap()).ok()
);
assert_eq!(
Decimal::from_f64(1.000_010),
Decimal::from_str(&client_proxy.get_balance(&["b", "1"]).unwrap()).ok()
);
}
#[test]
fn smoke_test_single_node() {
let (_swarm, mut client_proxy) = setup_swarm_and_client_proxy(1, 0);
test_smoke_script(client_proxy);
}
#[test]
fn smoke_test_single_node_block_metadata() {
let (_swarm, mut client_proxy) = setup_swarm_and_client_proxy(1, 0);
// just need an address to get the latest version
let address = AccountAddress::from_hex_literal("0xA550C18").unwrap();
// sleep 1s to commit some blocks
thread::sleep(time::Duration::from_secs(1));
let (_state, version) = client_proxy
.get_latest_account_state(&["q", &address.to_string()])
.unwrap();
assert!(version > 0, "BlockMetadata txn not persisted");
}
#[test]
fn smoke_test_multi_node() {
let (_swarm, mut client_proxy) = setup_swarm_and_client_proxy(4, 0);
test_smoke_script(client_proxy);
}
#[test]
fn test_concurrent_transfers_single_node() {
let (_swarm, mut client_proxy) = setup_swarm_and_client_proxy(1, 0);
client_proxy.create_next_account(false).unwrap();
client_proxy
.mint_coins(&["mintb", "0", "100"], true)
.unwrap();
client_proxy.create_next_account(false).unwrap();
for _ in 0..20 {
client_proxy
.transfer_coins(&["t", "0", "1", "1"], false)
.unwrap();
}
client_proxy
.transfer_coins(&["tb", "0", "1", "1"], true)
.unwrap();
assert_eq!(
Decimal::from_f64(79.0),
Decimal::from_str(&client_proxy.get_balance(&["b", "0"]).unwrap()).ok()
);
assert_eq!(
Decimal::from_f64(21.0),
Decimal::from_str(&client_proxy.get_balance(&["b", "1"]).unwrap()).ok()
);
}
#[test]
fn test_basic_fault_tolerance() {
// A configuration with 4 validators should tolerate single node failure.
let (mut env, mut client_proxy) = setup_swarm_and_client_proxy(4, 1);
// kill the first validator
env.validator_swarm.kill_node(0);
// run the script for the smoke test by submitting requests to the second validator
test_smoke_script(client_proxy);
}
#[test]
fn test_basic_restartability() {
let (mut env, mut client_proxy) = setup_swarm_and_client_proxy(4, 0);
client_proxy.create_next_account(false).unwrap();
client_proxy.create_next_account(false).unwrap();
client_proxy.mint_coins(&["mb", "0", "100"], true).unwrap();
client_proxy
.transfer_coins(&["tb", "0", "1", "10"], true)
.unwrap();
assert_eq!(
Decimal::from_f64(90.0),
Decimal::from_str(&client_proxy.get_balance(&["b", "0"]).unwrap()).ok()
);
assert_eq!(
Decimal::from_f64(10.0),
Decimal::from_str(&client_proxy.get_balance(&["b", "1"]).unwrap()).ok()
);
let peer_to_restart = 0;
// restart node
env.validator_swarm.kill_node(peer_to_restart);
assert!(env
.validator_swarm
.add_node(peer_to_restart, RoleType::Validator, false)
.is_ok());
assert_eq!(
Decimal::from_f64(90.0),
Decimal::from_str(&client_proxy.get_balance(&["b", "0"]).unwrap()).ok()
);
assert_eq!(
Decimal::from_f64(10.0),
Decimal::from_str(&client_proxy.get_balance(&["b", "1"]).unwrap()).ok()
);
client_proxy
.transfer_coins(&["tb", "0", "1", "10"], true)
.unwrap();
assert_eq!(
Decimal::from_f64(80.0),
Decimal::from_str(&client_proxy.get_balance(&["b", "0"]).unwrap()).ok()
);
assert_eq!(
Decimal::from_f64(20.0),
Decimal::from_str(&client_proxy.get_balance(&["b", "1"]).unwrap()).ok()
);
}
#[test]
fn test_startup_sync_state() {
let (mut env, mut client_proxy_1) = setup_swarm_and_client_proxy(4, 1);
client_proxy_1.create_next_account(false).unwrap();
client_proxy_1.create_next_account(false).unwrap();
client_proxy_1
.mint_coins(&["mb", "0", "100"], true)
.unwrap();
client_proxy_1
.transfer_coins(&["tb", "0", "1", "10"], true)
.unwrap();
assert_eq!(
Decimal::from_f64(90.0),
Decimal::from_str(&client_proxy_1.get_balance(&["b", "0"]).unwrap()).ok()
);
assert_eq!(
Decimal::from_f64(10.0),
Decimal::from_str(&client_proxy_1.get_balance(&["b", "1"]).unwrap()).ok()
);
let peer_to_stop = 0;
env.validator_swarm.kill_node(peer_to_stop);
let node_config = NodeConfig::load(
env.validator_swarm
.config
.config_files
.get(peer_to_stop)
.unwrap(),
)
.unwrap();
// TODO Remove hardcoded path to state db
let state_db_path = node_config.storage.dir().join("libradb");
// Verify that state_db_path exists and
// we are not deleting a non-existent directory
assert!(state_db_path.as_path().exists());
// Delete the state db to simulate state db lagging
// behind consensus db and forcing a state sync
// during a node startup
fs::remove_dir_all(state_db_path).unwrap();
assert!(env
.validator_swarm
.add_node(peer_to_stop, RoleType::Validator, false)
.is_ok());
// create the client for the restarted node
let accounts = client_proxy_1.copy_all_accounts();
let mut client_proxy_0 = env.get_validator_ac_client(0, None);
let sender_address = accounts[0].address;
client_proxy_0.set_accounts(accounts);
client_proxy_0.wait_for_transaction(sender_address, 1);
assert_eq!(
Decimal::from_f64(90.0),
Decimal::from_str(&client_proxy_0.get_balance(&["b", "0"]).unwrap()).ok()
);
assert_eq!(
Decimal::from_f64(10.0),
Decimal::from_str(&client_proxy_0.get_balance(&["b", "1"]).unwrap()).ok()
);
client_proxy_1
.transfer_coins(&["tb", "0", "1", "10"], true)
.unwrap();
client_proxy_0.wait_for_transaction(sender_address, 2);
assert_eq!(
Decimal::from_f64(80.0),
Decimal::from_str(&client_proxy_0.get_balance(&["b", "0"]).unwrap()).ok()
);
assert_eq!(
Decimal::from_f64(20.0),
Decimal::from_str(&client_proxy_0.get_balance(&["b", "1"]).unwrap()).ok()
);
}
#[test]
fn test_basic_state_synchronization() {
//
// - Start a swarm of 5 nodes (3 nodes forming a QC).
// - Kill one node and continue submitting transactions to the others.
// - Restart the node
// - Wait for all the nodes to catch up
// - Verify that the restarted node has synced up with the submitted transactions.
let (mut env, mut client_proxy) = setup_swarm_and_client_proxy(5, 1);
client_proxy.create_next_account(false).unwrap();
client_proxy.create_next_account(false).unwrap();
client_proxy.mint_coins(&["mb", "0", "100"], true).unwrap();
client_proxy
.transfer_coins(&["tb", "0", "1", "10"], true)
.unwrap();
assert_eq!(
Decimal::from_f64(90.0),
Decimal::from_str(&client_proxy.get_balance(&["b", "0"]).unwrap()).ok()
);
assert_eq!(
Decimal::from_f64(10.0),
Decimal::from_str(&client_proxy.get_balance(&["b", "1"]).unwrap()).ok()
);
let node_to_restart = 0;
env.validator_swarm.kill_node(node_to_restart);
// All these are executed while one node is down
assert_eq!(
Decimal::from_f64(90.0),
Decimal::from_str(&client_proxy.get_balance(&["b", "0"]).unwrap()).ok()
);
assert_eq!(
Decimal::from_f64(10.0),
Decimal::from_str(&client_proxy.get_balance(&["b", "1"]).unwrap()).ok()
);
for _ in 0..5 {
client_proxy
.transfer_coins(&["tb", "0", "1", "1"], true)
.unwrap();
}
// Reconnect and synchronize the state
assert!(env
.validator_swarm
.add_node(node_to_restart, RoleType::Validator, false)
.is_ok());
// Wait for all the nodes to catch up
assert!(env.validator_swarm.wait_for_all_nodes_to_catchup());
// Connect to the newly recovered node and verify its state
let mut client_proxy2 = env.get_validator_ac_client(node_to_restart, None);
client_proxy2.set_accounts(client_proxy.copy_all_accounts());
assert_eq!(
Decimal::from_f64(85.0),
Decimal::from_str(&client_proxy2.get_balance(&["b", "0"]).unwrap()).ok()
);
assert_eq!(
Decimal::from_f64(15.0),
Decimal::from_str(&client_proxy2.get_balance(&["b", "1"]).unwrap()).ok()
);
}
#[test]
fn test_external_transaction_signer() {
let (_swarm, mut client_proxy) = setup_swarm_and_client_proxy(1, 0);
// generate key pair
let mut seed: [u8; 32] = [0u8; 32];
seed[..4].copy_from_slice(&[1, 2, 3, 4]);
let key_pair = compat::generate_keypair(None);
let private_key = key_pair.0;
let public_key = key_pair.1;
// create transfer parameters
let sender_address = AccountAddress::from_public_key(&public_key);
let receiver_address = client_proxy
.get_account_address_from_parameter(
"1bfb3b36384dabd29e38b4a0eafd9797b75141bb007cea7943f8a4714d3d784a",
)
.unwrap();
let amount = ClientProxy::convert_to_micro_libras("1").unwrap();
let gas_unit_price = 123;
let max_gas_amount = 1000;
// mint to the sender address
client_proxy
.mint_coins(&["mintb", &format!("{}", sender_address), "10"], true)
.unwrap();
// prepare transfer transaction
let sequence_number = client_proxy
.get_sequence_number(&["sequence", &format!("{}", sender_address)])
.unwrap();
let unsigned_txn = client_proxy
.prepare_transfer_coins(
sender_address,
sequence_number,
receiver_address,
amount,
Some(gas_unit_price),
Some(max_gas_amount),
)
.unwrap();
assert_eq!(unsigned_txn.sender(), sender_address);
// sign the transaction with the private key
let signature = private_key.sign_message(&unsigned_txn.hash());
// submit the transaction
let submit_txn_result =
client_proxy.submit_signed_transaction(unsigned_txn, public_key, signature);
assert!(submit_txn_result.is_ok());
// query the transaction and check it contains the same values as requested
let txn = client_proxy
.get_committed_txn_by_acc_seq(&[
"txn_acc_seq",
&format!("{}", sender_address),
&sequence_number.to_string(),
"false",
])
.unwrap()
.unwrap()
.0;
let submitted_signed_txn = txn
.as_signed_user_txn()
.expect("Query should get user transaction.");
assert_eq!(submitted_signed_txn.sender(), sender_address);
assert_eq!(submitted_signed_txn.sequence_number(), sequence_number);
assert_eq!(submitted_signed_txn.gas_unit_price(), gas_unit_price);
assert_eq!(submitted_signed_txn.max_gas_amount(), max_gas_amount);
match submitted_signed_txn.payload() {
TransactionPayload::Script(program) => match program.args().len() {
2 => match (&program.args()[0], &program.args()[1]) {
(
TransactionArgument::Address(arg_receiver),
TransactionArgument::U64(arg_amount),
) => {
assert_eq!(arg_receiver.clone(), receiver_address);
assert_eq!(arg_amount.clone(), amount);
}
_ => panic!(
"The first argument for payment transaction must be recipient address \
and the second argument must be amount."
),
},
_ => panic!("Signed transaction payload arguments must have two arguments."),
},
_ => panic!("Signed transaction payload expected to be of struct Script"),
}
}
#[test]
fn test_full_node_basic_flow() {
// launch environment of 4 validator nodes and 2 full nodes
let mut env = TestEnvironment::new(4);
env.setup_full_node_swarm(2);
env.launch_swarm(RoleType::Validator);
env.launch_swarm(RoleType::FullNode);
// execute smoke script
test_smoke_script(env.get_validator_ac_client(0, None));
// read state from full node client
let mut validator_ac_client = env.get_validator_ac_client(1, None);
let mut full_node_client = env.get_full_node_ac_client(1, None);
let mut full_node_client_2 = env.get_full_node_ac_client(0, None);
for idx in 0..3 {
validator_ac_client.create_next_account(false).unwrap();
full_node_client.create_next_account(false).unwrap();
full_node_client_2.create_next_account(false).unwrap();
assert_eq!(
validator_ac_client
.get_balance(&["b", &idx.to_string()])
.unwrap(),
full_node_client
.get_balance(&["b", &idx.to_string()])
.unwrap(),
);
}
let sender_account = &format!(
"{}",
validator_ac_client.faucet_account.clone().unwrap().address
);
// mint from full node and check both validator and full node have correct balance
let account3 = validator_ac_client
.create_next_account(false)
.unwrap()
.address;
full_node_client.create_next_account(false).unwrap();
full_node_client_2.create_next_account(false).unwrap();
let mint_result = full_node_client.mint_coins(&["mintb", "3", "10"], true);
assert!(mint_result.is_ok());
assert_eq!(
Decimal::from_f64(10.0),
Decimal::from_str(&full_node_client.get_balance(&["b", "3"]).unwrap()).ok()
);
let sequence = full_node_client
.get_sequence_number(&["sequence", sender_account, "true"])
.unwrap();
validator_ac_client.wait_for_transaction(
validator_ac_client.faucet_account.clone().unwrap().address,
sequence,
);
assert_eq!(
Decimal::from_f64(10.0),
Decimal::from_str(&validator_ac_client.get_balance(&["b", "3"]).unwrap()).ok()
);
// reset sequence number for sender account
validator_ac_client
.get_sequence_number(&["sequence", sender_account, "true"])
.unwrap();
full_node_client
.get_sequence_number(&["sequence", sender_account, "true"])
.unwrap();
// mint from validator and check both nodes have correct balance
validator_ac_client.create_next_account(false).unwrap();
full_node_client.create_next_account(false).unwrap();
full_node_client_2.create_next_account(false).unwrap();
validator_ac_client
.mint_coins(&["mintb", "4", "10"], true)
.unwrap();
let sequence = validator_ac_client
.get_sequence_number(&["sequence", sender_account, "true"])
.unwrap();
full_node_client.wait_for_transaction(
validator_ac_client.faucet_account.clone().unwrap().address,
sequence,
);
assert_eq!(
Decimal::from_f64(10.0),
Decimal::from_str(&validator_ac_client.get_balance(&["b", "4"]).unwrap()).ok()
);
assert_eq!(
Decimal::from_f64(10.0),
Decimal::from_str(&full_node_client.get_balance(&["b", "4"]).unwrap()).ok()
);
// minting again on validator doesn't cause error since client sequence has been updated
validator_ac_client
.mint_coins(&["mintb", "4", "10"], true)
.unwrap();
// test transferring balance from 0 to 1 through full node proxy
full_node_client
.transfer_coins(&["tb", "3", "4", "10"], true)
.unwrap();
assert_eq!(
Decimal::from_f64(0.0),
Decimal::from_str(&full_node_client.get_balance(&["b", "3"]).unwrap()).ok()
);
assert_eq!(
Decimal::from_f64(30.0),
Decimal::from_str(&validator_ac_client.get_balance(&["b", "4"]).unwrap()).ok()
);
let sequence = validator_ac_client
.get_sequence_number(&["sequence", &format!("{}", account3), "true"])
.unwrap();
full_node_client_2.wait_for_transaction(account3, sequence);
assert_eq!(
Decimal::from_f64(0.0),
Decimal::from_str(&full_node_client_2.get_balance(&["b", "3"]).unwrap()).ok()
);
assert_eq!(
Decimal::from_f64(30.0),
Decimal::from_str(&full_node_client_2.get_balance(&["b", "4"]).unwrap()).ok()
);
}
#[test]
fn test_e2e_reconfiguration() {
let (mut env, mut client_proxy_1) = setup_swarm_and_client_proxy(3, 1);
// the client connected to the removed validator
let mut client_proxy_0 = env.get_validator_ac_client(0, None);
client_proxy_1.create_next_account(false).unwrap();
client_proxy_0.set_accounts(client_proxy_1.copy_all_accounts());
client_proxy_1
.mint_coins(&["mintb", "0", "10"], true)
.unwrap();
assert_eq!(
Decimal::from_f64(10.0),
Decimal::from_str(&client_proxy_1.get_balance(&["b", "0"]).unwrap()).ok()
);
// wait for the mint txn in node 0
client_proxy_0.wait_for_transaction(association_address(), 1);
assert_eq!(
Decimal::from_f64(10.0),
Decimal::from_str(&client_proxy_0.get_balance(&["b", "0"]).unwrap()).ok()
);
let peer_id = env
.get_validator(0)
.unwrap()
.validator_peer_id()
.unwrap()
.to_string();
client_proxy_1
.remove_validator(&["remove_validator", &peer_id], true)
.unwrap();
// mint another 10 coins after remove node 0
client_proxy_1
.mint_coins(&["mintb", "0", "10"], true)
.unwrap();
assert_eq!(
Decimal::from_f64(20.0),
Decimal::from_str(&client_proxy_1.get_balance(&["b", "0"]).unwrap()).ok()
);
// client connected to removed validator can not see the update
assert_eq!(
Decimal::from_f64(10.0),
Decimal::from_str(&client_proxy_0.get_balance(&["b", "0"]).unwrap()).ok()
);
// Add the node back
client_proxy_1
.add_validator(&["add_validator", &peer_id], true)
.unwrap();
// Wait for it catches up, mint1 + remove + mint2 + add => seq == 4
client_proxy_0.wait_for_transaction(association_address(), 4);
assert_eq!(
Decimal::from_f64(20.0),
Decimal::from_str(&client_proxy_0.get_balance(&["b", "0"]).unwrap()).ok()
);
}
#[test]
fn test_client_waypoints() {
let (mut env, mut client_proxy) = setup_swarm_and_client_proxy(3, 1);
// Make sure some txns are committed
client_proxy.create_next_account(false).unwrap();
client_proxy
.mint_coins(&["mintb", "0", "10"], true)
.unwrap();
// Create the waypoint for the initial epoch
let genesis_li = client_proxy
.latest_epoch_change_li()
.expect("Failed to retrieve genesis LedgerInfo");
assert_eq!(genesis_li.ledger_info().epoch(), 0);
let genesis_waypoint = Waypoint::new(genesis_li.ledger_info())
.expect("Failed to generate waypoint from genesis LI");
// Start another client with the genesis waypoint and make sure it successfully connects
let mut client_with_waypoint = env.get_validator_ac_client(0, Some(genesis_waypoint.clone()));
client_with_waypoint.test_validator_connection().unwrap();
assert_eq!(
client_with_waypoint.latest_epoch_change_li().unwrap(),
genesis_li
);
// Start next epoch
let peer_id = env
.get_validator(0)
.unwrap()
.validator_peer_id()
.unwrap()
.to_string();
client_proxy
.remove_validator(&["remove_validator", &peer_id], true)
.unwrap();
client_proxy
.mint_coins(&["mintb", "0", "10"], true)
.unwrap();
assert_eq!(
Decimal::from_f64(20.0),
Decimal::from_str(&client_proxy.get_balance(&["b", "0"]).unwrap()).ok()
);
let epoch_1_li = client_proxy
.latest_epoch_change_li()
.expect("Failed to retrieve end of epoch 1 LedgerInfo");
assert_eq!(epoch_1_li.ledger_info().epoch(), 1);
let epoch_1_waypoint = Waypoint::new(epoch_1_li.ledger_info())
.expect("Failed to generate waypoint from end of epoch 1");
// Start a client with the waypoint for end of epoch 1 and make sure it successfully connects
client_with_waypoint = env.get_validator_ac_client(1, Some(epoch_1_waypoint.clone()));
client_with_waypoint.test_validator_connection().unwrap();
assert_eq!(
client_with_waypoint.latest_epoch_change_li().unwrap(),
epoch_1_li
);
// Verify that a client with the wrong waypoint is not going to be able to connect to the chain.
let bad_li = LedgerInfo::new(BlockInfo::genesis(), HashValue::zero());
let bad_waypoint = Waypoint::new(&bad_li).unwrap();
let mut client_with_bad_waypoint = env.get_validator_ac_client(1, Some(bad_waypoint));
assert!(client_with_bad_waypoint
.test_validator_connection()
.is_err());
}
| 34.985507 | 100 | 0.619028 |
bb6d66a3266c003fb985a63840d9e8c6339a6888 | 4,073 | // Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use std::convert::{From, TryFrom};
use tss_esapi::{
handles::{ObjectHandle, PcrHandle},
tss2_esys::{
ESYS_TR, ESYS_TR_PCR0, ESYS_TR_PCR1, ESYS_TR_PCR10, ESYS_TR_PCR11, ESYS_TR_PCR12,
ESYS_TR_PCR13, ESYS_TR_PCR14, ESYS_TR_PCR15, ESYS_TR_PCR16, ESYS_TR_PCR17, ESYS_TR_PCR18,
ESYS_TR_PCR19, ESYS_TR_PCR2, ESYS_TR_PCR20, ESYS_TR_PCR21, ESYS_TR_PCR22, ESYS_TR_PCR23,
ESYS_TR_PCR24, ESYS_TR_PCR25, ESYS_TR_PCR26, ESYS_TR_PCR27, ESYS_TR_PCR28, ESYS_TR_PCR29,
ESYS_TR_PCR3, ESYS_TR_PCR30, ESYS_TR_PCR31, ESYS_TR_PCR4, ESYS_TR_PCR5, ESYS_TR_PCR6,
ESYS_TR_PCR7, ESYS_TR_PCR8, ESYS_TR_PCR9,
},
};
#[test]
fn test_conversion_of_invalid_handle() {
let invalid_value: ESYS_TR = 0xFFFFFFFF;
let invalid_object_handle: ObjectHandle = ObjectHandle::from(invalid_value);
let _ = PcrHandle::try_from(invalid_value).unwrap_err();
let _ = PcrHandle::try_from(invalid_object_handle).unwrap_err();
}
macro_rules! test_valid_conversions {
($esys_tr_handle:ident, PcrHandle::$pcr_handle:ident) => {
assert_eq!(
ObjectHandle::from(PcrHandle::$pcr_handle),
ObjectHandle::from($esys_tr_handle),
"ObjectHandle conversion failed for PcrHandle::{}",
std::stringify!($pcr_handle)
);
assert_eq!(
$esys_tr_handle,
ESYS_TR::from(PcrHandle::$pcr_handle),
"Esys TR handle conversion failed for PcrHandle::{}",
std::stringify!($pcr_handle),
);
assert_eq!(
PcrHandle::$pcr_handle,
PcrHandle::try_from($esys_tr_handle).expect(&format!(
"Failed to convert {} to PcrHandle",
std::stringify!($esys_tr_handle)
)),
"{} did not convert to the expected value PcrHandle::{}",
std::stringify!($esys_tr_handle),
std::stringify!($pcr_handle),
);
};
}
#[test]
fn test_conversion_of_valid_handle() {
// Check the valid values
test_valid_conversions!(ESYS_TR_PCR0, PcrHandle::Pcr0);
test_valid_conversions!(ESYS_TR_PCR1, PcrHandle::Pcr1);
test_valid_conversions!(ESYS_TR_PCR2, PcrHandle::Pcr2);
test_valid_conversions!(ESYS_TR_PCR3, PcrHandle::Pcr3);
test_valid_conversions!(ESYS_TR_PCR4, PcrHandle::Pcr4);
test_valid_conversions!(ESYS_TR_PCR5, PcrHandle::Pcr5);
test_valid_conversions!(ESYS_TR_PCR6, PcrHandle::Pcr6);
test_valid_conversions!(ESYS_TR_PCR7, PcrHandle::Pcr7);
test_valid_conversions!(ESYS_TR_PCR8, PcrHandle::Pcr8);
test_valid_conversions!(ESYS_TR_PCR9, PcrHandle::Pcr9);
test_valid_conversions!(ESYS_TR_PCR10, PcrHandle::Pcr10);
test_valid_conversions!(ESYS_TR_PCR11, PcrHandle::Pcr11);
test_valid_conversions!(ESYS_TR_PCR12, PcrHandle::Pcr12);
test_valid_conversions!(ESYS_TR_PCR13, PcrHandle::Pcr13);
test_valid_conversions!(ESYS_TR_PCR14, PcrHandle::Pcr14);
test_valid_conversions!(ESYS_TR_PCR15, PcrHandle::Pcr15);
test_valid_conversions!(ESYS_TR_PCR16, PcrHandle::Pcr16);
test_valid_conversions!(ESYS_TR_PCR17, PcrHandle::Pcr17);
test_valid_conversions!(ESYS_TR_PCR18, PcrHandle::Pcr18);
test_valid_conversions!(ESYS_TR_PCR19, PcrHandle::Pcr19);
test_valid_conversions!(ESYS_TR_PCR20, PcrHandle::Pcr20);
test_valid_conversions!(ESYS_TR_PCR21, PcrHandle::Pcr21);
test_valid_conversions!(ESYS_TR_PCR22, PcrHandle::Pcr22);
test_valid_conversions!(ESYS_TR_PCR23, PcrHandle::Pcr23);
test_valid_conversions!(ESYS_TR_PCR24, PcrHandle::Pcr24);
test_valid_conversions!(ESYS_TR_PCR25, PcrHandle::Pcr25);
test_valid_conversions!(ESYS_TR_PCR26, PcrHandle::Pcr26);
test_valid_conversions!(ESYS_TR_PCR27, PcrHandle::Pcr27);
test_valid_conversions!(ESYS_TR_PCR28, PcrHandle::Pcr28);
test_valid_conversions!(ESYS_TR_PCR29, PcrHandle::Pcr29);
test_valid_conversions!(ESYS_TR_PCR30, PcrHandle::Pcr30);
test_valid_conversions!(ESYS_TR_PCR31, PcrHandle::Pcr31);
}
| 45.764045 | 97 | 0.720108 |
b9f6ebebb8fbacfa81b245b91970f510d4a68af9 | 5,631 | use crate::cli::cli::{pre_exec, Colors, Palette};
use clap::{App, Arg, ArgMatches};
use fancy_regex::Regex;
pub struct Cmd {}
impl Cmd {
pub fn new() -> App<'static> {
App::new("du")
.args(&[
Arg::new("FILE").about("[FILE]"),
Arg::new("null").long("null").short('0').about("end each output line with NUL, not newline"),
Arg::new("all").long("all").short('a').about("write counts for all files, not just directories"),
Arg::new("apparent-size").long("apparent-size").about("print apparent sizes, rather than disk usage"),
Arg::new("block-size").long("block-size").short('B').takes_value(true).about("scale sizes by SIZE before printing them"),
Arg::new("bytes").long("bytes").short('b').about("equivalent to '--apparent-size --block-size=1'"),
Arg::new("total").long("total").short('c').about("produce a grand total"),
Arg::new("dereference-args").long("dereference-args").short('D').short('H').about("dereference only symlinks that are listed on the command line"),
Arg::new("max-depth").long("max-depth").short('d').takes_value(true).about("print the total for a directory"),
Arg::new("files0-from").long("files0-from").short('F').takes_value(true).about("summarize disk usage of the NUL-terminated file names specified in file F; if F is -, then read names from standard input"),
Arg::new("human-readable").long("human-readable").short('h').about("print sizes in human readable format (e.g., 1K 234M 2G)"),
Arg::new("inodes").long("inodes").about("list inode usage information instead of block usage"),
Arg::new("k").short('k').about("like --block-size=1K"),
Arg::new("dereference").long("dereference").short('L').about("dereference all symbolic links"),
Arg::new("count-links").long("count-links").short('l').about("count sizes many times if hard linked"),
Arg::new("m").short('m').about("like --block-size=1M"),
Arg::new("no-dereference").long("no-dereference").short('P').about("don't follow any symbolic links (this is the default)"),
Arg::new("separate-dirs").long("separate-dirs").short('S').about("for directories do not include size of subdirectories"),
Arg::new("si").long("si").about("like -h, but use powers of 1000 not 1024"),
Arg::new("summarize").long("summarize").short('s').about("display only a total for each argument"),
Arg::new("threshold").long("threshold").short('t').takes_value(true).about("exclude entries smaller than SIZE if positive, or entries greater than SIZE if negative"),
Arg::new("time").long("time").about("show time of the last modification of any file in the directory, or any of its subdirectories"),
Arg::new("time-style").long("time-style").takes_value(true).about("show times using STYLE, which can be: full-iso, long-iso, iso, or +FORMAT; FORMAT is interpreted like in 'date'"),
Arg::new("exclude-from").long("exclude-from").short('X').takes_value(true).about("exclude files that match any pattern in FILE"),
Arg::new("exclude").long("exclude").takes_value(true).about("exclude files that match PATTERN"),
Arg::new("one-file-system").long("one-file-system").short('x').takes_value(true).about("skip directories on different file systems"),
Arg::new("help").long("help").about("display this help and exit"),
Arg::new("version").long("version").about("output version information and exit"),
])
.about("du")
}
pub fn parse(_app: &ArgMatches) {
// print!("{:?}", app);
pre_exec(Cmd::palette());
}
fn palette() -> Vec<Palette<'static>> {
vec![
// Path
Palette {
regexp: Regex::new(r#"\s+[\./]+([\w\s\-\_\.]+)(/.*)?$"#).unwrap(),
colors: vec![&Colors::Default, &Colors::BBlue, &Colors::Blue],
},
// Total
Palette {
regexp: Regex::new(r#"(.*)\s+(total)$"#).unwrap(),
colors: vec![&Colors::BYellow],
},
// Size 'T'
Palette {
regexp: Regex::new(r#"^ ?\d*[.,]?\dTi?"#).unwrap(),
colors: vec![&Colors::BRed],
},
// Size 'G'
Palette {
regexp: Regex::new(r#"^ ?\d*[.,]?\dGi?"#).unwrap(),
colors: vec![&Colors::Red],
},
Palette {
regexp: Regex::new(r#"^\d{7,9}"#).unwrap(),
colors: vec![&Colors::Red],
},
// Size 'M'
Palette {
regexp: Regex::new(r#"^ ?\d*[.,]?\dMi?"#).unwrap(),
colors: vec![&Colors::Yellow],
},
Palette {
regexp: Regex::new(r#"^\d{4,6}"#).unwrap(),
colors: vec![&Colors::Yellow],
},
// Size 'K'
Palette {
regexp: Regex::new(r#"^ ?\d*[.,]?\dKi?"#).unwrap(),
colors: vec![&Colors::Green],
},
Palette {
regexp: Regex::new(r#"^\d{1,3}"#).unwrap(),
colors: vec![&Colors::Green],
},
// Cannot read error
Palette {
regexp: Regex::new(r#"^du.*"#).unwrap(),
colors: vec![&Colors::Red],
},
]
}
}
| 56.31 | 220 | 0.524241 |
1878dd4618730d93d762fc941f926f506a9f023d | 570 | // Jump back and forth between the OS main thread and a new scheduler.
// The OS main scheduler should continue to be available and not terminate
// while it is not in use.
fn main() {
run(100);
}
fn run(i: int) {
log(debug, i);
if i == 0 {
return;
}
do task::task().sched_mode(task::PlatformThread).unlinked().spawn {
task::yield();
do task::task().sched_mode(task::SingleThreaded).unlinked().spawn {
task::yield();
run(i - 1);
task::yield();
}
task::yield();
}
}
| 21.111111 | 75 | 0.550877 |
d6e3296e397748d1f30d4bbf49025165c0ca87a3 | 1,722 | use libc::*;
pub const ERR_TXT_MALLOCED: c_int = 0x01;
pub const ERR_TXT_STRING: c_int = 0x02;
pub const ERR_LIB_PEM: c_int = 9;
pub const ERR_LIB_ASN1: c_int = 13;
const_fn! {
pub const fn ERR_PACK(l: c_int, f: c_int, r: c_int) -> c_ulong {
((l as c_ulong & 0x0FF) << 24) |
((f as c_ulong & 0xFFF) << 12) |
(r as c_ulong & 0xFFF)
}
pub const fn ERR_GET_LIB(l: c_ulong) -> c_int {
((l >> 24) & 0x0FF) as c_int
}
pub const fn ERR_GET_FUNC(l: c_ulong) -> c_int {
((l >> 12) & 0xFFF) as c_int
}
pub const fn ERR_GET_REASON(l: c_ulong) -> c_int {
(l & 0xFFF) as c_int
}
}
#[repr(C)]
pub struct ERR_STRING_DATA {
pub error: c_ulong,
pub string: *const c_char,
}
extern "C" {
pub fn ERR_put_error(lib: c_int, func: c_int, reason: c_int, file: *const c_char, line: c_int);
pub fn ERR_set_error_data(data: *mut c_char, flags: c_int);
pub fn ERR_get_error() -> c_ulong;
pub fn ERR_get_error_line_data(
file: *mut *const c_char,
line: *mut c_int,
data: *mut *const c_char,
flags: *mut c_int,
) -> c_ulong;
pub fn ERR_peek_last_error() -> c_ulong;
pub fn ERR_clear_error();
pub fn ERR_lib_error_string(err: c_ulong) -> *const c_char;
pub fn ERR_func_error_string(err: c_ulong) -> *const c_char;
pub fn ERR_reason_error_string(err: c_ulong) -> *const c_char;
#[cfg(ossl110)]
pub fn ERR_load_strings(lib: c_int, str: *mut ERR_STRING_DATA) -> c_int;
#[cfg(not(ossl110))]
pub fn ERR_load_strings(lib: c_int, str: *mut ERR_STRING_DATA);
#[cfg(not(ossl110))]
pub fn ERR_load_crypto_strings();
pub fn ERR_get_next_error_library() -> c_int;
}
| 28.7 | 99 | 0.626016 |
39377b9d83d3f1035f634609b46620023dfa4295 | 489 | gui_main_project.pkg1.DepositWindow$10
gui_main_project.pkg1.DepositWindow$7
gui_main_project.pkg1.DepositWindow$6
gui_main_project.pkg1.DepositWindow$5
gui_main_project.pkg1.DepositWindow$4
gui_main_project.pkg1.DepositWindow$3
gui_main_project.pkg1.DepositWindow$2
gui_main_project.pkg1.DepositWindow$1
gui_main_project.pkg1.DepositWindow$11
gui_main_project.pkg1.DepositWindow$9
gui_main_project.pkg1.DepositWindow$8
gui_main_project.pkg1.MyCalendar
gui_main_project.pkg1.DepositWindow
| 34.928571 | 38 | 0.897751 |
28f5dcf598fca62124d8b01a97a8afa703572a68 | 800 | #[derive(Serialize, Deserialize)]
pub struct ZipResult {
#[serde(rename="post code")]
post_code: String,
country: String,
#[serde(rename="country abbreviation")]
country_abbr: String,
places: Vec<Place>,
}
#[derive(Serialize, Deserialize)]
pub struct Place {
#[serde(rename="place name")]
place_name: String,
latitude: String,
longitude: String,
state: String,
#[serde(rename="state abbreviation")]
state_abbr: String,
}
impl ::std::fmt::Display for ZipResult {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
match self.places.iter().nth(0) {
Some(place) => write!(f, "{}, {} {}", place.place_name, place.state, self.post_code),
None => f.write_str("No matches found"),
}
}
}
| 26.666667 | 97 | 0.6075 |
0e784ecac53323e7128132221a46ed81e52fc3ce | 3,076 | extern crate cc;
use std::env;
use std::path::{ Path, PathBuf };
use std::process::Command;
macro_rules! binary(() => (if cfg!(target_pointer_width = "32") { "32" } else { "64" }));
macro_rules! feature(($name:expr) => (env::var(concat!("CARGO_FEATURE_", $name)).is_ok()));
macro_rules! switch(($condition:expr) => (if $condition { "YES" } else { "NO" }));
macro_rules! variable(($name:expr) => (env::var($name).unwrap()));
fn main() {
for v in env::vars() {
println!("{:?}", v);
}
let kind = if feature!("STATIC") {
"static"
} else {
"dylib"
};
if !feature!("SYSTEM") {
let output = PathBuf::from(variable!("OUT_DIR").replace(r"\", "/"));
if !output.join("libopenblas.a").exists() {
build(&output);
}
println!(
"cargo:rustc-link-search={}",
output.join("opt/OpenBLAS/lib").display(),
);
}
println!("cargo:rustc-link-lib={}=openblas", kind);
// println!("cargo:rustc-link-lib=dylib=gfortran");
}
fn build(output: &Path) {
let cblas = feature!("CBLAS");
let lapacke = feature!("LAPACKE");
let source = PathBuf::from("source");
let target = variable!("TARGET");
let host = variable!("HOST");
let cross_args = if target != host {
let cc = cc::Build::new().get_compiler();
let toolchain_bin_dir = cc.path().parent().expect("toolchain is a dir");
let cc_exe = cc.path().file_name().expect("cc was not a file")
.to_string_lossy();
let splitted_exe = cc_exe.split("-").collect::<Vec<_>>();
let prefix = splitted_exe[0..splitted_exe.len()-1].join("-");
let fc = toolchain_bin_dir.join(format!("{}-gfortran", prefix));
let ar = toolchain_bin_dir.join(format!("{}-ar", prefix));
vec!(
format!("CC={}", cc.path().to_string_lossy()),
// format!("FC={}", fc.to_string_lossy()),
format!("AR={}", ar.to_string_lossy()),
format!("NOFORTRAN=1"),
"HOSTCC=cc".to_string(),
"TARGET=ARMV6".to_string(),
)
} else {
vec!()
};
env::remove_var("TARGET");
run(
Command::new("make")
.args(&["libs", "netlib", "shared"])
.arg(format!("BINARY={}", variable!("CARGO_CFG_TARGET_POINTER_WIDTH")))
.arg(format!("{}_CBLAS=1", switch!(cblas)))
.arg(format!("{}_LAPACKE=1", switch!(lapacke)))
// .arg(format!("-j{}", variable!("NUM_JOBS")))
.args(cross_args)
.current_dir(&source),
);
run(
Command::new("make")
.arg("install")
.arg(format!("DESTDIR={}", output.display()))
.current_dir(&source),
);
}
fn run(command: &mut Command) {
println!("Running: `{:?}`", command);
match command.status() {
Ok(status) => if !status.success() {
panic!("Failed: `{:?}` ({})", command, status);
},
Err(error) => {
panic!("Failed: `{:?}` ({})", command, error);
}
}
}
| 33.802198 | 91 | 0.519506 |
edcfac979fb3ef2c11a2e906385b1b1ce52c175f | 399 | use once_cell::sync::Lazy;
use wasmer::{imports, Function, ImportObject, Instance};
pub static IMPORT_OBJECTS: Lazy<ImportObject> = Lazy::new(|| imports! {});
pub fn seach_function<'a>(
instance: &'a Instance,
name: &'a str,
) -> Option<(&'a String, &'a Function)> {
instance
.exports
.iter()
.functions()
.filter(|(x, _)| x == &name)
.nth(0)
}
| 23.470588 | 74 | 0.573935 |
acbbdcfc7a7aee217f03266bf4bc91a44dacdd77 | 12,330 | // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
/// Service config.
///
///
/// Service configuration allows for customization of endpoints, region, credentials providers,
/// and retry configuration. Generally, it is constructed automatically for you from a shared
/// configuration loaded by the `aws-config` crate. For example:
///
/// ```ignore
/// // Load a shared config from the environment
/// let shared_config = aws_config::from_env().load().await;
/// // The client constructor automatically converts the shared config into the service config
/// let client = Client::new(&shared_config);
/// ```
///
/// The service config can also be constructed manually using its builder.
///
pub struct Config {
pub(crate) make_token: crate::idempotency_token::IdempotencyTokenProvider,
app_name: Option<aws_types::app_name::AppName>,
pub(crate) timeout_config: Option<aws_smithy_types::timeout::Config>,
pub(crate) sleep_impl: Option<std::sync::Arc<dyn aws_smithy_async::rt::sleep::AsyncSleep>>,
pub(crate) retry_config: Option<aws_smithy_types::retry::RetryConfig>,
pub(crate) endpoint_resolver: ::std::sync::Arc<dyn aws_endpoint::ResolveAwsEndpoint>,
pub(crate) region: Option<aws_types::region::Region>,
pub(crate) credentials_provider: aws_types::credentials::SharedCredentialsProvider,
}
impl std::fmt::Debug for Config {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut config = f.debug_struct("Config");
config.finish()
}
}
impl Config {
/// Constructs a config builder.
pub fn builder() -> Builder {
Builder::default()
}
/// Returns the name of the app that is using the client, if it was provided.
///
/// This _optional_ name is used to identify the application in the user agent that
/// gets sent along with requests.
pub fn app_name(&self) -> Option<&aws_types::app_name::AppName> {
self.app_name.as_ref()
}
/// Creates a new [service config](crate::Config) from a [shared `config`](aws_types::sdk_config::SdkConfig).
pub fn new(config: &aws_types::sdk_config::SdkConfig) -> Self {
Builder::from(config).build()
}
/// The signature version 4 service signing name to use in the credential scope when signing requests.
///
/// The signing service may be overridden by the `Endpoint`, or by specifying a custom
/// [`SigningService`](aws_types::SigningService) during operation construction
pub fn signing_service(&self) -> &'static str {
"fis"
}
}
/// Builder for creating a `Config`.
#[derive(Default)]
pub struct Builder {
make_token: Option<crate::idempotency_token::IdempotencyTokenProvider>,
app_name: Option<aws_types::app_name::AppName>,
timeout_config: Option<aws_smithy_types::timeout::Config>,
sleep_impl: Option<std::sync::Arc<dyn aws_smithy_async::rt::sleep::AsyncSleep>>,
retry_config: Option<aws_smithy_types::retry::RetryConfig>,
endpoint_resolver: Option<::std::sync::Arc<dyn aws_endpoint::ResolveAwsEndpoint>>,
region: Option<aws_types::region::Region>,
credentials_provider: Option<aws_types::credentials::SharedCredentialsProvider>,
}
impl Builder {
/// Constructs a config builder.
pub fn new() -> Self {
Self::default()
}
/// Sets the idempotency token provider to use for service calls that require tokens.
pub fn make_token(
mut self,
make_token: impl Into<crate::idempotency_token::IdempotencyTokenProvider>,
) -> Self {
self.make_token = Some(make_token.into());
self
}
/// Sets the name of the app that is using the client.
///
/// This _optional_ name is used to identify the application in the user agent that
/// gets sent along with requests.
pub fn app_name(mut self, app_name: aws_types::app_name::AppName) -> Self {
self.set_app_name(Some(app_name));
self
}
/// Sets the name of the app that is using the client.
///
/// This _optional_ name is used to identify the application in the user agent that
/// gets sent along with requests.
pub fn set_app_name(&mut self, app_name: Option<aws_types::app_name::AppName>) -> &mut Self {
self.app_name = app_name;
self
}
/// Set the timeout_config for the builder
///
/// # Examples
///
/// ```no_run
/// # use std::time::Duration;
/// use aws_sdk_fis::config::Config;
/// use aws_smithy_types::{timeout, tristate::TriState};
///
/// let api_timeouts = timeout::Api::new()
/// .with_call_attempt_timeout(TriState::Set(Duration::from_secs(1)));
/// let timeout_config = timeout::Config::new()
/// .with_api_timeouts(api_timeouts);
/// let config = Config::builder().timeout_config(timeout_config).build();
/// ```
pub fn timeout_config(mut self, timeout_config: aws_smithy_types::timeout::Config) -> Self {
self.set_timeout_config(Some(timeout_config));
self
}
/// Set the timeout_config for the builder
///
/// # Examples
///
/// ```no_run
/// # use std::time::Duration;
/// use aws_sdk_fis::config::{Builder, Config};
/// use aws_smithy_types::{timeout, tristate::TriState};
///
/// fn set_request_timeout(builder: &mut Builder) {
/// let api_timeouts = timeout::Api::new()
/// .with_call_attempt_timeout(TriState::Set(Duration::from_secs(1)));
/// let timeout_config = timeout::Config::new()
/// .with_api_timeouts(api_timeouts);
/// builder.set_timeout_config(Some(timeout_config));
/// }
///
/// let mut builder = Config::builder();
/// set_request_timeout(&mut builder);
/// let config = builder.build();
/// ```
pub fn set_timeout_config(
&mut self,
timeout_config: Option<aws_smithy_types::timeout::Config>,
) -> &mut Self {
self.timeout_config = timeout_config;
self
}
/// Set the sleep_impl for the builder
///
/// # Examples
///
/// ```no_run
/// use aws_sdk_fis::config::Config;
/// use aws_smithy_async::rt::sleep::AsyncSleep;
/// use aws_smithy_async::rt::sleep::Sleep;
///
/// #[derive(Debug)]
/// pub struct ForeverSleep;
///
/// impl AsyncSleep for ForeverSleep {
/// fn sleep(&self, duration: std::time::Duration) -> Sleep {
/// Sleep::new(std::future::pending())
/// }
/// }
///
/// let sleep_impl = std::sync::Arc::new(ForeverSleep);
/// let config = Config::builder().sleep_impl(sleep_impl).build();
/// ```
pub fn sleep_impl(
mut self,
sleep_impl: std::sync::Arc<dyn aws_smithy_async::rt::sleep::AsyncSleep>,
) -> Self {
self.set_sleep_impl(Some(sleep_impl));
self
}
/// Set the sleep_impl for the builder
///
/// # Examples
///
/// ```no_run
/// use aws_sdk_fis::config::{Builder, Config};
/// use aws_smithy_async::rt::sleep::AsyncSleep;
/// use aws_smithy_async::rt::sleep::Sleep;
///
/// #[derive(Debug)]
/// pub struct ForeverSleep;
///
/// impl AsyncSleep for ForeverSleep {
/// fn sleep(&self, duration: std::time::Duration) -> Sleep {
/// Sleep::new(std::future::pending())
/// }
/// }
///
/// fn set_never_ending_sleep_impl(builder: &mut Builder) {
/// let sleep_impl = std::sync::Arc::new(ForeverSleep);
/// builder.set_sleep_impl(Some(sleep_impl));
/// }
///
/// let mut builder = Config::builder();
/// set_never_ending_sleep_impl(&mut builder);
/// let config = builder.build();
/// ```
pub fn set_sleep_impl(
&mut self,
sleep_impl: Option<std::sync::Arc<dyn aws_smithy_async::rt::sleep::AsyncSleep>>,
) -> &mut Self {
self.sleep_impl = sleep_impl;
self
}
/// Set the retry_config for the builder
///
/// # Examples
/// ```no_run
/// use aws_sdk_fis::config::Config;
/// use aws_smithy_types::retry::RetryConfig;
///
/// let retry_config = RetryConfig::new().with_max_attempts(5);
/// let config = Config::builder().retry_config(retry_config).build();
/// ```
pub fn retry_config(mut self, retry_config: aws_smithy_types::retry::RetryConfig) -> Self {
self.set_retry_config(Some(retry_config));
self
}
/// Set the retry_config for the builder
///
/// # Examples
/// ```no_run
/// use aws_sdk_fis::config::{Builder, Config};
/// use aws_smithy_types::retry::RetryConfig;
///
/// fn disable_retries(builder: &mut Builder) {
/// let retry_config = RetryConfig::new().with_max_attempts(1);
/// builder.set_retry_config(Some(retry_config));
/// }
///
/// let mut builder = Config::builder();
/// disable_retries(&mut builder);
/// let config = builder.build();
/// ```
pub fn set_retry_config(
&mut self,
retry_config: Option<aws_smithy_types::retry::RetryConfig>,
) -> &mut Self {
self.retry_config = retry_config;
self
}
// TODO(docs): include an example of using a static endpoint
/// Sets the endpoint resolver to use when making requests.
pub fn endpoint_resolver(
mut self,
endpoint_resolver: impl aws_endpoint::ResolveAwsEndpoint + 'static,
) -> Self {
self.endpoint_resolver = Some(::std::sync::Arc::new(endpoint_resolver));
self
}
/// Sets the AWS region to use when making requests.
///
/// # Examples
/// ```no_run
/// use aws_types::region::Region;
/// use aws_sdk_fis::config::{Builder, Config};
///
/// let config = aws_sdk_fis::Config::builder()
/// .region(Region::new("us-east-1"))
/// .build();
/// ```
pub fn region(mut self, region: impl Into<Option<aws_types::region::Region>>) -> Self {
self.region = region.into();
self
}
/// Sets the credentials provider for this service
pub fn credentials_provider(
mut self,
credentials_provider: impl aws_types::credentials::ProvideCredentials + 'static,
) -> Self {
self.credentials_provider = Some(aws_types::credentials::SharedCredentialsProvider::new(
credentials_provider,
));
self
}
/// Sets the credentials provider for this service
pub fn set_credentials_provider(
&mut self,
credentials_provider: Option<aws_types::credentials::SharedCredentialsProvider>,
) -> &mut Self {
self.credentials_provider = credentials_provider;
self
}
/// Builds a [`Config`].
pub fn build(self) -> Config {
Config {
make_token: self
.make_token
.unwrap_or_else(crate::idempotency_token::default_provider),
app_name: self.app_name,
timeout_config: self.timeout_config,
sleep_impl: self.sleep_impl,
retry_config: self.retry_config,
endpoint_resolver: self
.endpoint_resolver
.unwrap_or_else(|| ::std::sync::Arc::new(crate::aws_endpoint::endpoint_resolver())),
region: self.region,
credentials_provider: self.credentials_provider.unwrap_or_else(|| {
aws_types::credentials::SharedCredentialsProvider::new(
crate::no_credentials::NoCredentials,
)
}),
}
}
}
impl From<&aws_types::sdk_config::SdkConfig> for Builder {
fn from(input: &aws_types::sdk_config::SdkConfig) -> Self {
let mut builder = Builder::default();
builder = builder.region(input.region().cloned());
builder.set_retry_config(input.retry_config().cloned());
builder.set_timeout_config(input.timeout_config().cloned());
builder.set_sleep_impl(input.sleep_impl().clone());
builder.set_credentials_provider(input.credentials_provider().cloned());
builder.set_app_name(input.app_name().cloned());
builder
}
}
impl From<&aws_types::sdk_config::SdkConfig> for Config {
fn from(sdk_config: &aws_types::sdk_config::SdkConfig) -> Self {
Builder::from(sdk_config).build()
}
}
| 37.027027 | 113 | 0.625466 |
64a17ba220323d3b8c4eaff835322c9110b46cee | 4,906 | // Copyright (C) 2019 Boyu Yang
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::{
convert::{AsMut, AsRef},
mem, ptr,
};
use balloons::{FixedHash, FixedUint, HashAlgo, Result};
pub use balloons::BalloonBuilder;
#[derive(Debug)]
pub struct U256([u64; 4]);
#[derive(Debug)]
pub struct H256([u8; 32]);
const BYTE_BITS: usize = 8;
impl U256 {
#[inline]
fn bytes_size() -> usize {
32
}
const fn unit_bytes_size() -> usize {
64 / BYTE_BITS
}
}
impl FixedUint for U256 {
fn from_slice(slice: &[u8]) -> Self {
let bytes_size = Self::bytes_size();
assert!(slice.len() >= bytes_size);
let inner = unsafe {
let mut inner: [u64; 4] = mem::uninitialized();
let dst_ptr = inner.as_mut_ptr() as *mut u8;
let src_ptr = slice.as_ptr();
if cfg!(target_endian = "little") {
let unit_bytes_size = Self::unit_bytes_size();
let dst_ptr = dst_ptr.add(bytes_size);
let src_ptr = src_ptr.offset(-(unit_bytes_size as isize));
let mut idx = bytes_size;
loop {
let part_dst_ptr = dst_ptr.offset(-(idx as isize));
let part_src_ptr = src_ptr.add(idx + unit_bytes_size - 1);
let mut part_idx = unit_bytes_size as isize - 1;
loop {
*part_dst_ptr.offset(part_idx) = *part_src_ptr.offset(-part_idx);
if part_idx == 0 {
break;
} else {
part_idx -= 1;
}
}
if idx == unit_bytes_size {
break;
}
idx -= unit_bytes_size;
}
} else {
ptr::copy_nonoverlapping(src_ptr, dst_ptr, bytes_size);
}
inner
};
U256(inner)
}
fn modulo(&self, divisor: u64) -> u64 {
let m_2_64 = {
let x = (!0) % divisor + 1;
if x == divisor {
0
} else {
u128::from(x)
}
};
let tmp = u128::from(self.0[3] % divisor);
// Suppose:
// N = 2^64
// Since:
// tmp <= N-2
// m_2_64 <= N-2
// self.0[idx] <= N-1
// So:
// tmp * m_2_64 + self.0[idx]
// <= (N-2) * (N-2) + N - 1
// = N^2 - 3 * (N - 1)
// < N^2
let tmp = (tmp * m_2_64 + u128::from(self.0[2])) % u128::from(divisor);
let tmp = (tmp * m_2_64 + u128::from(self.0[1])) % u128::from(divisor);
let tmp = (tmp * m_2_64 + u128::from(self.0[0])) % u128::from(divisor);
tmp as u64
}
}
impl AsRef<[u8]> for H256 {
fn as_ref(&self) -> &[u8] {
&self.0[..]
}
}
impl AsMut<[u8]> for H256 {
fn as_mut(&mut self) -> &mut [u8] {
&mut self.0[..]
}
}
impl FixedHash<U256> for H256 {}
pub struct Blake2b256 {
inner: blake2b::Blake2b,
}
impl HashAlgo<U256, H256> for Blake2b256 {
fn create() -> Self {
let key = b"balloon-blake2b256";
let inner = blake2b::Blake2bBuilder::new(256 / BYTE_BITS)
.key(key)
.build();
Self { inner }
}
fn update<T>(&mut self, data: T) -> Result<()>
where
T: AsRef<[u8]>,
{
self.inner.update(data.as_ref());
Ok(())
}
fn finalize(self) -> Result<H256> {
let mut inner: [u8; 32] = unsafe { mem::uninitialized() };
self.inner.finalize(&mut inner);
Ok(H256(inner))
}
fn finalize_into(self, dst: &mut H256) -> Result<()> {
self.inner.finalize(dst.as_mut());
Ok(())
}
}
#[cfg(test)]
mod tests {
use crate::kernel::{FixedUint, U256};
use slices::u8_slice;
#[test]
fn u256_from_slice() {
let slice =
u8_slice!("0x123456789abcdef0_13579bdf2468ace0_1122334455667788_99aabbccddeeff00");
let ffu = U256::from_slice(slice);
assert_eq!(ffu.0[0], 0x99aa_bbcc_ddee_ff00);
assert_eq!(ffu.0[1], 0x1122_3344_5566_7788);
assert_eq!(ffu.0[2], 0x1357_9bdf_2468_ace0);
assert_eq!(ffu.0[3], 0x1234_5678_9abc_def0);
}
#[test]
fn u256_modulo() {
let slice =
u8_slice!("0x123456789abcdef0_13579bdf2468ace0_1122334455667788_99aabbccddeeff00");
let ffu = U256::from_slice(slice);
assert_eq!(ffu.modulo(!0), 0xd058_e168_f27b_0258);
}
}
| 28.195402 | 95 | 0.502446 |
fc3a2731089eb406381f6ff37add7f4555b02f87 | 4,814 | // edition:2018
// aux-build: extern_crate.rs
#![crate_name = "foo"]
extern crate extern_crate;
// @has foo/fn.extern_fn.html '//pre[@class="rust fn"]' \
// 'pub fn extern_fn<const N: usize>() -> impl Iterator<Item = [u8; N]>'
pub use extern_crate::extern_fn;
// @has foo/struct.ExternTy.html '//pre[@class="rust struct"]' \
// 'pub struct ExternTy<const N: usize> {'
pub use extern_crate::ExternTy;
// @has foo/type.TyAlias.html '//pre[@class="rust typedef"]' \
// 'type TyAlias<const N: usize> = ExternTy<N>;'
pub use extern_crate::TyAlias;
// @has foo/trait.WTrait.html '//pre[@class="rust trait"]' \
// 'pub trait WTrait<const N: usize, const M: usize>'
// @has - '//*[@class="rust trait"]' 'fn hey<const P: usize>() -> usize'
pub use extern_crate::WTrait;
// @has foo/trait.Trait.html '//pre[@class="rust trait"]' \
// 'pub trait Trait<const N: usize>'
// @has - '//*[@id="impl-Trait%3C1_usize%3E-for-u8"]//h3[@class="code-header in-band"]' 'impl Trait<1_usize> for u8'
// @has - '//*[@id="impl-Trait%3C2_usize%3E-for-u8"]//h3[@class="code-header in-band"]' 'impl Trait<2_usize> for u8'
// @has - '//*[@id="impl-Trait%3C{1%20+%202}%3E-for-u8"]//h3[@class="code-header in-band"]' 'impl Trait<{1 + 2}> for u8'
// @has - '//*[@id="impl-Trait%3CN%3E-for-%5Bu8%3B%20N%5D"]//h3[@class="code-header in-band"]' \
// 'impl<const N: usize> Trait<N> for [u8; N]'
pub trait Trait<const N: usize> {}
impl Trait<1> for u8 {}
impl Trait<2> for u8 {}
impl Trait<{1 + 2}> for u8 {}
impl<const N: usize> Trait<N> for [u8; N] {}
// @has foo/struct.Foo.html '//pre[@class="rust struct"]' \
// 'pub struct Foo<const N: usize> where u8: Trait<N>'
pub struct Foo<const N: usize> where u8: Trait<N>;
// @has foo/struct.Bar.html '//pre[@class="rust struct"]' 'pub struct Bar<T, const N: usize>(_)'
pub struct Bar<T, const N: usize>([T; N]);
// @has foo/struct.Foo.html '//*[@id="impl"]/h3[@class="code-header in-band"]' 'impl<const M: usize> Foo<M> where u8: Trait<M>'
impl<const M: usize> Foo<M> where u8: Trait<M> {
// @has - '//*[@id="associatedconstant.FOO_ASSOC"]' 'pub const FOO_ASSOC: usize'
pub const FOO_ASSOC: usize = M + 13;
// @has - '//*[@id="method.hey"]' 'pub fn hey<const N: usize>(&self) -> Bar<u8, N>'
pub fn hey<const N: usize>(&self) -> Bar<u8, N> {
Bar([0; N])
}
}
// @has foo/struct.Bar.html '//*[@id="impl"]/h3[@class="code-header in-band"]' 'impl<const M: usize> Bar<u8, M>'
impl<const M: usize> Bar<u8, M> {
// @has - '//*[@id="method.hey"]' \
// 'pub fn hey<const N: usize>(&self) -> Foo<N> where u8: Trait<N>'
pub fn hey<const N: usize>(&self) -> Foo<N> where u8: Trait<N> {
Foo
}
}
// @has foo/fn.test.html '//pre[@class="rust fn"]' \
// 'pub fn test<const N: usize>() -> impl Trait<N> where u8: Trait<N>'
pub fn test<const N: usize>() -> impl Trait<N> where u8: Trait<N> {
2u8
}
// @has foo/fn.a_sink.html '//pre[@class="rust fn"]' \
// 'pub async fn a_sink<const N: usize>(v: [u8; N]) -> impl Trait<N>'
pub async fn a_sink<const N: usize>(v: [u8; N]) -> impl Trait<N> {
v
}
// @has foo/fn.b_sink.html '//pre[@class="rust fn"]' \
// 'pub async fn b_sink<const N: usize>(_: impl Trait<N>)'
pub async fn b_sink<const N: usize>(_: impl Trait<N>) {}
// @has foo/fn.concrete.html '//pre[@class="rust fn"]' \
// 'pub fn concrete() -> [u8; 22]'
pub fn concrete() -> [u8; 3 + std::mem::size_of::<u64>() << 1] {
Default::default()
}
// @has foo/type.Faz.html '//pre[@class="rust typedef"]' \
// 'type Faz<const N: usize> = [u8; N];'
pub type Faz<const N: usize> = [u8; N];
// @has foo/type.Fiz.html '//pre[@class="rust typedef"]' \
// 'type Fiz<const N: usize> = [[u8; N]; 48];'
pub type Fiz<const N: usize> = [[u8; N]; 3 << 4];
macro_rules! define_me {
($t:tt<$q:tt>) => {
pub struct $t<const $q: usize>([u8; $q]);
}
}
// @has foo/struct.Foz.html '//pre[@class="rust struct"]' \
// 'pub struct Foz<const N: usize>(_);'
define_me!(Foz<N>);
trait Q {
const ASSOC: usize;
}
impl<const N: usize> Q for [u8; N] {
const ASSOC: usize = N;
}
// @has foo/fn.q_user.html '//pre[@class="rust fn"]' \
// 'pub fn q_user() -> [u8; 13]'
pub fn q_user() -> [u8; <[u8; 13] as Q>::ASSOC] {
[0; <[u8; 13] as Q>::ASSOC]
}
// @has foo/union.Union.html '//pre[@class="rust union"]' \
// 'pub union Union<const N: usize>'
pub union Union<const N: usize> {
// @has - //pre "pub arr: [u8; N]"
pub arr: [u8; N],
// @has - //pre "pub another_arr: [(); N]"
pub another_arr: [(); N],
}
// @has foo/enum.Enum.html '//pre[@class="rust enum"]' \
// 'pub enum Enum<const N: usize>'
pub enum Enum<const N: usize> {
// @has - //pre "Variant([u8; N])"
Variant([u8; N]),
// @has - //pre "EmptyVariant"
EmptyVariant,
}
| 37.317829 | 127 | 0.574366 |
ace23c086a4fb911f7395398020f67b740f0e8dd | 4,574 | #![deny(
warnings,
missing_docs,
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unstable_features,
unused_import_braces
)]
//! node macro facilitates users of duid to use html-like syntax
//! for building view of web app components
extern crate proc_macro;
mod node;
/// Quasi-quoting macro for building duid Nodes.
///
/// The macro allows for specifying html-like elements and attributes, and
/// supports advanced interpolation and looping.
///
///
/// # Elements
///
/// Both open elements with a closing tag, and elements which are immediately
/// closed are supported:
///
/// ```rust
/// use duid::{node,Node};
///
/// let _: Node<()> = rsx!(<input type="button" />);
/// let _: Node<()> = rsx!(<h1>"A title"</h1>);
/// ```
///
/// # Attributes
///
/// Attributes must be valid Rust identifiers. These are translated to
/// `kebab-case` and trimmed. So `x_data_` would be translated to `x-data`.
///
/// Any sort of literal (like `true` or `42u32`) is supported as an attribute
/// argument.
///
/// ```rust
/// use duid::{node,Node};
///
/// let _: Node<()> = rsx!(<input x_data_="my data" />);
/// let _: Node<()> = rsx!(<input x_data_int_=42u32 x_data_bool_=true />);
/// ```
///
/// Attribute values can be interpolated. These expressions must produce
/// an attribute that can be converted into a [Value].
///
/// ```rust
/// use duid::{node,Node};
///
/// struct Model {
/// value: String,
/// }
///
/// impl Model {
/// pub fn view(&self) -> Node<()> {
/// rsx!(<input value={self.value.clone()} />)
/// }
/// }
/// ```
///
/// Whole attributes can also be generated. These expressions must produce an
/// [Attribute].
///
/// ```rust
/// use duid::{node,Node,html::attributes::classes_flag};
///
/// struct Model {
/// editing: bool,
/// completed: bool,
/// }
///
/// impl Model {
/// pub fn view(&self) -> Node<()> {
/// rsx!(<input {{classes_flag([
/// ("todo", true),
/// ("editing", self.editing),
/// ("completed", self.completed),
/// ])}} />)
/// }
/// }
/// ```
///
/// Finally, we also support empty attributes.
///
/// ```rust
/// use duid::{node,Node};
///
/// let _: Node<()> = rsx!(<button disabled />);
/// ```
///
/// [Value]: https://docs.rs/duid/0/duid/html/attributes/enum.Value.html
/// [Attribute]: https://docs.rs/duid/0/duid/type.Attribute.html
///
/// # Event handlers
///
/// Event handlers are special attributes. Any attribute that starts with `on_`
/// will be matched with event handlers available in [duid::dom::events].
///
/// ```rust
/// use duid::{node,Node,
/// events::{InputEvent,KeyboardEvent},
/// };
///
/// enum Msg {
/// Update(String),
/// Add,
/// Nope,
/// }
///
/// struct Model {
/// value: String,
/// }
///
/// impl Model {
/// fn view(&self) -> Node<Msg> {
/// rsx! {
/// <input
/// class="new-todo"
/// id="new-todo"
/// placeholder="What needs to be done?"
/// value={self.value.to_string()}
/// on_input={|v: InputEvent| Msg::Update(v.value.to_string())}
/// on_keypress={|event: KeyboardEvent| {
/// if event.key() == "Enter" {
/// Msg::Add
/// } else {
/// Msg::Nope
/// }
/// }} />
/// }
/// }
/// }
/// ```
///
/// [duid::dom::events]: https://docs.rs/duid/0/duid/dom/events/index.html
///
/// # Loops
///
/// Loops are supported through a special construct. They look and behave like
/// regular Rust loops, except that whatever the loop body evaluates to will be
/// appended to the child of a node.
///
/// The loop body must evaluate to a [Node].
///
/// ```rust
/// use duid::{node,Node,html::text};
///
/// struct Model {
/// items: Vec<String>,
/// }
///
/// impl Model {
/// pub fn view(&self) -> Node<()> {
/// rsx! {
/// <ul>
/// {for item in &self.items {
/// text(item)
/// }}
/// </ul>
/// }
/// }
/// }
/// ```
///
///
/// Note: `rsx!` macro is used since it is not an html tag
/// while most other framework uses `html!` macro, this prevents
/// the library to have collision with the `html` tag, when used as tag macro
#[proc_macro]
pub fn rsx(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
node::to_token_stream(input).into()
} | 25.553073 | 79 | 0.537822 |
d7b7fc908528e57b852c9be9b861aed32e395295 | 1,914 | //! Utilities for inspecting unicode strings.
//!
//! # Usage
//! Use [DecodedString](decoding/struct.DecodedString.html) to wrap a sequence of bytes and a [rust-encoding](https://lifthrasiir.github.io/rust-encoding/) encoding.
//! ```
//! let bytes = [0x41, 0x42, 0x43];
//! let string = string_inspector::DecodedString::decode(&bytes, encoding::all::ISO_8859_2).unwrap();
//!
//! assert_eq!("ABC", string.to_string());
//! assert_eq!("\u{1b}[32mA \u{1b}[0m\u{1b}[34mB \u{1b}[0m\u{1b}[32mC \u{1b}[0m", string.format_characters());
//! assert_eq!("\u{1b}[32m41 \u{1b}[0m\u{1b}[34m42 \u{1b}[0m\u{1b}[32m43 \u{1b}[0m", string.format_bytes());
//! ```
//!
//! [DecodedString](decoding/struct.DecodedString.html) contains a sequence of [Atoms](decoding/enum.Atom.html).
//! Atoms represent either a valid character or an invalid code unit in the original string.
//! ```
//! # let bytes = [0x41, 0x42, 0x43];
//! # let string = string_inspector::DecodedString::decode(&bytes, encoding::all::ISO_8859_2).unwrap();
//! assert_eq!(3, string.atoms.len());
//! ```
//!
//! Atoms can be easily converted to their character representation or byte representation:
//! ```
//! # let bytes = [0x41, 0x42, 0x43];
//! # let string = string_inspector::DecodedString::decode(&bytes, encoding::all::ISO_8859_2).unwrap();
//! assert_eq!('A', string.atoms[0].to_char());
//! assert_eq!(vec![0x41], string.atoms[0].to_bytes());
//! ```
//!
//! The unicode replacement character � (U+FFFD) is used if the input contains invalid code units:
//! ```
//! let bytes = [0x41, 0x42, 0x43, 0xC0];
//! let string = string_inspector::DecodedString::decode(&bytes, encoding::all::UTF_8).unwrap();
//!
//! assert_eq!('\u{FFFD}', string.atoms[3].to_char());
//! assert_eq!(vec![0xC0], string.atoms[3].to_bytes());
//! ```
pub mod cli;
pub mod decoding;
pub use decoding::Atom;
pub use decoding::DecodedCharacter;
pub use decoding::DecodedString; | 44.511628 | 165 | 0.669279 |
cce2a16297a1c6f3038a59503a79530a070c936f | 1,793 | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::sync::Arc;
use engine_traits::{self, Error, Result};
use rocksdb::{DBIterator, SeekKey as RawSeekKey, DB};
// FIXME: Would prefer using &DB instead of Arc<DB>. As elsewhere in
// this crate, it would require generic associated types.
pub struct RocksEngineIterator(DBIterator<Arc<DB>>);
impl RocksEngineIterator {
pub fn from_raw(iter: DBIterator<Arc<DB>>) -> RocksEngineIterator {
RocksEngineIterator(iter)
}
}
impl engine_traits::Iterator for RocksEngineIterator {
fn seek(&mut self, key: engine_traits::SeekKey) -> bool {
let k: RocksSeekKey = key.into();
self.0.seek(k.into_raw())
}
fn seek_for_prev(&mut self, key: engine_traits::SeekKey) -> bool {
let k: RocksSeekKey = key.into();
self.0.seek_for_prev(k.into_raw())
}
fn prev(&mut self) -> bool {
self.0.prev()
}
fn next(&mut self) -> bool {
self.0.next()
}
fn key(&self) -> &[u8] {
self.0.key()
}
fn value(&self) -> &[u8] {
self.0.value()
}
fn valid(&self) -> bool {
self.0.valid()
}
fn status(&self) -> Result<()> {
self.0.status().map_err(Error::Engine)
}
}
pub struct RocksSeekKey<'a>(RawSeekKey<'a>);
impl<'a> RocksSeekKey<'a> {
pub fn into_raw(self) -> RawSeekKey<'a> {
self.0
}
}
impl<'a> From<engine_traits::SeekKey<'a>> for RocksSeekKey<'a> {
fn from(key: engine_traits::SeekKey<'a>) -> Self {
let k = match key {
engine_traits::SeekKey::Start => RawSeekKey::Start,
engine_traits::SeekKey::End => RawSeekKey::End,
engine_traits::SeekKey::Key(k) => RawSeekKey::Key(k),
};
RocksSeekKey(k)
}
}
| 24.902778 | 71 | 0.59565 |
09d646681e2bdf18b0555a33c39f03eedc0eb233 | 2,437 | // Copyright (c) SimpleStaking, Viable Systems and Tezedge Contributors
// SPDX-License-Identifier: MIT
//! This channel is used to transmit p2p networking messages between actors.
use std::net::SocketAddr;
use std::sync::Arc;
use tezedge_actor_system::actors::*;
use tezos_messages::p2p::encoding::metadata::MetadataMessage;
use tezos_messages::p2p::encoding::peer::PeerMessageResponse;
use crate::PeerId;
use tezos_messages::p2p::encoding::version::NetworkVersion;
/// We have received message from another peer
#[derive(Clone, Debug)]
pub struct PeerMessageReceived {
pub peer_address: SocketAddr,
pub message: Arc<PeerMessageResponse>,
}
/// Network channel event message.
#[derive(Clone, Debug)]
pub enum NetworkChannelMsg {
/// Events
PeerBootstrapped(Arc<PeerId>, MetadataMessage, Arc<NetworkVersion>),
PeerDisconnected(SocketAddr),
PeerMessageReceived(PeerMessageReceived),
}
/// Represents various topics
pub enum NetworkChannelTopic {
/// Events generated from networking layer
NetworkEvents,
/// Commands generated from other layers for network layer
NetworkCommands,
}
impl From<NetworkChannelTopic> for Topic {
fn from(evt: NetworkChannelTopic) -> Self {
match evt {
NetworkChannelTopic::NetworkEvents => Topic::from("network.events"),
NetworkChannelTopic::NetworkCommands => Topic::from("network.commands"),
}
}
}
/// This struct represents network bus where all network events must be published.
pub struct NetworkChannel(Channel<NetworkChannelMsg>);
pub type NetworkChannelRef = ChannelRef<NetworkChannelMsg>;
impl NetworkChannel {
pub fn actor(fact: &impl ActorRefFactory) -> Result<NetworkChannelRef, CreateError> {
fact.actor_of::<NetworkChannel>(NetworkChannel::name())
}
fn name() -> &'static str {
"network-event-channel"
}
}
type ChannelCtx<Msg> = Context<ChannelMsg<Msg>>;
impl ActorFactory for NetworkChannel {
fn create() -> Self {
NetworkChannel(Channel::default())
}
}
impl Actor for NetworkChannel {
type Msg = ChannelMsg<NetworkChannelMsg>;
fn pre_start(&mut self, ctx: &ChannelCtx<NetworkChannelMsg>) {
self.0.pre_start(ctx);
}
fn recv(
&mut self,
ctx: &ChannelCtx<NetworkChannelMsg>,
msg: ChannelMsg<NetworkChannelMsg>,
sender: Sender,
) {
self.0.receive(ctx, msg, sender);
}
}
| 27.077778 | 89 | 0.703734 |
0af5fa1e7701358ace38a997b333bb80ec4c2879 | 1,109 | use std::collections::HashMap;
use std::io;
fn main() {
let mut ids = Vec::new();
loop {
let mut buf = String::new();
match io::stdin().read_line(&mut buf) {
Ok(_) => {
if buf == "\n" {
break;
}
ids.push(buf)
}
Err(error) => println!("error: {}", error),
}
}
let mut twices = 0;
let mut thrices = 0;
for id in ids {
let mut counts: HashMap<char, i32> = HashMap::new();
for x in id.chars() {
let val = counts.entry(x).or_insert(0);
*val += 1;
}
for (_, v) in &counts {
match v {
2 => {
twices += 1;
break;
}
_ => (),
}
}
for (_, v) in &counts {
match v {
3 => {
thrices += 1;
break;
}
_ => (),
}
}
}
println!("Result: {}", twices * thrices)
}
| 22.632653 | 60 | 0.32642 |
d5cfc9b6d6b6c06e0fd69ccaa7fd50a8a8e7f73d | 9,519 | extern crate specs;
use specs::prelude::*;
use super::{Attributes, Skills, WantsToMelee, Name,
HungerClock, HungerState, Pools, skill_bonus,
Skill, Equipped, Weapon, EquipmentSlot, WeaponAttribute, Wearable, NaturalAttackDefense,
effects::*};
pub struct MeleeCombatSystem {}
impl<'a> System<'a> for MeleeCombatSystem {
#[allow(clippy::type_complexity)]
type SystemData = ( Entities<'a>,
WriteStorage<'a, WantsToMelee>,
ReadStorage<'a, Name>,
ReadStorage<'a, Attributes>,
ReadStorage<'a, Skills>,
ReadStorage<'a, HungerClock>,
ReadStorage<'a, Pools>,
WriteExpect<'a, rltk::RandomNumberGenerator>,
ReadStorage<'a, Equipped>,
ReadStorage<'a, Weapon>,
ReadStorage<'a, Wearable>,
ReadStorage<'a, NaturalAttackDefense>
);
fn run(&mut self, data : Self::SystemData) {
let (entities, mut wants_melee, names, attributes, skills,
hunger_clock, pools, mut rng, equipped_items, weapon, wearables, natural) = data;
for (entity, wants_melee, name, attacker_attributes, attacker_skills, attacker_pools) in (&entities, &wants_melee, &names, &attributes, &skills, &pools).join() {
// Are the attacker and defender alive? Only attack if they are
let target_pools = pools.get(wants_melee.target).unwrap();
let target_attributes = attributes.get(wants_melee.target).unwrap();
let target_skills = skills.get(wants_melee.target).unwrap();
if attacker_pools.hit_points.current > 0 && target_pools.hit_points.current > 0 {
let target_name = names.get(wants_melee.target).unwrap();
// Define the basic unarmed attack - overridden by wielding check below if a weapon is equipped
let mut weapon_info = Weapon{
range: None,
attribute : WeaponAttribute::Might,
hit_bonus : 0,
damage_n_dice : 1,
damage_die_type : 4,
damage_bonus : 0,
proc_chance : None,
proc_target : None
};
if let Some(nat) = natural.get(entity) {
if !nat.attacks.is_empty() {
let attack_index = if nat.attacks.len()==1 { 0 } else { rng.roll_dice(1, nat.attacks.len() as i32) as usize -1 };
weapon_info.hit_bonus = nat.attacks[attack_index].hit_bonus;
weapon_info.damage_n_dice = nat.attacks[attack_index].damage_n_dice;
weapon_info.damage_die_type = nat.attacks[attack_index].damage_die_type;
weapon_info.damage_bonus = nat.attacks[attack_index].damage_bonus;
}
}
let mut weapon_entity : Option<Entity> = None;
for (weaponentity,wielded,melee) in (&entities, &equipped_items, &weapon).join() {
if wielded.owner == entity && wielded.slot == EquipmentSlot::Melee {
weapon_info = melee.clone();
weapon_entity = Some(weaponentity);
}
}
let natural_roll = rng.roll_dice(1, 20);
let attribute_hit_bonus = if weapon_info.attribute == WeaponAttribute::Might
{ attacker_attributes.might.bonus }
else { attacker_attributes.quickness.bonus};
let skill_hit_bonus = skill_bonus(Skill::Melee, &*attacker_skills);
let weapon_hit_bonus = weapon_info.hit_bonus;
let mut status_hit_bonus = 0;
if let Some(hc) = hunger_clock.get(entity) { // Well-Fed grants +1
if hc.state == HungerState::WellFed {
status_hit_bonus += 1;
}
}
let modified_hit_roll = natural_roll + attribute_hit_bonus + skill_hit_bonus
+ weapon_hit_bonus + status_hit_bonus;
//println!("Natural roll: {}", natural_roll);
//println!("Modified hit roll: {}", modified_hit_roll);
let mut armor_item_bonus_f = 0.0;
for (wielded,armor) in (&equipped_items, &wearables).join() {
if wielded.owner == wants_melee.target {
armor_item_bonus_f += armor.armor_class;
}
}
let base_armor_class = match natural.get(wants_melee.target) {
None => 10,
Some(nat) => nat.armor_class.unwrap_or(10)
};
let armor_quickness_bonus = target_attributes.quickness.bonus;
let armor_skill_bonus = skill_bonus(Skill::Defense, &*target_skills);
let armor_item_bonus = armor_item_bonus_f as i32;
let armor_class = base_armor_class + armor_quickness_bonus + armor_skill_bonus
+ armor_item_bonus;
//println!("Armor class: {}", armor_class);
if natural_roll != 1 && (natural_roll == 20 || modified_hit_roll > armor_class) {
// Target hit! Until we support weapons, we're going with 1d4
let base_damage = rng.roll_dice(weapon_info.damage_n_dice, weapon_info.damage_die_type);
let attr_damage_bonus = attacker_attributes.might.bonus;
let skill_damage_bonus = skill_bonus(Skill::Melee, &*attacker_skills);
let weapon_damage_bonus = weapon_info.damage_bonus;
let damage = i32::max(0, base_damage + attr_damage_bonus +
skill_damage_bonus + weapon_damage_bonus);
/*println!("Damage: {} + {}attr + {}skill + {}weapon = {}",
base_damage, attr_damage_bonus, skill_damage_bonus,
weapon_damage_bonus, damage
);*/
add_effect(
Some(entity),
EffectType::Damage{ amount: damage },
Targets::Single{ target: wants_melee.target }
);
crate::gamelog::Logger::new()
.npc_name(&name.name)
.append("hits")
.npc_name(&target_name.name)
.append("for")
.damage(damage)
.append("hp.")
.log();
// Proc effects
if let Some(chance) = &weapon_info.proc_chance {
let roll = rng.roll_dice(1, 100);
//println!("Roll {}, Chance {}", roll, chance);
if roll <= (chance * 100.0) as i32 {
//println!("Proc!");
let effect_target = if weapon_info.proc_target.unwrap() == "Self" {
Targets::Single{ target: entity }
} else {
Targets::Single { target : wants_melee.target }
};
add_effect(
Some(entity),
EffectType::ItemUse{ item: weapon_entity.unwrap() },
effect_target
)
}
}
} else if natural_roll == 1 {
// Natural 1 miss
crate::gamelog::Logger::new()
.color(rltk::CYAN)
.append(&name.name)
.color(rltk::WHITE)
.append("considers attacking")
.color(rltk::CYAN)
.append(&target_name.name)
.color(rltk::WHITE)
.append("but misjudges the timing!")
.log();
add_effect(
None,
EffectType::Particle{ glyph: rltk::to_cp437('‼'), fg: rltk::RGB::named(rltk::BLUE), bg : rltk::RGB::named(rltk::BLACK), lifespan: 200.0 },
Targets::Single{ target: wants_melee.target }
);
} else {
// Miss
crate::gamelog::Logger::new()
.color(rltk::CYAN)
.append(&name.name)
.color(rltk::WHITE)
.append("attacks")
.color(rltk::CYAN)
.append(&target_name.name)
.color(rltk::WHITE)
.append("but can't connect.")
.log();
add_effect(
None,
EffectType::Particle{ glyph: rltk::to_cp437('‼'), fg: rltk::RGB::named(rltk::CYAN), bg : rltk::RGB::named(rltk::BLACK), lifespan: 200.0 },
Targets::Single{ target: wants_melee.target }
);
}
}
}
wants_melee.clear();
}
}
| 50.1 | 169 | 0.479987 |
f95229d07750204f27e18816b1989118f4c20ab2 | 680 | #[macro_use]
extern crate plaster;
#[macro_use]
extern crate wasm_bindgen_test;
wasm_bindgen_test_configure!(run_in_browser);
use plaster::prelude::*;
use plaster::virtual_dom::VNode;
struct Comp;
impl Component for Comp {
type Message = ();
type Properties = ();
fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self {
Comp
}
fn update(&mut self, _: Self::Message) -> ShouldRender {
unimplemented!();
}
}
impl Renderable<Comp> for Comp {
fn view(&self) -> Html<Self> {
unimplemented!();
}
}
#[wasm_bindgen_test]
fn text_as_root() {
let _: VNode<Comp> = html! {
{ "Text Node As Root" }
};
}
| 17.894737 | 68 | 0.620588 |
bbea84529fd7fbc9815bef2d33f064c7047dab76 | 3,207 | #[macro_use]
extern crate serde_json;
#[cfg(test)]
mod tests {
use serde_json::Value;
use serde_pickle as pickle;
use std::fs::File;
use toml;
#[test]
fn test_dynamic_json() {
let j = r#"{
"userid": 103609,
"verified": true,
"friendly_name": "Jason",
"access_privileges": [
"user",
"admin"
]
}"#;
let parsed: Value = serde_json::from_str(j).unwrap();
let expected = json!({
"userid": 103609,
"verified": true,
"friendly_name": "Jason",
"access_privileges": [
"user",
"admin"
]
});
assert_eq!(parsed, expected);
assert_eq!(parsed["userid"], 103609);
assert_eq!(parsed["verified"], true);
assert_eq!(parsed["friendly_name"], "Jason");
assert_eq!(parsed["access_privileges"][0], "user");
assert_eq!(parsed["access_privileges"][1], "admin");
assert_eq!(parsed["access_privileges"][2], Value::Null);
assert_eq!(parsed["not-available"], Value::Null);
}
#[test]
fn test_dynamic_pickle() {
let parsed: Value = {
let data = File::open("user.pkl").expect("Did you run create_pickle.py?");
pickle::from_reader(&data).unwrap()
};
let expected = json!({
"userid": 103609,
"verified": true,
"friendly_name": "Jason",
"access_privileges": [
"user",
"admin"
]
});
assert_eq!(parsed, expected);
assert_eq!(parsed["userid"], 103609);
assert_eq!(parsed["verified"], true);
assert_eq!(parsed["friendly_name"], "Jason");
assert_eq!(parsed["access_privileges"][0], "user");
assert_eq!(parsed["access_privileges"][1], "admin");
assert_eq!(parsed["access_privileges"][2], Value::Null);
assert_eq!(parsed["not-available"], Value::Null);
}
#[test]
fn test_dynamic_toml() {
let t = r#"
[[user]]
userid = 103609
verified = true
friendly_name = "Jason"
access_privileges = [ "user", "admin" ]
"#;
let parsed: Value = toml::de::from_str(t).unwrap();
let expected = json!({
"user": [
{
"userid": 103609,
"verified": true,
"friendly_name": "Jason",
"access_privileges": [
"user",
"admin"
]
}
]
});
assert_eq!(parsed, expected);
let first_user = &parsed["user"][0];
assert_eq!(first_user["userid"], 103609);
assert_eq!(first_user["verified"], true);
assert_eq!(first_user["friendly_name"], "Jason");
assert_eq!(first_user["access_privileges"][0], "user");
assert_eq!(first_user["access_privileges"][1], "admin");
assert_eq!(first_user["access_privileges"][2], Value::Null);
assert_eq!(first_user["not-available"], Value::Null);
}
}
| 28.891892 | 86 | 0.494855 |
5b1ae167ce31543850a1475dcf5f9379536baaa6 | 2,299 | // http://rust-lang.org/COPYRIGHT.
//
// #[test_case] is used by custom test authors to mark tests
// When building for test, it needs to make the item public and gensym the name
// Otherwise, we'll omit the item. This behavior means that any item annotated
// with #[test_case] is never addressable.
//
// We mark item with an inert attribute "rustc_test_marker" which the test generation
// logic will pick up on.
use syntax::ext::base::*;
use syntax::ext::build::AstBuilder;
use syntax::ext::hygiene::{Mark, SyntaxContext};
use syntax::ast;
use syntax::source_map::respan;
use syntax::symbol::{Symbol, sym};
use syntax_pos::{DUMMY_SP, Span};
use syntax::source_map::{ExpnInfo, MacroAttribute};
use syntax::feature_gate;
pub fn expand(
ecx: &mut ExtCtxt<'_>,
attr_sp: Span,
_meta_item: &ast::MetaItem,
anno_item: Annotatable
) -> Vec<Annotatable> {
if !ecx.ecfg.enable_custom_test_frameworks() {
feature_gate::emit_feature_err(&ecx.parse_sess,
sym::custom_test_frameworks,
attr_sp,
feature_gate::GateIssue::Language,
feature_gate::EXPLAIN_CUSTOM_TEST_FRAMEWORKS);
}
if !ecx.ecfg.should_test { return vec![]; }
let sp = {
let mark = Mark::fresh(Mark::root());
mark.set_expn_info(ExpnInfo {
call_site: DUMMY_SP,
def_site: None,
format: MacroAttribute(Symbol::intern("test_case")),
allow_internal_unstable: Some(vec![
Symbol::intern("test"),
Symbol::intern("rustc_attrs"),
].into()),
allow_internal_unsafe: false,
local_inner_macros: false,
edition: ecx.parse_sess.edition,
});
attr_sp.with_ctxt(SyntaxContext::empty().apply_mark(mark))
};
let mut item = anno_item.expect_item();
item = item.map(|mut item| {
item.vis = respan(item.vis.span, ast::VisibilityKind::Public);
item.ident = item.ident.gensym();
item.attrs.push(
ecx.attribute(sp,
ecx.meta_word(sp, Symbol::intern("rustc_test_marker")))
);
item
});
return vec![Annotatable::Item(item)]
}
| 33.318841 | 85 | 0.599826 |
908e4acb8d96dbc36d780fea8684b2ae352b9f40 | 1,039 | use shell2batch;
#[test]
fn convert() {
let script = shell2batch::convert(
r#"
set -x
export FILE1=file1
export FILE2=file2
#this is some test code
cp ${FILE1} $FILE2
cp -r ${DIR1} $DIR2
#another
mv file2 file3
export MY_DIR=directory
#flags are supported
rm -Rf ${MY_DIR}
unset MY_DIR
touch ./file3
#provide custom windows command for specific shell command
complex_bash_command --flag1 value2 # shell2batch: complex_windows_command /flag10 windows_value
"#,
);
assert_eq!(
script,
r#"
@echo on
set FILE1=file1
set FILE2=file2
@REM this is some test code
copy %FILE1% %FILE2%
xcopy /E %DIR1% %DIR2%
@REM another
move file2 file3
set MY_DIR=directory
@REM flags are supported
rmdir /S /Q %MY_DIR%
set MY_DIR=
copy /B .\file3+,, .\file3
@REM provide custom windows command for specific shell command
complex_windows_command /flag10 windows_value
"#
);
}
| 16.758065 | 104 | 0.620789 |
2f71230d5729faa26ee6d5d3bd9c3e430b301d0d | 332 | mod file;
mod misc;
mod projfs;
mod result;
mod windows;
mod zip;
pub use crate::{
file::OnexFile,
misc::{OffsetSeeker, ReadSeek, SeekableVec},
projfs::ProjfsProvider,
result::{Error, Result},
windows::{get_temp_dir, raw_str_to_os_string, to_u16_vec},
zip::{extract_zip, list_zip_contents, zip_app_dir},
};
| 20.75 | 62 | 0.704819 |
f53d40f5f8f89ff90b4da9f09e3c9e8d6b60f861 | 9,316 | use crate::{
ast,
types::{DefaultAttribute, FieldWithArgs, ScalarField, ScalarType, SortOrder},
walkers::{EnumWalker, ModelWalker, Walker},
ParserDatabase, ScalarFieldType,
};
use diagnostics::Span;
/// A scalar field, as part of a model.
#[derive(Debug, Copy, Clone)]
pub struct ScalarFieldWalker<'db> {
pub(crate) model_id: ast::ModelId,
pub(crate) field_id: ast::FieldId,
pub(crate) db: &'db ParserDatabase,
pub(crate) scalar_field: &'db ScalarField,
}
impl<'db> PartialEq for ScalarFieldWalker<'db> {
fn eq(&self, other: &Self) -> bool {
self.model_id == other.model_id && self.field_id == other.field_id
}
}
impl<'db> Eq for ScalarFieldWalker<'db> {}
impl<'db> ScalarFieldWalker<'db> {
/// The ID of the field node in the AST.
pub fn field_id(self) -> ast::FieldId {
self.field_id
}
/// The field node in the AST.
pub fn ast_field(self) -> &'db ast::Field {
&self.db.ast[self.model_id][self.field_id]
}
/// The name of the field.
pub fn name(self) -> &'db str {
self.ast_field().name()
}
/// The `@default()` AST attribute on the field, if any.
pub fn default_attribute(self) -> Option<&'db ast::Attribute> {
self.scalar_field
.default
.as_ref()
.map(|d| d.default_attribute)
.map(|id| &self.db.ast[id])
}
/// The final database name of the field. See crate docs for explanations on database names.
pub fn database_name(self) -> &'db str {
self.attributes()
.mapped_name
.map(|id| &self.db[id])
.unwrap_or_else(|| self.name())
}
/// Does the field have an `@default(autoincrement())` attribute?
pub fn is_autoincrement(self) -> bool {
self.default_value().map(|dv| dv.is_autoincrement()).unwrap_or(false)
}
/// Does the field define a primary key by its own.
pub fn is_single_pk(self) -> bool {
self.model().field_is_single_pk(self.field_id)
}
/// Is there an `@ignore` attribute on the field?
pub fn is_ignored(self) -> bool {
self.attributes().is_ignored
}
/// Is the field optional / nullable?
pub fn is_optional(self) -> bool {
self.ast_field().arity.is_optional()
}
/// Is there an `@updateAt` attribute on the field?
pub fn is_updated_at(self) -> bool {
self.attributes().is_updated_at
}
fn attributes(self) -> &'db ScalarField {
self.scalar_field
}
/// Is this field's type an enum? If yes, walk the enum.
pub fn field_type_as_enum(self) -> Option<EnumWalker<'db>> {
match self.scalar_field_type() {
ScalarFieldType::Enum(enum_id) => Some(Walker {
db: self.db,
id: enum_id,
}),
_ => None,
}
}
/// The name in the `@map(<name>)` attribute.
pub fn mapped_name(self) -> Option<&'db str> {
self.attributes().mapped_name.map(|id| &self.db[id])
}
/// The model that contains the field.
pub fn model(self) -> ModelWalker<'db> {
ModelWalker {
model_id: self.model_id,
db: self.db,
model_attributes: &self.db.types.model_attributes[&self.model_id],
}
}
/// (attribute scope, native type name, arguments, span)
///
/// For example: `@db.Text` would translate to ("db", "Text", &[], <the span>)
pub fn raw_native_type(self) -> Option<(&'db str, &'db str, &'db [String], Span)> {
let db = self.db;
self.attributes()
.native_type
.as_ref()
.map(move |(datasource_name, name, args, span)| (&db[*datasource_name], &db[*name], args.as_slice(), *span))
}
/// Is the type of the field `Unsupported("...")`?
pub fn is_unsupported(self) -> bool {
matches!(self.ast_field().field_type, ast::FieldType::Unsupported(_, _))
}
/// The `@default()` attribute of the field, if any.
pub fn default_value(self) -> Option<DefaultValueWalker<'db>> {
self.attributes().default.as_ref().map(|d| DefaultValueWalker {
model_id: self.model_id,
field_id: self.field_id,
db: self.db,
default: d,
})
}
/// The type of the field, with type aliases resolved.
pub fn resolved_scalar_field_type(self) -> ScalarFieldType {
match self.attributes().r#type {
ScalarFieldType::Alias(id) => *self.db.alias_scalar_field_type(&id),
other => other,
}
}
/// The type of the field.
pub fn scalar_field_type(self) -> ScalarFieldType {
self.attributes().r#type
}
/// The type of the field in case it is a scalar type (not an enum, not a composite type).
pub fn scalar_type(self) -> Option<ScalarType> {
let mut tpe = &self.scalar_field.r#type;
loop {
match tpe {
ScalarFieldType::BuiltInScalar(scalar) => return Some(*scalar),
ScalarFieldType::Alias(alias_id) => tpe = &self.db.types.type_aliases[alias_id],
_ => return None,
}
}
}
}
/// An `@default()` attribute on a field.
#[derive(Clone, Copy)]
pub struct DefaultValueWalker<'db> {
model_id: ast::ModelId,
field_id: ast::FieldId,
db: &'db ParserDatabase,
default: &'db DefaultAttribute,
}
impl<'db> DefaultValueWalker<'db> {
/// The AST node of the attribute.
pub fn ast_attribute(self) -> &'db ast::Attribute {
&self.db.ast[self.default.default_attribute]
}
/// The value expression in the `@default` attribute.
///
/// ```ignore
/// score Int @default(0)
/// ^
/// ```
pub fn value(self) -> &'db ast::Expression {
&self.ast_attribute().arguments.arguments[self.default.argument_idx].value
}
/// Is this an `@default(autoincrement())`?
pub fn is_autoincrement(self) -> bool {
matches!(self.value(), ast::Expression::Function(name, _, _) if name == "autoincrement")
}
/// Is this an `@default(cuid())`?
pub fn is_cuid(self) -> bool {
matches!(self.value(), ast::Expression::Function(name, _, _) if name == "cuid")
}
/// Is this an `@default(dbgenerated())`?
pub fn is_dbgenerated(self) -> bool {
matches!(self.value(), ast::Expression::Function(name, _, _) if name == "dbgenerated")
}
/// Is this an `@default(auto())`?
pub fn is_auto(self) -> bool {
matches!(self.value(), ast::Expression::Function(name, _, _) if name == "auto")
}
/// Is this an `@default(now())`?
pub fn is_now(self) -> bool {
matches!(self.value(), ast::Expression::Function(name, _, _) if name == "now")
}
/// Is this an `@default(uuid())`?
pub fn is_uuid(self) -> bool {
matches!(self.value(), ast::Expression::Function(name, _, _) if name == "uuid")
}
/// The mapped name of the default value. Not applicable to all connectors. See crate docs for
/// details on mapped names.
///
/// ```ignore
/// name String @default("george", map: "name_default_to_george")
/// ^^^^^^^^^^^^^^^^^^^^^^^^
/// ```
pub fn mapped_name(self) -> Option<&'db str> {
self.default.mapped_name.map(|id| &self.db[id])
}
/// The field carrying the default attribute.
///
/// ```ignore
/// name String @default("george")
/// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/// ```
pub fn field(self) -> ScalarFieldWalker<'db> {
ScalarFieldWalker {
model_id: self.model_id,
field_id: self.field_id,
db: self.db,
scalar_field: &self.db.types.scalar_fields[&(self.model_id, self.field_id)],
}
}
}
/// A scalar field as referenced in a key specification (id, index or unique).
#[derive(Copy, Clone)]
pub struct ScalarFieldAttributeWalker<'db> {
pub(crate) model_id: ast::ModelId,
pub(crate) fields: &'db [FieldWithArgs],
pub(crate) db: &'db ParserDatabase,
pub(crate) field_arg_id: usize,
}
impl<'db> ScalarFieldAttributeWalker<'db> {
fn args(self) -> &'db FieldWithArgs {
&self.fields[self.field_arg_id]
}
/// The length argument on the field.
///
/// ```ignore
/// @@index(name(length: 10))
/// ^^
/// ```
pub fn length(self) -> Option<u32> {
self.args().length
}
/// The underlying scalar field.
///
/// ```ignore
/// model Test {
/// id Int @id
/// name String
/// ^^^^^^^^^^^^^^^^^^
/// kind Int
///
/// @@index([name])
/// }
///
/// ```
pub fn as_scalar_field(self) -> ScalarFieldWalker<'db> {
ScalarFieldWalker {
model_id: self.model_id,
field_id: self.args().field_id,
db: self.db,
scalar_field: &self.db.types.scalar_fields[&(self.model_id, self.args().field_id)],
}
}
/// The sort order (asc or desc) on the field.
///
/// ```ignore
/// @@index(name(sort: Desc))
/// ^^^^
/// ```
pub fn sort_order(&self) -> Option<SortOrder> {
self.args().sort_order
}
}
| 30.644737 | 120 | 0.560434 |
236730a287ff2b799033dcf789253912c1990df5 | 2,991 | use crate::event::{LogEvent, Value};
use rlua::prelude::*;
impl<'a> ToLua<'a> for LogEvent {
fn to_lua(self, ctx: LuaContext<'a>) -> LuaResult<LuaValue> {
ctx.create_table_from(self.into_iter().map(|(k, v)| (k, v)))
.map(LuaValue::Table)
}
}
impl<'a> FromLua<'a> for LogEvent {
fn from_lua(value: LuaValue<'a>, _: LuaContext<'a>) -> LuaResult<Self> {
match value {
LuaValue::Table(t) => {
let mut log = LogEvent::default();
for pair in t.pairs() {
let (key, value): (String, Value) = pair?;
log.insert_flat(key, value);
}
Ok(log)
}
_ => Err(rlua::Error::FromLuaConversionError {
from: value.type_name(),
to: "LogEvent",
message: Some("LogEvent should ba a Lua table".to_string()),
}),
}
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::event::Event;
#[test]
fn to_lua() {
let mut event = Event::new_empty_log();
let log = event.as_mut_log();
log.insert("a", 1);
log.insert("nested.field", "2");
log.insert("nested.array[0]", "example value");
log.insert("nested.array[2]", "another value");
let assertions = vec![
"type(log) == 'table'",
"log.a == 1",
"type(log.nested) == 'table'",
"log.nested.field == '2'",
"#log.nested.array == 3",
"log.nested.array[1] == 'example value'",
"log.nested.array[2] == ''",
"log.nested.array[3] == 'another value'",
];
Lua::new().context(move |ctx| {
ctx.globals().set("log", log.clone()).unwrap();
for assertion in assertions {
let result: bool = ctx
.load(assertion)
.eval()
.unwrap_or_else(|_| panic!("Failed to verify assertion {:?}", assertion));
assert!(result, assertion);
}
});
}
#[test]
fn from_lua() {
let lua_event = r#"
{
a = 1,
nested = {
field = '2',
array = {'example value', '', 'another value'}
}
}
"#;
Lua::new().context(move |ctx| {
let event: LogEvent = ctx.load(lua_event).eval().unwrap();
assert_eq!(event[&"a".into()], Value::Integer(1));
assert_eq!(event[&"nested.field".into()], Value::Bytes("2".into()));
assert_eq!(
event[&"nested.array[0]".into()],
Value::Bytes("example value".into())
);
assert_eq!(event[&"nested.array[1]".into()], Value::Bytes("".into()));
assert_eq!(
event[&"nested.array[2]".into()],
Value::Bytes("another value".into())
);
});
}
}
| 31.15625 | 94 | 0.452023 |
75821e08a47e34fc82a33a6b31f732e88e4100aa | 40,723 | use crate::bounding_volume::{BoundingSphere, BoundingVolume, AABB};
use crate::mass_properties::MassProperties;
use crate::math::{Isometry, Point, Real, Vector};
use crate::query::{PointQuery, RayCast};
#[cfg(feature = "serde-serialize")]
use crate::shape::SharedShape;
#[cfg(feature = "std")]
use crate::shape::{composite_shape::SimdCompositeShape, Compound, HeightField, Polyline, TriMesh};
use crate::shape::{
Ball, Capsule, Cuboid, FeatureId, HalfSpace, PolygonalFeatureMap, RoundCuboid, RoundShape,
RoundTriangle, Segment, SupportMap, Triangle,
};
#[cfg(feature = "dim3")]
use crate::shape::{Cone, Cylinder, RoundCone, RoundCylinder};
#[cfg(feature = "dim3")]
#[cfg(feature = "std")]
use crate::shape::{ConvexPolyhedron, RoundConvexPolyhedron};
#[cfg(feature = "dim2")]
#[cfg(feature = "std")]
use crate::shape::{ConvexPolygon, RoundConvexPolygon};
use downcast_rs::{impl_downcast, DowncastSync};
use na::{RealField, Unit};
use num::Zero;
use num_derive::FromPrimitive;
#[derive(Copy, Clone, Debug, FromPrimitive, PartialEq, Eq, Hash)]
/// Enum representing the type of a shape.
pub enum ShapeType {
/// A ball shape.
Ball = 0,
/// A cuboid shape.
Cuboid,
/// A capsule shape.
Capsule,
/// A segment shape.
Segment,
/// A triangle shape.
Triangle,
/// A triangle mesh shape.
TriMesh,
/// A set of segments.
Polyline,
/// A shape representing a full half-space.
HalfSpace,
/// A heightfield shape.
HeightField,
/// A Compound shape.
Compound,
#[cfg(feature = "dim2")]
ConvexPolygon,
#[cfg(feature = "dim3")]
/// A convex polyhedron.
ConvexPolyhedron,
#[cfg(feature = "dim3")]
/// A cylindrical shape.
Cylinder,
#[cfg(feature = "dim3")]
/// A cone shape.
Cone,
// /// A custom shape type.
// Custom(u8),
/// A cuboid with rounded corners.
RoundCuboid,
/// A triangle with rounded corners.
RoundTriangle,
// /// A triangle-mesh with rounded corners.
// RoundedTriMesh,
// /// An heightfield with rounded corners.
// RoundedHeightField,
/// A cylinder with rounded corners.
#[cfg(feature = "dim3")]
RoundCylinder,
/// A cone with rounded corners.
#[cfg(feature = "dim3")]
RoundCone,
/// A convex polyhedron with rounded corners.
#[cfg(feature = "dim3")]
RoundConvexPolyhedron,
/// A convex polygon with rounded corners.
#[cfg(feature = "dim2")]
RoundConvexPolygon,
/// A custom user-defined shape.
Custom,
}
#[derive(Copy, Clone)]
#[cfg_attr(feature = "serde-serialize", derive(Serialize))]
/// Enum representing the shape with its actual type
pub enum TypedShape<'a> {
/// A ball shape.
Ball(&'a Ball),
/// A cuboid shape.
Cuboid(&'a Cuboid),
/// A capsule shape.
Capsule(&'a Capsule),
/// A segment shape.
Segment(&'a Segment),
/// A triangle shape.
Triangle(&'a Triangle),
/// A triangle mesh shape.
#[cfg(feature = "std")]
TriMesh(&'a TriMesh),
/// A set of segments.
#[cfg(feature = "std")]
Polyline(&'a Polyline),
/// A shape representing a full half-space.
HalfSpace(&'a HalfSpace),
/// A heightfield shape.
#[cfg(feature = "std")]
HeightField(&'a HeightField),
/// A Compound shape.
#[cfg(feature = "std")]
Compound(&'a Compound),
#[cfg(feature = "dim2")]
#[cfg(feature = "std")]
ConvexPolygon(&'a ConvexPolygon),
#[cfg(feature = "dim3")]
#[cfg(feature = "std")]
/// A convex polyhedron.
ConvexPolyhedron(&'a ConvexPolyhedron),
#[cfg(feature = "dim3")]
/// A cylindrical shape.
Cylinder(&'a Cylinder),
#[cfg(feature = "dim3")]
/// A cone shape.
Cone(&'a Cone),
// /// A custom shape type.
// Custom(u8),
/// A cuboid with rounded corners.
RoundCuboid(&'a RoundCuboid),
/// A triangle with rounded corners.
RoundTriangle(&'a RoundTriangle),
// /// A triangle-mesh with rounded corners.
// RoundedTriMesh,
// /// An heightfield with rounded corners.
// RoundedHeightField,
/// A cylinder with rounded corners.
#[cfg(feature = "dim3")]
RoundCylinder(&'a RoundCylinder),
/// A cone with rounded corners.
#[cfg(feature = "dim3")]
RoundCone(&'a RoundCone),
/// A convex polyhedron with rounded corners.
#[cfg(feature = "dim3")]
#[cfg(feature = "std")]
RoundConvexPolyhedron(&'a RoundConvexPolyhedron),
/// A convex polygon with rounded corners.
#[cfg(feature = "dim2")]
#[cfg(feature = "std")]
RoundConvexPolygon(&'a RoundConvexPolygon),
/// A custom user-defined shape with a type identified by a number.
Custom(u32),
}
#[cfg(feature = "serde-serialize")]
#[derive(Deserialize)]
// NOTE: tha this enum MUST match the `TypedShape` enum.
/// Enum representing the shape with its actual type
pub(crate) enum DeserializableTypedShape {
/// A ball shape.
Ball(Ball),
/// A cuboid shape.
Cuboid(Cuboid),
/// A capsule shape.
Capsule(Capsule),
/// A segment shape.
Segment(Segment),
/// A triangle shape.
Triangle(Triangle),
/// A triangle mesh shape.
#[cfg(feature = "std")]
TriMesh(TriMesh),
/// A set of segments.
#[cfg(feature = "std")]
Polyline(Polyline),
/// A shape representing a full half-space.
HalfSpace(HalfSpace),
/// A heightfield shape.
#[cfg(feature = "std")]
HeightField(HeightField),
/// A Compound shape.
#[cfg(feature = "std")]
Compound(Compound),
#[cfg(feature = "dim2")]
#[cfg(feature = "std")]
ConvexPolygon(ConvexPolygon),
#[cfg(feature = "dim3")]
#[cfg(feature = "std")]
/// A convex polyhedron.
ConvexPolyhedron(ConvexPolyhedron),
#[cfg(feature = "dim3")]
/// A cylindrical shape.
Cylinder(Cylinder),
#[cfg(feature = "dim3")]
/// A cone shape.
Cone(Cone),
// /// A custom shape type.
// Custom(u8),
/// A cuboid with rounded corners.
RoundCuboid(RoundCuboid),
/// A triangle with rounded corners.
RoundTriangle(RoundTriangle),
// /// A triangle-mesh with rounded corners.
// RoundedTriMesh,
// /// An heightfield with rounded corners.
// RoundedHeightField,
/// A cylinder with rounded corners.
#[cfg(feature = "dim3")]
RoundCylinder(RoundCylinder),
/// A cone with rounded corners.
#[cfg(feature = "dim3")]
RoundCone(RoundCone),
/// A convex polyhedron with rounded corners.
#[cfg(feature = "dim3")]
#[cfg(feature = "std")]
RoundConvexPolyhedron(RoundConvexPolyhedron),
/// A convex polygon with rounded corners.
#[cfg(feature = "dim2")]
#[cfg(feature = "std")]
RoundConvexPolygon(RoundConvexPolygon),
/// A custom user-defined shape identified by a number.
Custom(u32),
}
#[cfg(feature = "serde-serialize")]
impl DeserializableTypedShape {
/// Converts `self` to a `SharedShape` if `self` isn't `Custom`.
pub fn into_shared_shape(self) -> Option<SharedShape> {
match self {
DeserializableTypedShape::Ball(s) => Some(SharedShape::new(s)),
DeserializableTypedShape::Cuboid(s) => Some(SharedShape::new(s)),
DeserializableTypedShape::Capsule(s) => Some(SharedShape::new(s)),
DeserializableTypedShape::Segment(s) => Some(SharedShape::new(s)),
DeserializableTypedShape::Triangle(s) => Some(SharedShape::new(s)),
#[cfg(feature = "std")]
DeserializableTypedShape::TriMesh(s) => Some(SharedShape::new(s)),
#[cfg(feature = "std")]
DeserializableTypedShape::Polyline(s) => Some(SharedShape::new(s)),
DeserializableTypedShape::HalfSpace(s) => Some(SharedShape::new(s)),
#[cfg(feature = "std")]
DeserializableTypedShape::HeightField(s) => Some(SharedShape::new(s)),
#[cfg(feature = "std")]
DeserializableTypedShape::Compound(s) => Some(SharedShape::new(s)),
#[cfg(feature = "dim2")]
#[cfg(feature = "std")]
DeserializableTypedShape::ConvexPolygon(s) => Some(SharedShape::new(s)),
#[cfg(feature = "dim3")]
#[cfg(feature = "std")]
DeserializableTypedShape::ConvexPolyhedron(s) => Some(SharedShape::new(s)),
#[cfg(feature = "dim3")]
DeserializableTypedShape::Cylinder(s) => Some(SharedShape::new(s)),
#[cfg(feature = "dim3")]
DeserializableTypedShape::Cone(s) => Some(SharedShape::new(s)),
DeserializableTypedShape::RoundCuboid(s) => Some(SharedShape::new(s)),
DeserializableTypedShape::RoundTriangle(s) => Some(SharedShape::new(s)),
#[cfg(feature = "dim3")]
DeserializableTypedShape::RoundCylinder(s) => Some(SharedShape::new(s)),
#[cfg(feature = "dim3")]
DeserializableTypedShape::RoundCone(s) => Some(SharedShape::new(s)),
#[cfg(feature = "dim3")]
#[cfg(feature = "std")]
DeserializableTypedShape::RoundConvexPolyhedron(s) => Some(SharedShape::new(s)),
#[cfg(feature = "dim2")]
#[cfg(feature = "std")]
DeserializableTypedShape::RoundConvexPolygon(s) => Some(SharedShape::new(s)),
DeserializableTypedShape::Custom(_) => None,
}
}
}
/// Trait implemented by shapes usable by Rapier.
pub trait Shape: RayCast + PointQuery + DowncastSync {
/// Computes the AABB of this shape.
fn compute_local_aabb(&self) -> AABB;
/// Computes the bounding-sphere of this shape.
fn compute_local_bounding_sphere(&self) -> BoundingSphere;
/// Clones this shape into a boxed trait-object.
#[cfg(feature = "std")]
fn clone_box(&self) -> Box<dyn Shape>;
/// Computes the AABB of this shape with the given position.
fn compute_aabb(&self, position: &Isometry<Real>) -> AABB {
self.compute_local_aabb().transform_by(position)
}
/// Computes the bounding-sphere of this shape with the given position.
fn compute_bounding_sphere(&self, position: &Isometry<Real>) -> BoundingSphere {
self.compute_local_bounding_sphere().transform_by(position)
}
/// Compute the mass-properties of this shape given its uniform density.
fn mass_properties(&self, density: Real) -> MassProperties;
/// Gets the type tag of this shape.
fn shape_type(&self) -> ShapeType;
/// Gets the underlying shape as an enum.
fn as_typed_shape(&self) -> TypedShape;
fn ccd_thickness(&self) -> Real;
// TODO: document this.
// This should probably be the largest sharp edge angle (in radians) in [0; PI].
// Though this isn't a very good description considering this is PI / 2
// for capsule (which doesn't have any sharp angle). I guess a better way
// to phrase this is: "the smallest angle such that rotating the shape by
// that angle may result in different contact points".
fn ccd_angular_thickness(&self) -> Real;
/// Is this shape known to be convex?
///
/// If this returns `true` then `self` is known to be convex.
/// If this returns `false` then it is not known whether or
/// not `self` is convex.
fn is_convex(&self) -> bool {
false
}
/// Convents this shape into its support mapping, if it has one.
fn as_support_map(&self) -> Option<&dyn SupportMap> {
None
}
#[cfg(feature = "std")]
fn as_composite_shape(&self) -> Option<&dyn SimdCompositeShape> {
None
}
/// Converts this shape to a polygonal feature-map, if it is one.
fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {
None
}
// fn as_rounded(&self) -> Option<&Rounded<Box<AnyShape>>> {
// None
// }
/// The shape's normal at the given point located on a specific feature.
fn feature_normal_at_point(
&self,
_feature: FeatureId,
_point: &Point<Real>,
) -> Option<Unit<Vector<Real>>> {
None
}
/// Computes the swept AABB of this shape, i.e., the space it would occupy by moving from
/// the given start position to the given end position.
fn compute_swept_aabb(&self, start_pos: &Isometry<Real>, end_pos: &Isometry<Real>) -> AABB {
let aabb1 = self.compute_aabb(start_pos);
let aabb2 = self.compute_aabb(end_pos);
aabb1.merged(&aabb2)
}
}
impl_downcast!(sync Shape);
impl dyn Shape {
/// Converts this abstract shape to the given shape, if it is one.
pub fn as_shape<T: Shape>(&self) -> Option<&T> {
self.downcast_ref()
}
/// Converts this abstract shape to the given mutable shape, if it is one.
pub fn as_shape_mut<T: Shape>(&mut self) -> Option<&mut T> {
self.downcast_mut()
}
/// Converts this abstract shape to a ball, if it is one.
pub fn as_ball(&self) -> Option<&Ball> {
self.downcast_ref()
}
/// Converts this abstract shape to a mutable ball, if it is one.
pub fn as_ball_mut(&mut self) -> Option<&mut Ball> {
self.downcast_mut()
}
/// Converts this abstract shape to a cuboid, if it is one.
pub fn as_cuboid(&self) -> Option<&Cuboid> {
self.downcast_ref()
}
/// Converts this abstract shape to a mutable cuboid, if it is one.
pub fn as_cuboid_mut(&mut self) -> Option<&mut Cuboid> {
self.downcast_mut()
}
/// Converts this abstract shape to a halfspace, if it is one.
pub fn as_halfspace(&self) -> Option<&HalfSpace> {
self.downcast_ref()
}
/// Converts this abstract shape to a halfspace, if it is one.
pub fn as_halfspace_mut(&mut self) -> Option<&mut HalfSpace> {
self.downcast_mut()
}
/// Converts this abstract shape to a segment, if it is one.
pub fn as_segment(&self) -> Option<&Segment> {
self.downcast_ref()
}
/// Converts this abstract shape to a mutable segment, if it is one.
pub fn as_segment_mut(&mut self) -> Option<&mut Segment> {
self.downcast_mut()
}
/// Converts this abstract shape to a capsule, if it is one.
pub fn as_capsule(&self) -> Option<&Capsule> {
self.downcast_ref()
}
/// Converts this abstract shape to a mutable capsule, if it is one.
pub fn as_capsule_mut(&mut self) -> Option<&mut Capsule> {
self.downcast_mut()
}
/// Converts this abstract shape to a triangle, if it is one.
pub fn as_triangle(&self) -> Option<&Triangle> {
self.downcast_ref()
}
/// Converts this abstract shape to a mutable triangle, if it is one.
pub fn as_triangle_mut(&mut self) -> Option<&mut Triangle> {
self.downcast_mut()
}
/// Converts this abstract shape to a compound shape, if it is one.
#[cfg(feature = "std")]
pub fn as_compound(&self) -> Option<&Compound> {
self.downcast_ref()
}
/// Converts this abstract shape to a mutable compound shape, if it is one.
#[cfg(feature = "std")]
pub fn as_compound_mut(&mut self) -> Option<&mut Compound> {
self.downcast_mut()
}
/// Converts this abstract shape to a triangle mesh, if it is one.
#[cfg(feature = "std")]
pub fn as_trimesh(&self) -> Option<&TriMesh> {
self.downcast_ref()
}
/// Converts this abstract shape to a mutable triangle mesh, if it is one.
#[cfg(feature = "std")]
pub fn as_trimesh_mut(&mut self) -> Option<&mut TriMesh> {
self.downcast_mut()
}
/// Converts this abstract shape to a polyline, if it is one.
#[cfg(feature = "std")]
pub fn as_polyline(&self) -> Option<&Polyline> {
self.downcast_ref()
}
/// Converts this abstract shape to a mutable polyline, if it is one.
#[cfg(feature = "std")]
pub fn as_polyline_mut(&mut self) -> Option<&mut Polyline> {
self.downcast_mut()
}
/// Converts this abstract shape to a heightfield, if it is one.
#[cfg(feature = "std")]
pub fn as_heightfield(&self) -> Option<&HeightField> {
self.downcast_ref()
}
/// Converts this abstract shape to a mutable heightfield, if it is one.
#[cfg(feature = "std")]
pub fn as_heightfield_mut(&mut self) -> Option<&mut HeightField> {
self.downcast_mut()
}
/// Converts this abstract shape to a round cuboid, if it is one.
pub fn as_round_cuboid(&self) -> Option<&RoundCuboid> {
self.downcast_ref()
}
/// Converts this abstract shape to a mutable round cuboid, if it is one.
pub fn as_round_cuboid_mut(&mut self) -> Option<&mut RoundCuboid> {
self.downcast_mut()
}
/// Converts this abstract shape to a round triangle, if it is one.
pub fn as_round_triangle(&self) -> Option<&RoundTriangle> {
self.downcast_ref()
}
/// Converts this abstract shape to a round triangle, if it is one.
pub fn as_round_triangle_mut(&mut self) -> Option<&mut RoundTriangle> {
self.downcast_mut()
}
/// Converts this abstract shape to a convex polygon, if it is one.
#[cfg(feature = "dim2")]
#[cfg(feature = "std")]
pub fn as_convex_polygon(&self) -> Option<&ConvexPolygon> {
self.downcast_ref()
}
/// Converts this abstract shape to a mutable convex polygon, if it is one.
#[cfg(feature = "dim2")]
#[cfg(feature = "std")]
pub fn as_convex_polygon_mut(&mut self) -> Option<&mut ConvexPolygon> {
self.downcast_mut()
}
/// Converts this abstract shape to a round convex polygon, if it is one.
#[cfg(feature = "dim2")]
#[cfg(feature = "std")]
pub fn as_round_convex_polygon(&self) -> Option<&RoundConvexPolygon> {
self.downcast_ref()
}
/// Converts this abstract shape to a mutable round convex polygon, if it is one.
#[cfg(feature = "dim2")]
#[cfg(feature = "std")]
pub fn as_round_convex_polygon_mut(&mut self) -> Option<&mut RoundConvexPolygon> {
self.downcast_mut()
}
#[cfg(feature = "dim3")]
#[cfg(feature = "std")]
pub fn as_convex_polyhedron(&self) -> Option<&ConvexPolyhedron> {
self.downcast_ref()
}
#[cfg(feature = "dim3")]
#[cfg(feature = "std")]
pub fn as_convex_polyhedron_mut(&mut self) -> Option<&mut ConvexPolyhedron> {
self.downcast_mut()
}
/// Converts this abstract shape to a cylinder, if it is one.
#[cfg(feature = "dim3")]
pub fn as_cylinder(&self) -> Option<&Cylinder> {
self.downcast_ref()
}
/// Converts this abstract shape to a mutable cylinder, if it is one.
#[cfg(feature = "dim3")]
pub fn as_cylinder_mut(&mut self) -> Option<&mut Cylinder> {
self.downcast_mut()
}
/// Converts this abstract shape to a cone, if it is one.
#[cfg(feature = "dim3")]
pub fn as_cone(&self) -> Option<&Cone> {
self.downcast_ref()
}
/// Converts this abstract shape to a mutable cone, if it is one.
#[cfg(feature = "dim3")]
pub fn as_cone_mut(&mut self) -> Option<&mut Cone> {
self.downcast_mut()
}
/// Converts this abstract shape to a round cylinder, if it is one.
#[cfg(feature = "dim3")]
pub fn as_round_cylinder(&self) -> Option<&RoundCylinder> {
self.downcast_ref()
}
/// Converts this abstract shape to a mutable round cylinder, if it is one.
#[cfg(feature = "dim3")]
pub fn as_round_cylinder_mut(&mut self) -> Option<&mut RoundCylinder> {
self.downcast_mut()
}
/// Converts this abstract shape to a round cone, if it is one.
#[cfg(feature = "dim3")]
pub fn as_round_cone(&self) -> Option<&RoundCone> {
self.downcast_ref()
}
/// Converts this abstract shape to a mutable round cone, if it is one.
#[cfg(feature = "dim3")]
pub fn as_round_cone_mut(&mut self) -> Option<&mut RoundCone> {
self.downcast_mut()
}
/// Converts this abstract shape to a round convex polyhedron, if it is one.
#[cfg(feature = "dim3")]
#[cfg(feature = "std")]
pub fn as_round_convex_polyhedron(&self) -> Option<&RoundConvexPolyhedron> {
self.downcast_ref()
}
/// Converts this abstract shape to a mutable round convex polyhedron, if it is one.
#[cfg(feature = "dim3")]
#[cfg(feature = "std")]
pub fn as_round_convex_polyhedron_mut(&mut self) -> Option<&mut RoundConvexPolyhedron> {
self.downcast_mut()
}
}
impl Shape for Ball {
#[cfg(feature = "std")]
fn clone_box(&self) -> Box<dyn Shape> {
Box::new(self.clone())
}
fn compute_local_aabb(&self) -> AABB {
self.local_aabb()
}
fn compute_local_bounding_sphere(&self) -> BoundingSphere {
self.local_bounding_sphere()
}
fn compute_aabb(&self, position: &Isometry<Real>) -> AABB {
self.aabb(position)
}
fn mass_properties(&self, density: Real) -> MassProperties {
MassProperties::from_ball(density, self.radius)
}
fn ccd_thickness(&self) -> Real {
self.radius
}
fn ccd_angular_thickness(&self) -> Real {
Real::pi()
}
fn is_convex(&self) -> bool {
true
}
fn shape_type(&self) -> ShapeType {
ShapeType::Ball
}
fn as_typed_shape(&self) -> TypedShape {
TypedShape::Ball(self)
}
fn as_support_map(&self) -> Option<&dyn SupportMap> {
Some(self as &dyn SupportMap)
}
/// The shape's normal at the given point located on a specific feature.
#[inline]
fn feature_normal_at_point(
&self,
_: FeatureId,
point: &Point<Real>,
) -> Option<Unit<Vector<Real>>> {
Unit::try_new(point.coords, crate::math::DEFAULT_EPSILON)
}
}
impl Shape for Cuboid {
#[cfg(feature = "std")]
fn clone_box(&self) -> Box<dyn Shape> {
Box::new(self.clone())
}
fn compute_local_aabb(&self) -> AABB {
self.local_aabb()
}
fn compute_local_bounding_sphere(&self) -> BoundingSphere {
self.local_bounding_sphere()
}
fn compute_aabb(&self, position: &Isometry<Real>) -> AABB {
self.aabb(position)
}
fn mass_properties(&self, density: Real) -> MassProperties {
MassProperties::from_cuboid(density, self.half_extents)
}
fn is_convex(&self) -> bool {
true
}
fn shape_type(&self) -> ShapeType {
ShapeType::Cuboid
}
fn as_typed_shape(&self) -> TypedShape {
TypedShape::Cuboid(self)
}
fn ccd_thickness(&self) -> Real {
self.half_extents.min()
}
fn ccd_angular_thickness(&self) -> Real {
Real::frac_pi_2()
}
fn as_support_map(&self) -> Option<&dyn SupportMap> {
Some(self as &dyn SupportMap)
}
fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {
Some((self as &dyn PolygonalFeatureMap, 0.0))
}
fn feature_normal_at_point(
&self,
feature: FeatureId,
_point: &Point<Real>,
) -> Option<Unit<Vector<Real>>> {
self.feature_normal(feature)
}
}
impl Shape for Capsule {
#[cfg(feature = "std")]
fn clone_box(&self) -> Box<dyn Shape> {
Box::new(self.clone())
}
fn compute_local_aabb(&self) -> AABB {
self.local_aabb()
}
fn compute_local_bounding_sphere(&self) -> BoundingSphere {
self.local_bounding_sphere()
}
fn compute_aabb(&self, position: &Isometry<Real>) -> AABB {
self.aabb(position)
}
fn mass_properties(&self, density: Real) -> MassProperties {
MassProperties::from_capsule(density, self.segment.a, self.segment.b, self.radius)
}
fn is_convex(&self) -> bool {
true
}
fn shape_type(&self) -> ShapeType {
ShapeType::Capsule
}
fn as_typed_shape(&self) -> TypedShape {
TypedShape::Capsule(self)
}
fn ccd_thickness(&self) -> Real {
self.radius
}
fn ccd_angular_thickness(&self) -> Real {
Real::frac_pi_2()
}
fn as_support_map(&self) -> Option<&dyn SupportMap> {
Some(self as &dyn SupportMap)
}
fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {
Some((&self.segment as &dyn PolygonalFeatureMap, self.radius))
}
}
impl Shape for Triangle {
#[cfg(feature = "std")]
fn clone_box(&self) -> Box<dyn Shape> {
Box::new(self.clone())
}
fn compute_local_aabb(&self) -> AABB {
self.local_aabb()
}
fn compute_local_bounding_sphere(&self) -> BoundingSphere {
self.local_bounding_sphere()
}
fn compute_aabb(&self, position: &Isometry<Real>) -> AABB {
self.aabb(position)
}
fn mass_properties(&self, _density: Real) -> MassProperties {
#[cfg(feature = "dim2")]
return MassProperties::from_triangle(_density, &self.a, &self.b, &self.c);
#[cfg(feature = "dim3")]
return MassProperties::zero();
}
fn is_convex(&self) -> bool {
true
}
fn shape_type(&self) -> ShapeType {
ShapeType::Triangle
}
fn as_typed_shape(&self) -> TypedShape {
TypedShape::Triangle(self)
}
fn ccd_thickness(&self) -> Real {
// TODO: in 2D use the smallest height of the triangle.
0.0
}
fn ccd_angular_thickness(&self) -> Real {
Real::frac_pi_2()
}
fn as_support_map(&self) -> Option<&dyn SupportMap> {
Some(self as &dyn SupportMap)
}
fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {
Some((self as &dyn PolygonalFeatureMap, 0.0))
}
fn feature_normal_at_point(
&self,
feature: FeatureId,
_point: &Point<Real>,
) -> Option<Unit<Vector<Real>>> {
self.feature_normal(feature)
}
}
impl Shape for Segment {
#[cfg(feature = "std")]
fn clone_box(&self) -> Box<dyn Shape> {
Box::new(self.clone())
}
fn compute_local_aabb(&self) -> AABB {
self.local_aabb()
}
fn compute_local_bounding_sphere(&self) -> BoundingSphere {
self.local_bounding_sphere()
}
fn compute_aabb(&self, position: &Isometry<Real>) -> AABB {
self.aabb(position)
}
fn mass_properties(&self, _density: Real) -> MassProperties {
MassProperties::zero()
}
fn is_convex(&self) -> bool {
true
}
fn ccd_thickness(&self) -> Real {
0.0
}
fn ccd_angular_thickness(&self) -> Real {
Real::frac_pi_2()
}
fn shape_type(&self) -> ShapeType {
ShapeType::Segment
}
fn as_typed_shape(&self) -> TypedShape {
TypedShape::Segment(self)
}
fn as_support_map(&self) -> Option<&dyn SupportMap> {
Some(self as &dyn SupportMap)
}
fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {
Some((self as &dyn PolygonalFeatureMap, 0.0))
}
fn feature_normal_at_point(
&self,
feature: FeatureId,
_point: &Point<Real>,
) -> Option<Unit<Vector<Real>>> {
self.feature_normal(feature)
}
}
#[cfg(feature = "std")]
impl Shape for Compound {
fn clone_box(&self) -> Box<dyn Shape> {
Box::new(self.clone())
}
fn compute_local_aabb(&self) -> AABB {
*self.local_aabb()
}
fn compute_local_bounding_sphere(&self) -> BoundingSphere {
self.local_bounding_sphere()
}
fn compute_aabb(&self, position: &Isometry<Real>) -> AABB {
self.local_aabb().transform_by(position)
}
fn mass_properties(&self, density: Real) -> MassProperties {
MassProperties::from_compound(density, self.shapes())
}
fn shape_type(&self) -> ShapeType {
ShapeType::Compound
}
fn as_typed_shape(&self) -> TypedShape {
TypedShape::Compound(self)
}
fn ccd_thickness(&self) -> Real {
self.shapes()
.iter()
.fold(Real::MAX, |curr, (_, s)| curr.min(s.ccd_thickness()))
}
fn ccd_angular_thickness(&self) -> Real {
self.shapes().iter().fold(Real::MAX, |curr, (_, s)| {
curr.max(s.ccd_angular_thickness())
})
}
#[cfg(feature = "std")]
fn as_composite_shape(&self) -> Option<&dyn SimdCompositeShape> {
Some(self as &dyn SimdCompositeShape)
}
}
#[cfg(feature = "std")]
impl Shape for Polyline {
fn clone_box(&self) -> Box<dyn Shape> {
Box::new(self.clone())
}
fn compute_local_aabb(&self) -> AABB {
*self.local_aabb()
}
fn compute_local_bounding_sphere(&self) -> BoundingSphere {
self.local_bounding_sphere()
}
fn compute_aabb(&self, position: &Isometry<Real>) -> AABB {
self.aabb(position)
}
fn mass_properties(&self, _density: Real) -> MassProperties {
MassProperties::zero()
}
fn shape_type(&self) -> ShapeType {
ShapeType::Polyline
}
fn as_typed_shape(&self) -> TypedShape {
TypedShape::Polyline(self)
}
fn ccd_thickness(&self) -> Real {
0.0
}
fn ccd_angular_thickness(&self) -> Real {
// TODO: the value should depend on the angles between
// adjacent segments of the polyline.
Real::frac_pi_4()
}
#[cfg(feature = "std")]
fn as_composite_shape(&self) -> Option<&dyn SimdCompositeShape> {
Some(self as &dyn SimdCompositeShape)
}
}
#[cfg(feature = "std")]
impl Shape for TriMesh {
fn clone_box(&self) -> Box<dyn Shape> {
Box::new(self.clone())
}
fn compute_local_aabb(&self) -> AABB {
*self.local_aabb()
}
fn compute_local_bounding_sphere(&self) -> BoundingSphere {
self.local_bounding_sphere()
}
fn compute_aabb(&self, position: &Isometry<Real>) -> AABB {
self.aabb(position)
}
fn mass_properties(&self, _density: Real) -> MassProperties {
#[cfg(feature = "dim2")]
return MassProperties::from_trimesh(_density, self.vertices(), self.indices());
#[cfg(feature = "dim3")]
return MassProperties::zero();
}
fn shape_type(&self) -> ShapeType {
ShapeType::TriMesh
}
fn as_typed_shape(&self) -> TypedShape {
TypedShape::TriMesh(self)
}
fn ccd_thickness(&self) -> Real {
// TODO: in 2D, return the smallest CCD thickness among triangles?
0.0
}
fn ccd_angular_thickness(&self) -> Real {
// TODO: the value should depend on the angles between
// adjacent triangles of the trimesh.
Real::frac_pi_4()
}
#[cfg(feature = "std")]
fn as_composite_shape(&self) -> Option<&dyn SimdCompositeShape> {
Some(self as &dyn SimdCompositeShape)
}
}
#[cfg(feature = "std")]
impl Shape for HeightField {
fn clone_box(&self) -> Box<dyn Shape> {
Box::new(self.clone())
}
fn compute_local_aabb(&self) -> AABB {
self.local_aabb()
}
fn compute_local_bounding_sphere(&self) -> BoundingSphere {
self.local_bounding_sphere()
}
fn compute_aabb(&self, position: &Isometry<Real>) -> AABB {
self.aabb(position)
}
fn mass_properties(&self, _density: Real) -> MassProperties {
MassProperties::zero()
}
fn shape_type(&self) -> ShapeType {
ShapeType::HeightField
}
fn as_typed_shape(&self) -> TypedShape {
TypedShape::HeightField(self)
}
fn ccd_thickness(&self) -> Real {
0.0
}
fn ccd_angular_thickness(&self) -> Real {
// TODO: the value should depend on the angles between
// adjacent triangles of the heightfield.
Real::frac_pi_4()
}
}
#[cfg(feature = "dim2")]
#[cfg(feature = "std")]
impl Shape for ConvexPolygon {
fn clone_box(&self) -> Box<dyn Shape> {
Box::new(self.clone())
}
fn compute_local_aabb(&self) -> AABB {
self.local_aabb()
}
fn compute_local_bounding_sphere(&self) -> BoundingSphere {
self.local_bounding_sphere()
}
fn compute_aabb(&self, position: &Isometry<Real>) -> AABB {
self.aabb(position)
}
fn mass_properties(&self, density: Real) -> MassProperties {
MassProperties::from_convex_polygon(density, &self.points())
}
fn is_convex(&self) -> bool {
true
}
fn shape_type(&self) -> ShapeType {
ShapeType::ConvexPolygon
}
fn as_typed_shape(&self) -> TypedShape {
TypedShape::ConvexPolygon(self)
}
fn ccd_thickness(&self) -> Real {
// TODO: we should use the OBB instead.
self.compute_local_aabb().half_extents().min()
}
fn ccd_angular_thickness(&self) -> Real {
// TODO: the value should depend on the angles between
// adjacent segments of the convex polygon.
Real::frac_pi_4()
}
fn as_support_map(&self) -> Option<&dyn SupportMap> {
Some(self as &dyn SupportMap)
}
fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {
Some((self as &dyn PolygonalFeatureMap, 0.0))
}
fn feature_normal_at_point(
&self,
feature: FeatureId,
_point: &Point<Real>,
) -> Option<Unit<Vector<Real>>> {
self.feature_normal(feature)
}
}
#[cfg(feature = "dim3")]
#[cfg(feature = "std")]
impl Shape for ConvexPolyhedron {
fn clone_box(&self) -> Box<dyn Shape> {
Box::new(self.clone())
}
fn compute_local_aabb(&self) -> AABB {
self.local_aabb()
}
fn compute_local_bounding_sphere(&self) -> BoundingSphere {
self.local_bounding_sphere()
}
fn compute_aabb(&self, position: &Isometry<Real>) -> AABB {
self.aabb(position)
}
fn mass_properties(&self, density: Real) -> MassProperties {
let (vertices, indices) = self.to_trimesh();
MassProperties::from_convex_polyhedron(density, &vertices, &indices)
}
fn is_convex(&self) -> bool {
true
}
fn shape_type(&self) -> ShapeType {
ShapeType::ConvexPolyhedron
}
fn as_typed_shape(&self) -> TypedShape {
TypedShape::ConvexPolyhedron(self)
}
fn ccd_thickness(&self) -> Real {
// TODO: we should use the OBB instead.
self.compute_local_aabb().half_extents().min()
}
fn ccd_angular_thickness(&self) -> Real {
// TODO: the value should depend on the angles between
// adjacent segments of the convex polyhedron.
Real::frac_pi_4()
}
fn as_support_map(&self) -> Option<&dyn SupportMap> {
Some(self as &dyn SupportMap)
}
fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {
Some((self as &dyn PolygonalFeatureMap, 0.0))
}
fn feature_normal_at_point(
&self,
feature: FeatureId,
_point: &Point<Real>,
) -> Option<Unit<Vector<Real>>> {
self.feature_normal(feature)
}
}
#[cfg(feature = "dim3")]
impl Shape for Cylinder {
#[cfg(feature = "std")]
fn clone_box(&self) -> Box<dyn Shape> {
Box::new(self.clone())
}
fn compute_local_aabb(&self) -> AABB {
self.local_aabb()
}
fn compute_local_bounding_sphere(&self) -> BoundingSphere {
self.local_bounding_sphere()
}
fn compute_aabb(&self, position: &Isometry<Real>) -> AABB {
self.aabb(position)
}
fn mass_properties(&self, density: Real) -> MassProperties {
MassProperties::from_cylinder(density, self.half_height, self.radius)
}
fn is_convex(&self) -> bool {
true
}
fn shape_type(&self) -> ShapeType {
ShapeType::Cylinder
}
fn as_typed_shape(&self) -> TypedShape {
TypedShape::Cylinder(self)
}
fn ccd_thickness(&self) -> Real {
self.radius
}
fn ccd_angular_thickness(&self) -> Real {
Real::frac_pi_2()
}
fn as_support_map(&self) -> Option<&dyn SupportMap> {
Some(self as &dyn SupportMap)
}
fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {
Some((self as &dyn PolygonalFeatureMap, 0.0))
}
}
#[cfg(feature = "dim3")]
impl Shape for Cone {
#[cfg(feature = "std")]
fn clone_box(&self) -> Box<dyn Shape> {
Box::new(self.clone())
}
fn compute_local_aabb(&self) -> AABB {
self.local_aabb()
}
fn compute_local_bounding_sphere(&self) -> BoundingSphere {
self.local_bounding_sphere()
}
fn compute_aabb(&self, position: &Isometry<Real>) -> AABB {
self.aabb(position)
}
fn mass_properties(&self, density: Real) -> MassProperties {
MassProperties::from_cone(density, self.half_height, self.radius)
}
fn is_convex(&self) -> bool {
true
}
fn shape_type(&self) -> ShapeType {
ShapeType::Cone
}
fn as_typed_shape(&self) -> TypedShape {
TypedShape::Cone(self)
}
fn ccd_thickness(&self) -> Real {
self.radius
}
fn ccd_angular_thickness(&self) -> Real {
let apex_half_angle = self.radius.atan2(self.half_height);
assert!(apex_half_angle >= 0.0);
let basis_angle = Real::frac_pi_2() - apex_half_angle;
basis_angle.min(apex_half_angle * 2.0)
}
fn as_support_map(&self) -> Option<&dyn SupportMap> {
Some(self as &dyn SupportMap)
}
fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {
Some((self as &dyn PolygonalFeatureMap, 0.0))
}
}
impl Shape for HalfSpace {
#[cfg(feature = "std")]
fn clone_box(&self) -> Box<dyn Shape> {
Box::new(self.clone())
}
fn compute_local_aabb(&self) -> AABB {
self.local_aabb()
}
fn compute_local_bounding_sphere(&self) -> BoundingSphere {
self.local_bounding_sphere()
}
fn compute_aabb(&self, position: &Isometry<Real>) -> AABB {
self.aabb(position)
}
fn is_convex(&self) -> bool {
true
}
fn ccd_thickness(&self) -> Real {
f32::MAX as Real
}
fn ccd_angular_thickness(&self) -> Real {
Real::pi()
}
fn mass_properties(&self, _: Real) -> MassProperties {
MassProperties::zero()
}
fn shape_type(&self) -> ShapeType {
ShapeType::HalfSpace
}
fn as_typed_shape(&self) -> TypedShape {
TypedShape::HalfSpace(self)
}
}
macro_rules! impl_shape_for_round_shape(
($($S: ty, $Tag: ident);*) => {$(
impl Shape for RoundShape<$S> {
#[cfg(feature = "std")]
fn clone_box(&self) -> Box<dyn Shape> {
Box::new(self.clone())
}
fn compute_local_aabb(&self) -> AABB {
self.base_shape.local_aabb().loosened(self.border_radius)
}
fn compute_local_bounding_sphere(&self) -> BoundingSphere {
self.base_shape.local_bounding_sphere().loosened(self.border_radius)
}
fn compute_aabb(&self, position: &Isometry<Real>) -> AABB {
self.base_shape.aabb(position).loosened(self.border_radius)
}
fn mass_properties(&self, density: Real) -> MassProperties {
self.base_shape.mass_properties(density)
}
fn is_convex(&self) -> bool {
self.base_shape.is_convex()
}
fn shape_type(&self) -> ShapeType {
ShapeType::$Tag
}
fn as_typed_shape(&self) -> TypedShape {
TypedShape::$Tag(self)
}
fn ccd_thickness(&self) -> Real {
self.base_shape.ccd_thickness() + self.border_radius
}
fn ccd_angular_thickness(&self) -> Real {
// The fact that the shape is round doesn't change anything
// to the CCD angular thickness.
self.base_shape.ccd_angular_thickness()
}
fn as_support_map(&self) -> Option<&dyn SupportMap> {
Some(self as &dyn SupportMap)
}
fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {
Some((&self.base_shape as &dyn PolygonalFeatureMap, self.border_radius))
}
}
)*}
);
impl_shape_for_round_shape!(
Cuboid, RoundCuboid;
Triangle, RoundTriangle
);
#[cfg(feature = "dim2")]
#[cfg(feature = "std")]
impl_shape_for_round_shape!(ConvexPolygon, RoundConvexPolygon);
#[cfg(feature = "dim3")]
impl_shape_for_round_shape!(
Cylinder, RoundCylinder;
Cone, RoundCone
);
#[cfg(feature = "dim3")]
#[cfg(feature = "std")]
impl_shape_for_round_shape!(ConvexPolyhedron, RoundConvexPolyhedron);
| 28.984342 | 98 | 0.606365 |
03dff108770413c0959f4c24fbf8d6eb3a468bfc | 154,090 | //! This module contains the "cleaned" pieces of the AST, and the functions
//! that clean them.
pub mod inline;
pub mod cfg;
mod simplify;
mod auto_trait;
mod blanket_impl;
pub mod def_ctor;
use rustc_data_structures::indexed_vec::{IndexVec, Idx};
use rustc_data_structures::sync::Lrc;
use rustc_target::spec::abi::Abi;
use rustc_typeck::hir_ty_to_ty;
use rustc::infer::region_constraints::{RegionConstraintData, Constraint};
use rustc::middle::resolve_lifetime as rl;
use rustc::middle::lang_items;
use rustc::middle::stability;
use rustc::mir::interpret::GlobalId;
use rustc::hir::{self, GenericArg, HirVec};
use rustc::hir::def::{self, Def, CtorKind};
use rustc::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
use rustc::ty::subst::Substs;
use rustc::ty::{self, TyCtxt, Region, RegionVid, Ty, AdtKind};
use rustc::ty::fold::TypeFolder;
use rustc::ty::layout::VariantIdx;
use rustc::util::nodemap::{FxHashMap, FxHashSet};
use syntax::ast::{self, AttrStyle, Ident};
use syntax::attr;
use syntax::ext::base::MacroKind;
use syntax::source_map::{dummy_spanned, Spanned};
use syntax::ptr::P;
use syntax::symbol::keywords::{self, Keyword};
use syntax::symbol::InternedString;
use syntax_pos::{self, DUMMY_SP, Pos, FileName};
use std::collections::hash_map::Entry;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::default::Default;
use std::{mem, slice, vec};
use std::iter::{FromIterator, once};
use std::rc::Rc;
use std::str::FromStr;
use std::cell::RefCell;
use std::sync::Arc;
use std::u32;
use parking_lot::ReentrantMutex;
use crate::core::{self, DocContext};
use crate::doctree;
use crate::visit_ast;
use crate::html::render::{cache, ExternalLocation};
use crate::html::item_type::ItemType;
use self::cfg::Cfg;
use self::auto_trait::AutoTraitFinder;
use self::blanket_impl::BlanketImplFinder;
pub use self::Type::*;
pub use self::Mutability::*;
pub use self::ItemEnum::*;
pub use self::SelfTy::*;
pub use self::FunctionRetTy::*;
pub use self::Visibility::{Public, Inherited};
thread_local!(pub static MAX_DEF_ID: RefCell<FxHashMap<CrateNum, DefId>> = Default::default());
const FN_OUTPUT_NAME: &'static str = "Output";
// extract the stability index for a node from tcx, if possible
fn get_stability(cx: &DocContext<'_, '_, '_>, def_id: DefId) -> Option<Stability> {
cx.tcx.lookup_stability(def_id).clean(cx)
}
fn get_deprecation(cx: &DocContext<'_, '_, '_>, def_id: DefId) -> Option<Deprecation> {
cx.tcx.lookup_deprecation(def_id).clean(cx)
}
pub trait Clean<T> {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> T;
}
impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Vec<U> {
self.iter().map(|x| x.clean(cx)).collect()
}
}
impl<T: Clean<U>, U, V: Idx> Clean<IndexVec<V, U>> for IndexVec<V, T> {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> IndexVec<V, U> {
self.iter().map(|x| x.clean(cx)).collect()
}
}
impl<T: Clean<U>, U> Clean<U> for P<T> {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> U {
(**self).clean(cx)
}
}
impl<T: Clean<U>, U> Clean<U> for Rc<T> {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> U {
(**self).clean(cx)
}
}
impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Option<U> {
self.as_ref().map(|v| v.clean(cx))
}
}
impl<T, U> Clean<U> for ty::Binder<T> where T: Clean<U> {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> U {
self.skip_binder().clean(cx)
}
}
impl<T: Clean<U>, U> Clean<Vec<U>> for P<[T]> {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Vec<U> {
self.iter().map(|x| x.clean(cx)).collect()
}
}
#[derive(Clone, Debug)]
pub struct Crate {
pub name: String,
pub version: Option<String>,
pub src: FileName,
pub module: Option<Item>,
pub externs: Vec<(CrateNum, ExternalCrate)>,
pub primitives: Vec<(DefId, PrimitiveType, Attributes)>,
// These are later on moved into `CACHEKEY`, leaving the map empty.
// Only here so that they can be filtered through the rustdoc passes.
pub external_traits: Arc<ReentrantMutex<RefCell<FxHashMap<DefId, Trait>>>>,
pub masked_crates: FxHashSet<CrateNum>,
}
impl<'a, 'tcx, 'rcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx, 'rcx> {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Crate {
use crate::visit_lib::LibEmbargoVisitor;
{
let mut r = cx.renderinfo.borrow_mut();
r.deref_trait_did = cx.tcx.lang_items().deref_trait();
r.deref_mut_trait_did = cx.tcx.lang_items().deref_mut_trait();
r.owned_box_did = cx.tcx.lang_items().owned_box();
}
let mut externs = Vec::new();
for &cnum in cx.tcx.crates().iter() {
externs.push((cnum, cnum.clean(cx)));
// Analyze doc-reachability for extern items
LibEmbargoVisitor::new(cx).visit_lib(cnum);
}
externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
// Clean the crate, translating the entire libsyntax AST to one that is
// understood by rustdoc.
let mut module = self.module.clean(cx);
let mut masked_crates = FxHashSet::default();
match module.inner {
ModuleItem(ref module) => {
for it in &module.items {
// `compiler_builtins` should be masked too, but we can't apply
// `#[doc(masked)]` to the injected `extern crate` because it's unstable.
if it.is_extern_crate()
&& (it.attrs.has_doc_flag("masked")
|| self.cx.tcx.is_compiler_builtins(it.def_id.krate))
{
masked_crates.insert(it.def_id.krate);
}
}
}
_ => unreachable!(),
}
let ExternalCrate { name, src, primitives, keywords, .. } = LOCAL_CRATE.clean(cx);
{
let m = match module.inner {
ModuleItem(ref mut m) => m,
_ => unreachable!(),
};
m.items.extend(primitives.iter().map(|&(def_id, prim, ref attrs)| {
Item {
source: Span::empty(),
name: Some(prim.to_url_str().to_string()),
attrs: attrs.clone(),
visibility: Some(Public),
stability: get_stability(cx, def_id),
deprecation: get_deprecation(cx, def_id),
def_id,
inner: PrimitiveItem(prim),
}
}));
m.items.extend(keywords.into_iter().map(|(def_id, kw, attrs)| {
Item {
source: Span::empty(),
name: Some(kw.clone()),
attrs: attrs,
visibility: Some(Public),
stability: get_stability(cx, def_id),
deprecation: get_deprecation(cx, def_id),
def_id,
inner: KeywordItem(kw),
}
}));
}
Crate {
name,
version: None,
src,
module: Some(module),
externs,
primitives,
external_traits: cx.external_traits.clone(),
masked_crates,
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct ExternalCrate {
pub name: String,
pub src: FileName,
pub attrs: Attributes,
pub primitives: Vec<(DefId, PrimitiveType, Attributes)>,
pub keywords: Vec<(DefId, String, Attributes)>,
}
impl Clean<ExternalCrate> for CrateNum {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> ExternalCrate {
let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
let krate_span = cx.tcx.def_span(root);
let krate_src = cx.sess().source_map().span_to_filename(krate_span);
// Collect all inner modules which are tagged as implementations of
// primitives.
//
// Note that this loop only searches the top-level items of the crate,
// and this is intentional. If we were to search the entire crate for an
// item tagged with `#[doc(primitive)]` then we would also have to
// search the entirety of external modules for items tagged
// `#[doc(primitive)]`, which is a pretty inefficient process (decoding
// all that metadata unconditionally).
//
// In order to keep the metadata load under control, the
// `#[doc(primitive)]` feature is explicitly designed to only allow the
// primitive tags to show up as the top level items in a crate.
//
// Also note that this does not attempt to deal with modules tagged
// duplicately for the same primitive. This is handled later on when
// rendering by delegating everything to a hash map.
let as_primitive = |def: Def| {
if let Def::Mod(def_id) = def {
let attrs = cx.tcx.get_attrs(def_id).clean(cx);
let mut prim = None;
for attr in attrs.lists("doc") {
if let Some(v) = attr.value_str() {
if attr.check_name("primitive") {
prim = PrimitiveType::from_str(&v.as_str());
if prim.is_some() {
break;
}
// FIXME: should warn on unknown primitives?
}
}
}
return prim.map(|p| (def_id, p, attrs));
}
None
};
let primitives = if root.is_local() {
cx.tcx.hir().krate().module.item_ids.iter().filter_map(|&id| {
let item = cx.tcx.hir().expect_item(id.id);
match item.node {
hir::ItemKind::Mod(_) => {
as_primitive(Def::Mod(cx.tcx.hir().local_def_id(id.id)))
}
hir::ItemKind::Use(ref path, hir::UseKind::Single)
if item.vis.node.is_pub() => {
as_primitive(path.def).map(|(_, prim, attrs)| {
// Pretend the primitive is local.
(cx.tcx.hir().local_def_id(id.id), prim, attrs)
})
}
_ => None
}
}).collect()
} else {
cx.tcx.item_children(root).iter().map(|item| item.def)
.filter_map(as_primitive).collect()
};
let as_keyword = |def: Def| {
if let Def::Mod(def_id) = def {
let attrs = cx.tcx.get_attrs(def_id).clean(cx);
let mut keyword = None;
for attr in attrs.lists("doc") {
if let Some(v) = attr.value_str() {
if attr.check_name("keyword") {
keyword = Keyword::from_str(&v.as_str()).ok()
.map(|x| x.name().to_string());
if keyword.is_some() {
break
}
// FIXME: should warn on unknown keywords?
}
}
}
return keyword.map(|p| (def_id, p, attrs));
}
None
};
let keywords = if root.is_local() {
cx.tcx.hir().krate().module.item_ids.iter().filter_map(|&id| {
let item = cx.tcx.hir().expect_item(id.id);
match item.node {
hir::ItemKind::Mod(_) => {
as_keyword(Def::Mod(cx.tcx.hir().local_def_id(id.id)))
}
hir::ItemKind::Use(ref path, hir::UseKind::Single)
if item.vis.node.is_pub() => {
as_keyword(path.def).map(|(_, prim, attrs)| {
(cx.tcx.hir().local_def_id(id.id), prim, attrs)
})
}
_ => None
}
}).collect()
} else {
cx.tcx.item_children(root).iter().map(|item| item.def)
.filter_map(as_keyword).collect()
};
ExternalCrate {
name: cx.tcx.crate_name(*self).to_string(),
src: krate_src,
attrs: cx.tcx.get_attrs(root).clean(cx),
primitives,
keywords,
}
}
}
/// Anything with a source location and set of attributes and, optionally, a
/// name. That is, anything that can be documented. This doesn't correspond
/// directly to the AST's concept of an item; it's a strict superset.
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Item {
/// Stringified span
pub source: Span,
/// Not everything has a name. E.g., impls
pub name: Option<String>,
pub attrs: Attributes,
pub inner: ItemEnum,
pub visibility: Option<Visibility>,
pub def_id: DefId,
pub stability: Option<Stability>,
pub deprecation: Option<Deprecation>,
}
impl fmt::Debug for Item {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
let fake = MAX_DEF_ID.with(|m| m.borrow().get(&self.def_id.krate)
.map(|id| self.def_id >= *id).unwrap_or(false));
let def_id: &dyn fmt::Debug = if fake { &"**FAKE**" } else { &self.def_id };
fmt.debug_struct("Item")
.field("source", &self.source)
.field("name", &self.name)
.field("attrs", &self.attrs)
.field("inner", &self.inner)
.field("visibility", &self.visibility)
.field("def_id", def_id)
.field("stability", &self.stability)
.field("deprecation", &self.deprecation)
.finish()
}
}
impl Item {
/// Finds the `doc` attribute as a NameValue and returns the corresponding
/// value found.
pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
self.attrs.doc_value()
}
/// Finds all `doc` attributes as NameValues and returns their corresponding values, joined
/// with newlines.
pub fn collapsed_doc_value(&self) -> Option<String> {
self.attrs.collapsed_doc_value()
}
pub fn links(&self) -> Vec<(String, String)> {
self.attrs.links(&self.def_id.krate)
}
pub fn is_crate(&self) -> bool {
match self.inner {
StrippedItem(box ModuleItem(Module { is_crate: true, ..})) |
ModuleItem(Module { is_crate: true, ..}) => true,
_ => false,
}
}
pub fn is_mod(&self) -> bool {
self.type_() == ItemType::Module
}
pub fn is_trait(&self) -> bool {
self.type_() == ItemType::Trait
}
pub fn is_struct(&self) -> bool {
self.type_() == ItemType::Struct
}
pub fn is_enum(&self) -> bool {
self.type_() == ItemType::Enum
}
pub fn is_associated_type(&self) -> bool {
self.type_() == ItemType::AssociatedType
}
pub fn is_associated_const(&self) -> bool {
self.type_() == ItemType::AssociatedConst
}
pub fn is_method(&self) -> bool {
self.type_() == ItemType::Method
}
pub fn is_ty_method(&self) -> bool {
self.type_() == ItemType::TyMethod
}
pub fn is_typedef(&self) -> bool {
self.type_() == ItemType::Typedef
}
pub fn is_primitive(&self) -> bool {
self.type_() == ItemType::Primitive
}
pub fn is_union(&self) -> bool {
self.type_() == ItemType::Union
}
pub fn is_import(&self) -> bool {
self.type_() == ItemType::Import
}
pub fn is_extern_crate(&self) -> bool {
self.type_() == ItemType::ExternCrate
}
pub fn is_keyword(&self) -> bool {
self.type_() == ItemType::Keyword
}
pub fn is_stripped(&self) -> bool {
match self.inner { StrippedItem(..) => true, _ => false }
}
pub fn has_stripped_fields(&self) -> Option<bool> {
match self.inner {
StructItem(ref _struct) => Some(_struct.fields_stripped),
UnionItem(ref union) => Some(union.fields_stripped),
VariantItem(Variant { kind: VariantKind::Struct(ref vstruct)} ) => {
Some(vstruct.fields_stripped)
},
_ => None,
}
}
pub fn stability_class(&self) -> Option<String> {
self.stability.as_ref().and_then(|ref s| {
let mut classes = Vec::with_capacity(2);
if s.level == stability::Unstable {
classes.push("unstable");
}
if s.deprecation.is_some() {
classes.push("deprecated");
}
if classes.len() != 0 {
Some(classes.join(" "))
} else {
None
}
})
}
pub fn stable_since(&self) -> Option<&str> {
self.stability.as_ref().map(|s| &s.since[..])
}
pub fn is_non_exhaustive(&self) -> bool {
self.attrs.other_attrs.iter()
.any(|a| a.name().as_str() == "non_exhaustive")
}
/// Returns a documentation-level item type from the item.
pub fn type_(&self) -> ItemType {
ItemType::from(self)
}
/// Returns the info in the item's `#[deprecated]` or `#[rustc_deprecated]` attributes.
///
/// If the item is not deprecated, returns `None`.
pub fn deprecation(&self) -> Option<&Deprecation> {
self.deprecation
.as_ref()
.or_else(|| self.stability.as_ref().and_then(|s| s.deprecation.as_ref()))
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum ItemEnum {
ExternCrateItem(String, Option<String>),
ImportItem(Import),
StructItem(Struct),
UnionItem(Union),
EnumItem(Enum),
FunctionItem(Function),
ModuleItem(Module),
TypedefItem(Typedef, bool /* is associated type */),
ExistentialItem(Existential, bool /* is associated type */),
StaticItem(Static),
ConstantItem(Constant),
TraitItem(Trait),
TraitAliasItem(TraitAlias),
ImplItem(Impl),
/// A method signature only. Used for required methods in traits (ie,
/// non-default-methods).
TyMethodItem(TyMethod),
/// A method with a body.
MethodItem(Method),
StructFieldItem(Type),
VariantItem(Variant),
/// `fn`s from an extern block
ForeignFunctionItem(Function),
/// `static`s from an extern block
ForeignStaticItem(Static),
/// `type`s from an extern block
ForeignTypeItem,
MacroItem(Macro),
ProcMacroItem(ProcMacro),
PrimitiveItem(PrimitiveType),
AssociatedConstItem(Type, Option<String>),
AssociatedTypeItem(Vec<GenericBound>, Option<Type>),
/// An item that has been stripped by a rustdoc pass
StrippedItem(Box<ItemEnum>),
KeywordItem(String),
}
impl ItemEnum {
pub fn generics(&self) -> Option<&Generics> {
Some(match *self {
ItemEnum::StructItem(ref s) => &s.generics,
ItemEnum::EnumItem(ref e) => &e.generics,
ItemEnum::FunctionItem(ref f) => &f.generics,
ItemEnum::TypedefItem(ref t, _) => &t.generics,
ItemEnum::ExistentialItem(ref t, _) => &t.generics,
ItemEnum::TraitItem(ref t) => &t.generics,
ItemEnum::ImplItem(ref i) => &i.generics,
ItemEnum::TyMethodItem(ref i) => &i.generics,
ItemEnum::MethodItem(ref i) => &i.generics,
ItemEnum::ForeignFunctionItem(ref f) => &f.generics,
ItemEnum::TraitAliasItem(ref ta) => &ta.generics,
_ => return None,
})
}
pub fn is_associated(&self) -> bool {
match *self {
ItemEnum::TypedefItem(_, _) |
ItemEnum::AssociatedTypeItem(_, _) => true,
_ => false,
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Module {
pub items: Vec<Item>,
pub is_crate: bool,
}
impl Clean<Item> for doctree::Module {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
let name = if self.name.is_some() {
self.name.expect("No name provided").clean(cx)
} else {
String::new()
};
// maintain a stack of mod ids, for doc comment path resolution
// but we also need to resolve the module's own docs based on whether its docs were written
// inside or outside the module, so check for that
let attrs = self.attrs.clean(cx);
let mut items: Vec<Item> = vec![];
items.extend(self.extern_crates.iter().flat_map(|x| x.clean(cx)));
items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
items.extend(self.structs.iter().map(|x| x.clean(cx)));
items.extend(self.unions.iter().map(|x| x.clean(cx)));
items.extend(self.enums.iter().map(|x| x.clean(cx)));
items.extend(self.fns.iter().map(|x| x.clean(cx)));
items.extend(self.foreigns.iter().flat_map(|x| x.clean(cx)));
items.extend(self.mods.iter().map(|x| x.clean(cx)));
items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
items.extend(self.existentials.iter().map(|x| x.clean(cx)));
items.extend(self.statics.iter().map(|x| x.clean(cx)));
items.extend(self.constants.iter().map(|x| x.clean(cx)));
items.extend(self.traits.iter().map(|x| x.clean(cx)));
items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
items.extend(self.macros.iter().map(|x| x.clean(cx)));
items.extend(self.proc_macros.iter().map(|x| x.clean(cx)));
items.extend(self.trait_aliases.iter().map(|x| x.clean(cx)));
// determine if we should display the inner contents or
// the outer `mod` item for the source code.
let whence = {
let cm = cx.sess().source_map();
let outer = cm.lookup_char_pos(self.where_outer.lo());
let inner = cm.lookup_char_pos(self.where_inner.lo());
if outer.file.start_pos == inner.file.start_pos {
// mod foo { ... }
self.where_outer
} else {
// mod foo; (and a separate SourceFile for the contents)
self.where_inner
}
};
Item {
name: Some(name),
attrs,
source: whence.clean(cx),
visibility: self.vis.clean(cx),
stability: self.stab.clean(cx),
deprecation: self.depr.clean(cx),
def_id: cx.tcx.hir().local_def_id(self.id),
inner: ModuleItem(Module {
is_crate: self.is_crate,
items,
})
}
}
}
pub struct ListAttributesIter<'a> {
attrs: slice::Iter<'a, ast::Attribute>,
current_list: vec::IntoIter<ast::NestedMetaItem>,
name: &'a str
}
impl<'a> Iterator for ListAttributesIter<'a> {
type Item = ast::NestedMetaItem;
fn next(&mut self) -> Option<Self::Item> {
if let Some(nested) = self.current_list.next() {
return Some(nested);
}
for attr in &mut self.attrs {
if let Some(list) = attr.meta_item_list() {
if attr.check_name(self.name) {
self.current_list = list.into_iter();
if let Some(nested) = self.current_list.next() {
return Some(nested);
}
}
}
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
let lower = self.current_list.len();
(lower, None)
}
}
pub trait AttributesExt {
/// Finds an attribute as List and returns the list of attributes nested inside.
fn lists<'a>(&'a self, name: &'a str) -> ListAttributesIter<'a>;
}
impl AttributesExt for [ast::Attribute] {
fn lists<'a>(&'a self, name: &'a str) -> ListAttributesIter<'a> {
ListAttributesIter {
attrs: self.iter(),
current_list: Vec::new().into_iter(),
name,
}
}
}
pub trait NestedAttributesExt {
/// Returns `true` if the attribute list contains a specific `Word`
fn has_word(self, word: &str) -> bool;
}
impl<I: IntoIterator<Item=ast::NestedMetaItem>> NestedAttributesExt for I {
fn has_word(self, word: &str) -> bool {
self.into_iter().any(|attr| attr.is_word() && attr.check_name(word))
}
}
/// A portion of documentation, extracted from a `#[doc]` attribute.
///
/// Each variant contains the line number within the complete doc-comment where the fragment
/// starts, as well as the Span where the corresponding doc comment or attribute is located.
///
/// Included files are kept separate from inline doc comments so that proper line-number
/// information can be given when a doctest fails. Sugared doc comments and "raw" doc comments are
/// kept separate because of issue #42760.
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
pub enum DocFragment {
/// A doc fragment created from a `///` or `//!` doc comment.
SugaredDoc(usize, syntax_pos::Span, String),
/// A doc fragment created from a "raw" `#[doc=""]` attribute.
RawDoc(usize, syntax_pos::Span, String),
/// A doc fragment created from a `#[doc(include="filename")]` attribute. Contains both the
/// given filename and the file contents.
Include(usize, syntax_pos::Span, String, String),
}
impl DocFragment {
pub fn as_str(&self) -> &str {
match *self {
DocFragment::SugaredDoc(_, _, ref s) => &s[..],
DocFragment::RawDoc(_, _, ref s) => &s[..],
DocFragment::Include(_, _, _, ref s) => &s[..],
}
}
pub fn span(&self) -> syntax_pos::Span {
match *self {
DocFragment::SugaredDoc(_, span, _) |
DocFragment::RawDoc(_, span, _) |
DocFragment::Include(_, span, _, _) => span,
}
}
}
impl<'a> FromIterator<&'a DocFragment> for String {
fn from_iter<T>(iter: T) -> Self
where
T: IntoIterator<Item = &'a DocFragment>
{
iter.into_iter().fold(String::new(), |mut acc, frag| {
if !acc.is_empty() {
acc.push('\n');
}
match *frag {
DocFragment::SugaredDoc(_, _, ref docs)
| DocFragment::RawDoc(_, _, ref docs)
| DocFragment::Include(_, _, _, ref docs) =>
acc.push_str(docs),
}
acc
})
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
pub struct Attributes {
pub doc_strings: Vec<DocFragment>,
pub other_attrs: Vec<ast::Attribute>,
pub cfg: Option<Arc<Cfg>>,
pub span: Option<syntax_pos::Span>,
/// map from Rust paths to resolved defs and potential URL fragments
pub links: Vec<(String, Option<DefId>, Option<String>)>,
pub inner_docs: bool,
}
impl Attributes {
/// Extracts the content from an attribute `#[doc(cfg(content))]`.
fn extract_cfg(mi: &ast::MetaItem) -> Option<&ast::MetaItem> {
use syntax::ast::NestedMetaItemKind::MetaItem;
if let ast::MetaItemKind::List(ref nmis) = mi.node {
if nmis.len() == 1 {
if let MetaItem(ref cfg_mi) = nmis[0].node {
if cfg_mi.check_name("cfg") {
if let ast::MetaItemKind::List(ref cfg_nmis) = cfg_mi.node {
if cfg_nmis.len() == 1 {
if let MetaItem(ref content_mi) = cfg_nmis[0].node {
return Some(content_mi);
}
}
}
}
}
}
}
None
}
/// Reads a `MetaItem` from within an attribute, looks for whether it is a
/// `#[doc(include="file")]`, and returns the filename and contents of the file as loaded from
/// its expansion.
fn extract_include(mi: &ast::MetaItem)
-> Option<(String, String)>
{
mi.meta_item_list().and_then(|list| {
for meta in list {
if meta.check_name("include") {
// the actual compiled `#[doc(include="filename")]` gets expanded to
// `#[doc(include(file="filename", contents="file contents")]` so we need to
// look for that instead
return meta.meta_item_list().and_then(|list| {
let mut filename: Option<String> = None;
let mut contents: Option<String> = None;
for it in list {
if it.check_name("file") {
if let Some(name) = it.value_str() {
filename = Some(name.to_string());
}
} else if it.check_name("contents") {
if let Some(docs) = it.value_str() {
contents = Some(docs.to_string());
}
}
}
if let (Some(filename), Some(contents)) = (filename, contents) {
Some((filename, contents))
} else {
None
}
});
}
}
None
})
}
pub fn has_doc_flag(&self, flag: &str) -> bool {
for attr in &self.other_attrs {
if !attr.check_name("doc") { continue; }
if let Some(items) = attr.meta_item_list() {
if items.iter().filter_map(|i| i.meta_item()).any(|it| it.check_name(flag)) {
return true;
}
}
}
false
}
pub fn from_ast(diagnostic: &::errors::Handler,
attrs: &[ast::Attribute]) -> Attributes {
let mut doc_strings = vec![];
let mut sp = None;
let mut cfg = Cfg::True;
let mut doc_line = 0;
let other_attrs = attrs.iter().filter_map(|attr| {
attr.with_desugared_doc(|attr| {
if attr.check_name("doc") {
if let Some(mi) = attr.meta() {
if let Some(value) = mi.value_str() {
// Extracted #[doc = "..."]
let value = value.to_string();
let line = doc_line;
doc_line += value.lines().count();
if attr.is_sugared_doc {
doc_strings.push(DocFragment::SugaredDoc(line, attr.span, value));
} else {
doc_strings.push(DocFragment::RawDoc(line, attr.span, value));
}
if sp.is_none() {
sp = Some(attr.span);
}
return None;
} else if let Some(cfg_mi) = Attributes::extract_cfg(&mi) {
// Extracted #[doc(cfg(...))]
match Cfg::parse(cfg_mi) {
Ok(new_cfg) => cfg &= new_cfg,
Err(e) => diagnostic.span_err(e.span, e.msg),
}
return None;
} else if let Some((filename, contents)) = Attributes::extract_include(&mi)
{
let line = doc_line;
doc_line += contents.lines().count();
doc_strings.push(DocFragment::Include(line,
attr.span,
filename,
contents));
}
}
}
Some(attr.clone())
})
}).collect();
// treat #[target_feature(enable = "feat")] attributes as if they were
// #[doc(cfg(target_feature = "feat"))] attributes as well
for attr in attrs.lists("target_feature") {
if attr.check_name("enable") {
if let Some(feat) = attr.value_str() {
let meta = attr::mk_name_value_item_str(Ident::from_str("target_feature"),
dummy_spanned(feat));
if let Ok(feat_cfg) = Cfg::parse(&meta) {
cfg &= feat_cfg;
}
}
}
}
let inner_docs = attrs.iter()
.filter(|a| a.check_name("doc"))
.next()
.map_or(true, |a| a.style == AttrStyle::Inner);
Attributes {
doc_strings,
other_attrs,
cfg: if cfg == Cfg::True { None } else { Some(Arc::new(cfg)) },
span: sp,
links: vec![],
inner_docs,
}
}
/// Finds the `doc` attribute as a NameValue and returns the corresponding
/// value found.
pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
self.doc_strings.first().map(|s| s.as_str())
}
/// Finds all `doc` attributes as NameValues and returns their corresponding values, joined
/// with newlines.
pub fn collapsed_doc_value(&self) -> Option<String> {
if !self.doc_strings.is_empty() {
Some(self.doc_strings.iter().collect())
} else {
None
}
}
/// Gets links as a vector
///
/// Cache must be populated before call
pub fn links(&self, krate: &CrateNum) -> Vec<(String, String)> {
use crate::html::format::href;
self.links.iter().filter_map(|&(ref s, did, ref fragment)| {
match did {
Some(did) => {
if let Some((mut href, ..)) = href(did) {
if let Some(ref fragment) = *fragment {
href.push_str("#");
href.push_str(fragment);
}
Some((s.clone(), href))
} else {
None
}
}
None => {
if let Some(ref fragment) = *fragment {
let cache = cache();
let url = match cache.extern_locations.get(krate) {
Some(&(_, ref src, ExternalLocation::Local)) =>
src.to_str().expect("invalid file path"),
Some(&(_, _, ExternalLocation::Remote(ref s))) => s,
Some(&(_, _, ExternalLocation::Unknown)) | None =>
"https://doc.rust-lang.org/nightly",
};
// This is a primitive so the url is done "by hand".
let tail = fragment.find('#').unwrap_or_else(|| fragment.len());
Some((s.clone(),
format!("{}{}std/primitive.{}.html{}",
url,
if !url.ends_with('/') { "/" } else { "" },
&fragment[..tail],
&fragment[tail..])))
} else {
panic!("This isn't a primitive?!");
}
}
}
}).collect()
}
}
impl PartialEq for Attributes {
fn eq(&self, rhs: &Self) -> bool {
self.doc_strings == rhs.doc_strings &&
self.cfg == rhs.cfg &&
self.span == rhs.span &&
self.links == rhs.links &&
self.other_attrs.iter().map(|attr| attr.id).eq(rhs.other_attrs.iter().map(|attr| attr.id))
}
}
impl Eq for Attributes {}
impl Hash for Attributes {
fn hash<H: Hasher>(&self, hasher: &mut H) {
self.doc_strings.hash(hasher);
self.cfg.hash(hasher);
self.span.hash(hasher);
self.links.hash(hasher);
for attr in &self.other_attrs {
attr.id.hash(hasher);
}
}
}
impl AttributesExt for Attributes {
fn lists<'a>(&'a self, name: &'a str) -> ListAttributesIter<'a> {
self.other_attrs.lists(name)
}
}
impl Clean<Attributes> for [ast::Attribute] {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Attributes {
Attributes::from_ast(cx.sess().diagnostic(), self)
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
pub enum GenericBound {
TraitBound(PolyTrait, hir::TraitBoundModifier),
Outlives(Lifetime),
}
impl GenericBound {
fn maybe_sized(cx: &DocContext<'_, '_, '_>) -> GenericBound {
let did = cx.tcx.require_lang_item(lang_items::SizedTraitLangItem);
let empty = cx.tcx.intern_substs(&[]);
let path = external_path(cx, &cx.tcx.item_name(did).as_str(),
Some(did), false, vec![], empty);
inline::record_extern_fqn(cx, did, TypeKind::Trait);
GenericBound::TraitBound(PolyTrait {
trait_: ResolvedPath {
path,
typarams: None,
did,
is_generic: false,
},
generic_params: Vec::new(),
}, hir::TraitBoundModifier::Maybe)
}
fn is_sized_bound(&self, cx: &DocContext<'_, '_, '_>) -> bool {
use rustc::hir::TraitBoundModifier as TBM;
if let GenericBound::TraitBound(PolyTrait { ref trait_, .. }, TBM::None) = *self {
if trait_.def_id() == cx.tcx.lang_items().sized_trait() {
return true;
}
}
false
}
fn get_poly_trait(&self) -> Option<PolyTrait> {
if let GenericBound::TraitBound(ref p, _) = *self {
return Some(p.clone())
}
None
}
fn get_trait_type(&self) -> Option<Type> {
if let GenericBound::TraitBound(PolyTrait { ref trait_, .. }, _) = *self {
return Some(trait_.clone());
}
None
}
}
impl Clean<GenericBound> for hir::GenericBound {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> GenericBound {
match *self {
hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
hir::GenericBound::Trait(ref t, modifier) => {
GenericBound::TraitBound(t.clean(cx), modifier)
}
}
}
}
fn external_generic_args(cx: &DocContext<'_, '_, '_>, trait_did: Option<DefId>, has_self: bool,
bindings: Vec<TypeBinding>, substs: &Substs<'_>) -> GenericArgs {
let lifetimes = substs.regions().filter_map(|v| v.clean(cx)).collect();
let types = substs.types().skip(has_self as usize).collect::<Vec<_>>();
match trait_did {
// Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
Some(did) if cx.tcx.lang_items().fn_trait_kind(did).is_some() => {
assert_eq!(types.len(), 1);
let inputs = match types[0].sty {
ty::Tuple(ref tys) => tys.iter().map(|t| t.clean(cx)).collect(),
_ => {
return GenericArgs::AngleBracketed {
lifetimes,
types: types.clean(cx),
bindings,
}
}
};
let output = None;
// FIXME(#20299) return type comes from a projection now
// match types[1].sty {
// ty::Tuple(ref v) if v.is_empty() => None, // -> ()
// _ => Some(types[1].clean(cx))
// };
GenericArgs::Parenthesized {
inputs,
output,
}
},
_ => {
GenericArgs::AngleBracketed {
lifetimes,
types: types.clean(cx),
bindings,
}
}
}
}
// trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
// from Fn<(A, B,), C> to Fn(A, B) -> C
fn external_path(cx: &DocContext<'_, '_, '_>, name: &str, trait_did: Option<DefId>, has_self: bool,
bindings: Vec<TypeBinding>, substs: &Substs<'_>) -> Path {
Path {
global: false,
def: Def::Err,
segments: vec![PathSegment {
name: name.to_string(),
args: external_generic_args(cx, trait_did, has_self, bindings, substs)
}],
}
}
impl<'a, 'tcx> Clean<GenericBound> for (&'a ty::TraitRef<'tcx>, Vec<TypeBinding>) {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> GenericBound {
let (trait_ref, ref bounds) = *self;
inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait);
let path = external_path(cx, &cx.tcx.item_name(trait_ref.def_id).as_str(),
Some(trait_ref.def_id), true, bounds.clone(), trait_ref.substs);
debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
// collect any late bound regions
let mut late_bounds = vec![];
for ty_s in trait_ref.input_types().skip(1) {
if let ty::Tuple(ts) = ty_s.sty {
for &ty_s in ts {
if let ty::Ref(ref reg, _, _) = ty_s.sty {
if let &ty::RegionKind::ReLateBound(..) = *reg {
debug!(" hit an ReLateBound {:?}", reg);
if let Some(Lifetime(name)) = reg.clean(cx) {
late_bounds.push(GenericParamDef {
name,
kind: GenericParamDefKind::Lifetime,
});
}
}
}
}
}
}
GenericBound::TraitBound(
PolyTrait {
trait_: ResolvedPath {
path,
typarams: None,
did: trait_ref.def_id,
is_generic: false,
},
generic_params: late_bounds,
},
hir::TraitBoundModifier::None
)
}
}
impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> GenericBound {
(self, vec![]).clean(cx)
}
}
impl<'tcx> Clean<Option<Vec<GenericBound>>> for Substs<'tcx> {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Option<Vec<GenericBound>> {
let mut v = Vec::new();
v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
v.extend(self.types().map(|t| GenericBound::TraitBound(PolyTrait {
trait_: t.clean(cx),
generic_params: Vec::new(),
}, hir::TraitBoundModifier::None)));
if !v.is_empty() {Some(v)} else {None}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
pub struct Lifetime(String);
impl Lifetime {
pub fn get_ref<'a>(&'a self) -> &'a str {
let Lifetime(ref s) = *self;
let s: &'a str = s;
s
}
pub fn statik() -> Lifetime {
Lifetime("'static".to_string())
}
}
impl Clean<Lifetime> for hir::Lifetime {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Lifetime {
if self.id != ast::DUMMY_NODE_ID {
let def = cx.tcx.named_region(self.hir_id);
match def {
Some(rl::Region::EarlyBound(_, node_id, _)) |
Some(rl::Region::LateBound(_, node_id, _)) |
Some(rl::Region::Free(_, node_id)) => {
if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
return lt;
}
}
_ => {}
}
}
Lifetime(self.name.ident().to_string())
}
}
impl Clean<Lifetime> for hir::GenericParam {
fn clean(&self, _: &DocContext<'_, '_, '_>) -> Lifetime {
match self.kind {
hir::GenericParamKind::Lifetime { .. } => {
if self.bounds.len() > 0 {
let mut bounds = self.bounds.iter().map(|bound| match bound {
hir::GenericBound::Outlives(lt) => lt,
_ => panic!(),
});
let name = bounds.next().expect("no more bounds").name.ident();
let mut s = format!("{}: {}", self.name.ident(), name);
for bound in bounds {
s.push_str(&format!(" + {}", bound.name.ident()));
}
Lifetime(s)
} else {
Lifetime(self.name.ident().to_string())
}
}
_ => panic!(),
}
}
}
impl Clean<Constant> for hir::ConstArg {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Constant {
Constant {
type_: cx.tcx.type_of(cx.tcx.hir().body_owner_def_id(self.value.body)).clean(cx),
expr: print_const_expr(cx, self.value.body),
}
}
}
impl<'tcx> Clean<Lifetime> for ty::GenericParamDef {
fn clean(&self, _cx: &DocContext<'_, '_, '_>) -> Lifetime {
Lifetime(self.name.to_string())
}
}
impl Clean<Option<Lifetime>> for ty::RegionKind {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Option<Lifetime> {
match *self {
ty::ReStatic => Some(Lifetime::statik()),
ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
ty::ReLateBound(..) |
ty::ReFree(..) |
ty::ReScope(..) |
ty::ReVar(..) |
ty::RePlaceholder(..) |
ty::ReEmpty |
ty::ReClosureBound(_) |
ty::ReErased => {
debug!("Cannot clean region {:?}", self);
None
}
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
pub enum WherePredicate {
BoundPredicate { ty: Type, bounds: Vec<GenericBound> },
RegionPredicate { lifetime: Lifetime, bounds: Vec<GenericBound> },
EqPredicate { lhs: Type, rhs: Type },
}
impl Clean<WherePredicate> for hir::WherePredicate {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> WherePredicate {
match *self {
hir::WherePredicate::BoundPredicate(ref wbp) => {
WherePredicate::BoundPredicate {
ty: wbp.bounded_ty.clean(cx),
bounds: wbp.bounds.clean(cx)
}
}
hir::WherePredicate::RegionPredicate(ref wrp) => {
WherePredicate::RegionPredicate {
lifetime: wrp.lifetime.clean(cx),
bounds: wrp.bounds.clean(cx)
}
}
hir::WherePredicate::EqPredicate(ref wrp) => {
WherePredicate::EqPredicate {
lhs: wrp.lhs_ty.clean(cx),
rhs: wrp.rhs_ty.clean(cx)
}
}
}
}
}
impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Option<WherePredicate> {
use rustc::ty::Predicate;
match *self {
Predicate::Trait(ref pred) => Some(pred.clean(cx)),
Predicate::Subtype(ref pred) => Some(pred.clean(cx)),
Predicate::RegionOutlives(ref pred) => pred.clean(cx),
Predicate::TypeOutlives(ref pred) => pred.clean(cx),
Predicate::Projection(ref pred) => Some(pred.clean(cx)),
Predicate::WellFormed(..) |
Predicate::ObjectSafe(..) |
Predicate::ClosureKind(..) |
Predicate::ConstEvaluatable(..) => panic!("not user writable"),
}
}
}
impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> WherePredicate {
WherePredicate::BoundPredicate {
ty: self.trait_ref.self_ty().clean(cx),
bounds: vec![self.trait_ref.clean(cx)]
}
}
}
impl<'tcx> Clean<WherePredicate> for ty::SubtypePredicate<'tcx> {
fn clean(&self, _cx: &DocContext<'_, '_, '_>) -> WherePredicate {
panic!("subtype predicates are an internal rustc artifact \
and should not be seen by rustdoc")
}
}
impl<'tcx> Clean<Option<WherePredicate>> for
ty::OutlivesPredicate<ty::Region<'tcx>,ty::Region<'tcx>> {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Option<WherePredicate> {
let ty::OutlivesPredicate(ref a, ref b) = *self;
match (a, b) {
(ty::ReEmpty, ty::ReEmpty) => {
return None;
},
_ => {}
}
Some(WherePredicate::RegionPredicate {
lifetime: a.clean(cx).expect("failed to clean lifetime"),
bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))]
})
}
}
impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Option<WherePredicate> {
let ty::OutlivesPredicate(ref ty, ref lt) = *self;
match lt {
ty::ReEmpty => return None,
_ => {}
}
Some(WherePredicate::BoundPredicate {
ty: ty.clean(cx),
bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))]
})
}
}
impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> WherePredicate {
WherePredicate::EqPredicate {
lhs: self.projection_ty.clean(cx),
rhs: self.ty.clean(cx)
}
}
}
impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Type {
let trait_ = match self.trait_ref(cx.tcx).clean(cx) {
GenericBound::TraitBound(t, _) => t.trait_,
GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
};
Type::QPath {
name: cx.tcx.associated_item(self.item_def_id).ident.name.clean(cx),
self_type: box self.self_ty().clean(cx),
trait_: box trait_
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
pub enum GenericParamDefKind {
Lifetime,
Type {
did: DefId,
bounds: Vec<GenericBound>,
default: Option<Type>,
synthetic: Option<hir::SyntheticTyParamKind>,
},
Const {
did: DefId,
ty: Type,
},
}
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
pub struct GenericParamDef {
pub name: String,
pub kind: GenericParamDefKind,
}
impl GenericParamDef {
pub fn is_synthetic_type_param(&self) -> bool {
match self.kind {
GenericParamDefKind::Lifetime |
GenericParamDefKind::Const { .. } => {
false
}
GenericParamDefKind::Type { ref synthetic, .. } => synthetic.is_some(),
}
}
}
impl<'tcx> Clean<GenericParamDef> for ty::GenericParamDef {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> GenericParamDef {
let (name, kind) = match self.kind {
ty::GenericParamDefKind::Lifetime => {
(self.name.to_string(), GenericParamDefKind::Lifetime)
}
ty::GenericParamDefKind::Type { has_default, .. } => {
cx.renderinfo.borrow_mut().external_typarams
.insert(self.def_id, self.name.clean(cx));
let default = if has_default {
Some(cx.tcx.type_of(self.def_id).clean(cx))
} else {
None
};
(self.name.clean(cx), GenericParamDefKind::Type {
did: self.def_id,
bounds: vec![], // These are filled in from the where-clauses.
default,
synthetic: None,
})
}
};
GenericParamDef {
name,
kind,
}
}
}
impl Clean<GenericParamDef> for hir::GenericParam {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> GenericParamDef {
let (name, kind) = match self.kind {
hir::GenericParamKind::Lifetime { .. } => {
let name = if self.bounds.len() > 0 {
let mut bounds = self.bounds.iter().map(|bound| match bound {
hir::GenericBound::Outlives(lt) => lt,
_ => panic!(),
});
let name = bounds.next().expect("no more bounds").name.ident();
let mut s = format!("{}: {}", self.name.ident(), name);
for bound in bounds {
s.push_str(&format!(" + {}", bound.name.ident()));
}
s
} else {
self.name.ident().to_string()
};
(name, GenericParamDefKind::Lifetime)
}
hir::GenericParamKind::Type { ref default, synthetic } => {
(self.name.ident().name.clean(cx), GenericParamDefKind::Type {
did: cx.tcx.hir().local_def_id(self.id),
bounds: self.bounds.clean(cx),
default: default.clean(cx),
synthetic: synthetic,
})
}
hir::GenericParamKind::Const { ref ty } => {
(self.name.ident().name.clean(cx), GenericParamDefKind::Const {
did: cx.tcx.hir().local_def_id(self.id),
ty: ty.clean(cx),
})
}
};
GenericParamDef {
name,
kind,
}
}
}
// maybe use a Generic enum and use Vec<Generic>?
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Default, Hash)]
pub struct Generics {
pub params: Vec<GenericParamDef>,
pub where_predicates: Vec<WherePredicate>,
}
impl Clean<Generics> for hir::Generics {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Generics {
// Synthetic type-parameters are inserted after normal ones.
// In order for normal parameters to be able to refer to synthetic ones,
// scans them first.
fn is_impl_trait(param: &hir::GenericParam) -> bool {
match param.kind {
hir::GenericParamKind::Type { synthetic, .. } => {
synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
}
_ => false,
}
}
let impl_trait_params = self.params
.iter()
.filter(|param| is_impl_trait(param))
.map(|param| {
let param: GenericParamDef = param.clean(cx);
match param.kind {
GenericParamDefKind::Lifetime => unreachable!(),
GenericParamDefKind::Type { did, ref bounds, .. } => {
cx.impl_trait_bounds.borrow_mut().insert(did, bounds.clone());
}
GenericParamDefKind::Const { .. } => unreachable!(),
}
param
})
.collect::<Vec<_>>();
let mut params = Vec::with_capacity(self.params.len());
for p in self.params.iter().filter(|p| !is_impl_trait(p)) {
let p = p.clean(cx);
params.push(p);
}
params.extend(impl_trait_params);
let mut generics = Generics {
params,
where_predicates: self.where_clause.predicates.clean(cx),
};
// Some duplicates are generated for ?Sized bounds between type params and where
// predicates. The point in here is to move the bounds definitions from type params
// to where predicates when such cases occur.
for where_pred in &mut generics.where_predicates {
match *where_pred {
WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
if bounds.is_empty() {
for param in &mut generics.params {
match param.kind {
GenericParamDefKind::Lifetime => {}
GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
if ¶m.name == name {
mem::swap(bounds, ty_bounds);
break
}
}
GenericParamDefKind::Const { .. } => {}
}
}
}
}
_ => continue,
}
}
generics
}
}
impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics,
&'a Lrc<ty::GenericPredicates<'tcx>>) {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Generics {
use self::WherePredicate as WP;
let (gens, preds) = *self;
// Bounds in the type_params and lifetimes fields are repeated in the
// predicates field (see rustc_typeck::collect::ty_generics), so remove
// them.
let stripped_typarams = gens.params.iter().filter_map(|param| match param.kind {
ty::GenericParamDefKind::Lifetime => None,
ty::GenericParamDefKind::Type { .. } => {
if param.name == keywords::SelfUpper.name().as_str() {
assert_eq!(param.index, 0);
return None;
}
Some(param.clean(cx))
}
}).collect::<Vec<GenericParamDef>>();
let mut where_predicates = preds.predicates.iter()
.flat_map(|(p, _)| p.clean(cx))
.collect::<Vec<_>>();
// Type parameters and have a Sized bound by default unless removed with
// ?Sized. Scan through the predicates and mark any type parameter with
// a Sized bound, removing the bounds as we find them.
//
// Note that associated types also have a sized bound by default, but we
// don't actually know the set of associated types right here so that's
// handled in cleaning associated types
let mut sized_params = FxHashSet::default();
where_predicates.retain(|pred| {
match *pred {
WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
if bounds.iter().any(|b| b.is_sized_bound(cx)) {
sized_params.insert(g.clone());
false
} else {
true
}
}
_ => true,
}
});
// Run through the type parameters again and insert a ?Sized
// unbound for any we didn't find to be Sized.
for tp in &stripped_typarams {
if !sized_params.contains(&tp.name) {
where_predicates.push(WP::BoundPredicate {
ty: Type::Generic(tp.name.clone()),
bounds: vec![GenericBound::maybe_sized(cx)],
})
}
}
// It would be nice to collect all of the bounds on a type and recombine
// them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
// and instead see `where T: Foo + Bar + Sized + 'a`
Generics {
params: gens.params
.iter()
.flat_map(|param| match param.kind {
ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
ty::GenericParamDefKind::Type { .. } => None,
}).chain(simplify::ty_params(stripped_typarams).into_iter())
.collect(),
where_predicates: simplify::where_clauses(cx, where_predicates),
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Method {
pub generics: Generics,
pub decl: FnDecl,
pub header: hir::FnHeader,
}
impl<'a> Clean<Method> for (&'a hir::MethodSig, &'a hir::Generics, hir::BodyId) {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Method {
let (generics, decl) = enter_impl_trait(cx, || {
(self.1.clean(cx), (&*self.0.decl, self.2).clean(cx))
});
Method {
decl,
generics,
header: self.0.header,
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct TyMethod {
pub header: hir::FnHeader,
pub decl: FnDecl,
pub generics: Generics,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Function {
pub decl: FnDecl,
pub generics: Generics,
pub header: hir::FnHeader,
}
impl Clean<Item> for doctree::Function {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
let (generics, decl) = enter_impl_trait(cx, || {
(self.generics.clean(cx), (&self.decl, self.body).clean(cx))
});
let did = cx.tcx.hir().local_def_id(self.id);
let constness = if cx.tcx.is_min_const_fn(did) {
hir::Constness::Const
} else {
hir::Constness::NotConst
};
Item {
name: Some(self.name.clean(cx)),
attrs: self.attrs.clean(cx),
source: self.whence.clean(cx),
visibility: self.vis.clean(cx),
stability: self.stab.clean(cx),
deprecation: self.depr.clean(cx),
def_id: did,
inner: FunctionItem(Function {
decl,
generics,
header: hir::FnHeader { constness, ..self.header },
}),
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
pub struct FnDecl {
pub inputs: Arguments,
pub output: FunctionRetTy,
pub variadic: bool,
pub attrs: Attributes,
}
impl FnDecl {
pub fn self_type(&self) -> Option<SelfTy> {
self.inputs.values.get(0).and_then(|v| v.to_self())
}
/// Returns the sugared return type for an async function.
///
/// For example, if the return type is `impl std::future::Future<Output = i32>`, this function
/// will return `i32`.
///
/// # Panics
///
/// This function will panic if the return type does not match the expected sugaring for async
/// functions.
pub fn sugared_async_return_type(&self) -> FunctionRetTy {
match &self.output {
FunctionRetTy::Return(Type::ImplTrait(bounds)) => {
match &bounds[0] {
GenericBound::TraitBound(PolyTrait { trait_, .. }, ..) => {
let bindings = trait_.bindings().unwrap();
FunctionRetTy::Return(bindings[0].ty.clone())
}
_ => panic!("unexpected desugaring of async function"),
}
}
_ => panic!("unexpected desugaring of async function"),
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
pub struct Arguments {
pub values: Vec<Argument>,
}
impl<'a> Clean<Arguments> for (&'a [hir::Ty], &'a [ast::Ident]) {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Arguments {
Arguments {
values: self.0.iter().enumerate().map(|(i, ty)| {
let mut name = self.1.get(i).map(|ident| ident.to_string())
.unwrap_or(String::new());
if name.is_empty() {
name = "_".to_string();
}
Argument {
name,
type_: ty.clean(cx),
}
}).collect()
}
}
}
impl<'a> Clean<Arguments> for (&'a [hir::Ty], hir::BodyId) {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Arguments {
let body = cx.tcx.hir().body(self.1);
Arguments {
values: self.0.iter().enumerate().map(|(i, ty)| {
Argument {
name: name_from_pat(&body.arguments[i].pat),
type_: ty.clean(cx),
}
}).collect()
}
}
}
impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl, A)
where (&'a [hir::Ty], A): Clean<Arguments>
{
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> FnDecl {
FnDecl {
inputs: (&self.0.inputs[..], self.1).clean(cx),
output: self.0.output.clean(cx),
variadic: self.0.variadic,
attrs: Attributes::default()
}
}
}
impl<'a, 'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> FnDecl {
let (did, sig) = *self;
let mut names = if cx.tcx.hir().as_local_node_id(did).is_some() {
vec![].into_iter()
} else {
cx.tcx.fn_arg_names(did).into_iter()
};
FnDecl {
output: Return(sig.skip_binder().output().clean(cx)),
attrs: Attributes::default(),
variadic: sig.skip_binder().variadic,
inputs: Arguments {
values: sig.skip_binder().inputs().iter().map(|t| {
Argument {
type_: t.clean(cx),
name: names.next().map_or(String::new(), |name| name.to_string()),
}
}).collect(),
},
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
pub struct Argument {
pub type_: Type,
pub name: String,
}
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
pub enum SelfTy {
SelfValue,
SelfBorrowed(Option<Lifetime>, Mutability),
SelfExplicit(Type),
}
impl Argument {
pub fn to_self(&self) -> Option<SelfTy> {
if self.name != "self" {
return None;
}
if self.type_.is_self_type() {
return Some(SelfValue);
}
match self.type_ {
BorrowedRef{ref lifetime, mutability, ref type_} if type_.is_self_type() => {
Some(SelfBorrowed(lifetime.clone(), mutability))
}
_ => Some(SelfExplicit(self.type_.clone()))
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
pub enum FunctionRetTy {
Return(Type),
DefaultReturn,
}
impl Clean<FunctionRetTy> for hir::FunctionRetTy {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> FunctionRetTy {
match *self {
hir::Return(ref typ) => Return(typ.clean(cx)),
hir::DefaultReturn(..) => DefaultReturn,
}
}
}
impl GetDefId for FunctionRetTy {
fn def_id(&self) -> Option<DefId> {
match *self {
Return(ref ty) => ty.def_id(),
DefaultReturn => None,
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Trait {
pub auto: bool,
pub unsafety: hir::Unsafety,
pub items: Vec<Item>,
pub generics: Generics,
pub bounds: Vec<GenericBound>,
pub is_spotlight: bool,
pub is_auto: bool,
}
impl Clean<Item> for doctree::Trait {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
let attrs = self.attrs.clean(cx);
let is_spotlight = attrs.has_doc_flag("spotlight");
Item {
name: Some(self.name.clean(cx)),
attrs: attrs,
source: self.whence.clean(cx),
def_id: cx.tcx.hir().local_def_id(self.id),
visibility: self.vis.clean(cx),
stability: self.stab.clean(cx),
deprecation: self.depr.clean(cx),
inner: TraitItem(Trait {
auto: self.is_auto.clean(cx),
unsafety: self.unsafety,
items: self.items.clean(cx),
generics: self.generics.clean(cx),
bounds: self.bounds.clean(cx),
is_spotlight,
is_auto: self.is_auto.clean(cx),
}),
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct TraitAlias {
pub generics: Generics,
pub bounds: Vec<GenericBound>,
}
impl Clean<Item> for doctree::TraitAlias {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
let attrs = self.attrs.clean(cx);
Item {
name: Some(self.name.clean(cx)),
attrs,
source: self.whence.clean(cx),
def_id: cx.tcx.hir().local_def_id(self.id),
visibility: self.vis.clean(cx),
stability: self.stab.clean(cx),
deprecation: self.depr.clean(cx),
inner: TraitAliasItem(TraitAlias {
generics: self.generics.clean(cx),
bounds: self.bounds.clean(cx),
}),
}
}
}
impl Clean<bool> for hir::IsAuto {
fn clean(&self, _: &DocContext<'_, '_, '_>) -> bool {
match *self {
hir::IsAuto::Yes => true,
hir::IsAuto::No => false,
}
}
}
impl Clean<Type> for hir::TraitRef {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Type {
resolve_type(cx, self.path.clean(cx), self.ref_id)
}
}
impl Clean<PolyTrait> for hir::PolyTraitRef {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> PolyTrait {
PolyTrait {
trait_: self.trait_ref.clean(cx),
generic_params: self.bound_generic_params.clean(cx)
}
}
}
impl Clean<Item> for hir::TraitItem {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
let inner = match self.node {
hir::TraitItemKind::Const(ref ty, default) => {
AssociatedConstItem(ty.clean(cx),
default.map(|e| print_const_expr(cx, e)))
}
hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
MethodItem((sig, &self.generics, body).clean(cx))
}
hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref names)) => {
let (generics, decl) = enter_impl_trait(cx, || {
(self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
});
TyMethodItem(TyMethod {
header: sig.header,
decl,
generics,
})
}
hir::TraitItemKind::Type(ref bounds, ref default) => {
AssociatedTypeItem(bounds.clean(cx), default.clean(cx))
}
};
Item {
name: Some(self.ident.name.clean(cx)),
attrs: self.attrs.clean(cx),
source: self.span.clean(cx),
def_id: cx.tcx.hir().local_def_id(self.id),
visibility: None,
stability: get_stability(cx, cx.tcx.hir().local_def_id(self.id)),
deprecation: get_deprecation(cx, cx.tcx.hir().local_def_id(self.id)),
inner,
}
}
}
impl Clean<Item> for hir::ImplItem {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
let inner = match self.node {
hir::ImplItemKind::Const(ref ty, expr) => {
AssociatedConstItem(ty.clean(cx),
Some(print_const_expr(cx, expr)))
}
hir::ImplItemKind::Method(ref sig, body) => {
MethodItem((sig, &self.generics, body).clean(cx))
}
hir::ImplItemKind::Type(ref ty) => TypedefItem(Typedef {
type_: ty.clean(cx),
generics: Generics::default(),
}, true),
hir::ImplItemKind::Existential(ref bounds) => ExistentialItem(Existential {
bounds: bounds.clean(cx),
generics: Generics::default(),
}, true),
};
Item {
name: Some(self.ident.name.clean(cx)),
source: self.span.clean(cx),
attrs: self.attrs.clean(cx),
def_id: cx.tcx.hir().local_def_id(self.id),
visibility: self.vis.clean(cx),
stability: get_stability(cx, cx.tcx.hir().local_def_id(self.id)),
deprecation: get_deprecation(cx, cx.tcx.hir().local_def_id(self.id)),
inner,
}
}
}
impl<'tcx> Clean<Item> for ty::AssociatedItem {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
let inner = match self.kind {
ty::AssociatedKind::Const => {
let ty = cx.tcx.type_of(self.def_id);
let default = if self.defaultness.has_value() {
Some(inline::print_inlined_const(cx, self.def_id))
} else {
None
};
AssociatedConstItem(ty.clean(cx), default)
}
ty::AssociatedKind::Method => {
let generics = (cx.tcx.generics_of(self.def_id),
&cx.tcx.predicates_of(self.def_id)).clean(cx);
let sig = cx.tcx.fn_sig(self.def_id);
let mut decl = (self.def_id, sig).clean(cx);
if self.method_has_self_argument {
let self_ty = match self.container {
ty::ImplContainer(def_id) => {
cx.tcx.type_of(def_id)
}
ty::TraitContainer(_) => cx.tcx.mk_self_type()
};
let self_arg_ty = *sig.input(0).skip_binder();
if self_arg_ty == self_ty {
decl.inputs.values[0].type_ = Generic(String::from("Self"));
} else if let ty::Ref(_, ty, _) = self_arg_ty.sty {
if ty == self_ty {
match decl.inputs.values[0].type_ {
BorrowedRef{ref mut type_, ..} => {
**type_ = Generic(String::from("Self"))
}
_ => unreachable!(),
}
}
}
}
let provided = match self.container {
ty::ImplContainer(_) => true,
ty::TraitContainer(_) => self.defaultness.has_value()
};
if provided {
let constness = if cx.tcx.is_min_const_fn(self.def_id) {
hir::Constness::Const
} else {
hir::Constness::NotConst
};
MethodItem(Method {
generics,
decl,
header: hir::FnHeader {
unsafety: sig.unsafety(),
abi: sig.abi(),
constness,
asyncness: hir::IsAsync::NotAsync,
}
})
} else {
TyMethodItem(TyMethod {
generics,
decl,
header: hir::FnHeader {
unsafety: sig.unsafety(),
abi: sig.abi(),
constness: hir::Constness::NotConst,
asyncness: hir::IsAsync::NotAsync,
}
})
}
}
ty::AssociatedKind::Type => {
let my_name = self.ident.name.clean(cx);
if let ty::TraitContainer(did) = self.container {
// When loading a cross-crate associated type, the bounds for this type
// are actually located on the trait/impl itself, so we need to load
// all of the generics from there and then look for bounds that are
// applied to this associated type in question.
let predicates = cx.tcx.predicates_of(did);
let generics = (cx.tcx.generics_of(did), &predicates).clean(cx);
let mut bounds = generics.where_predicates.iter().filter_map(|pred| {
let (name, self_type, trait_, bounds) = match *pred {
WherePredicate::BoundPredicate {
ty: QPath { ref name, ref self_type, ref trait_ },
ref bounds
} => (name, self_type, trait_, bounds),
_ => return None,
};
if *name != my_name { return None }
match **trait_ {
ResolvedPath { did, .. } if did == self.container.id() => {}
_ => return None,
}
match **self_type {
Generic(ref s) if *s == "Self" => {}
_ => return None,
}
Some(bounds)
}).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>();
// Our Sized/?Sized bound didn't get handled when creating the generics
// because we didn't actually get our whole set of bounds until just now
// (some of them may have come from the trait). If we do have a sized
// bound, we remove it, and if we don't then we add the `?Sized` bound
// at the end.
match bounds.iter().position(|b| b.is_sized_bound(cx)) {
Some(i) => { bounds.remove(i); }
None => bounds.push(GenericBound::maybe_sized(cx)),
}
let ty = if self.defaultness.has_value() {
Some(cx.tcx.type_of(self.def_id))
} else {
None
};
AssociatedTypeItem(bounds, ty.clean(cx))
} else {
TypedefItem(Typedef {
type_: cx.tcx.type_of(self.def_id).clean(cx),
generics: Generics {
params: Vec::new(),
where_predicates: Vec::new(),
},
}, true)
}
}
ty::AssociatedKind::Existential => unimplemented!(),
};
let visibility = match self.container {
ty::ImplContainer(_) => self.vis.clean(cx),
ty::TraitContainer(_) => None,
};
Item {
name: Some(self.ident.name.clean(cx)),
visibility,
stability: get_stability(cx, self.def_id),
deprecation: get_deprecation(cx, self.def_id),
def_id: self.def_id,
attrs: inline::load_attrs(cx, self.def_id),
source: cx.tcx.def_span(self.def_id).clean(cx),
inner,
}
}
}
/// A trait reference, which may have higher ranked lifetimes.
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
pub struct PolyTrait {
pub trait_: Type,
pub generic_params: Vec<GenericParamDef>,
}
/// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
/// type out of the AST/TyCtxt given one of these, if more information is needed. Most importantly
/// it does not preserve mutability or boxes.
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
pub enum Type {
/// Structs/enums/traits (most that'd be an `hir::TyKind::Path`).
ResolvedPath {
path: Path,
typarams: Option<Vec<GenericBound>>,
did: DefId,
/// `true` if is a `T::Name` path for associated types.
is_generic: bool,
},
/// For parameterized types, so the consumer of the JSON don't go
/// looking for types which don't exist anywhere.
Generic(String),
/// Primitives are the fixed-size numeric types (plus int/usize/float), char,
/// arrays, slices, and tuples.
Primitive(PrimitiveType),
/// extern "ABI" fn
BareFunction(Box<BareFunctionDecl>),
Tuple(Vec<Type>),
Slice(Box<Type>),
Array(Box<Type>, String),
Never,
Unique(Box<Type>),
RawPointer(Mutability, Box<Type>),
BorrowedRef {
lifetime: Option<Lifetime>,
mutability: Mutability,
type_: Box<Type>,
},
// <Type as Trait>::Name
QPath {
name: String,
self_type: Box<Type>,
trait_: Box<Type>
},
// _
Infer,
// impl TraitA+TraitB
ImplTrait(Vec<GenericBound>),
}
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)]
pub enum PrimitiveType {
Isize, I8, I16, I32, I64, I128,
Usize, U8, U16, U32, U64, U128,
F32, F64,
Char,
Bool,
Str,
Slice,
Array,
Tuple,
Unit,
RawPointer,
Reference,
Fn,
Never,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Copy, Debug)]
pub enum TypeKind {
Enum,
Function,
Module,
Const,
Static,
Struct,
Union,
Trait,
Variant,
Typedef,
Foreign,
Macro,
Attr,
Derive,
TraitAlias,
}
pub trait GetDefId {
fn def_id(&self) -> Option<DefId>;
}
impl<T: GetDefId> GetDefId for Option<T> {
fn def_id(&self) -> Option<DefId> {
self.as_ref().and_then(|d| d.def_id())
}
}
impl Type {
pub fn primitive_type(&self) -> Option<PrimitiveType> {
match *self {
Primitive(p) | BorrowedRef { type_: box Primitive(p), ..} => Some(p),
Slice(..) | BorrowedRef { type_: box Slice(..), .. } => Some(PrimitiveType::Slice),
Array(..) | BorrowedRef { type_: box Array(..), .. } => Some(PrimitiveType::Array),
Tuple(ref tys) => if tys.is_empty() {
Some(PrimitiveType::Unit)
} else {
Some(PrimitiveType::Tuple)
},
RawPointer(..) => Some(PrimitiveType::RawPointer),
BorrowedRef { type_: box Generic(..), .. } => Some(PrimitiveType::Reference),
BareFunction(..) => Some(PrimitiveType::Fn),
Never => Some(PrimitiveType::Never),
_ => None,
}
}
pub fn is_generic(&self) -> bool {
match *self {
ResolvedPath { is_generic, .. } => is_generic,
_ => false,
}
}
pub fn is_self_type(&self) -> bool {
match *self {
Generic(ref name) => name == "Self",
_ => false
}
}
pub fn generics(&self) -> Option<&[Type]> {
match *self {
ResolvedPath { ref path, .. } => {
path.segments.last().and_then(|seg| {
if let GenericArgs::AngleBracketed { ref types, .. } = seg.args {
Some(&**types)
} else {
None
}
})
}
_ => None,
}
}
pub fn bindings(&self) -> Option<&[TypeBinding]> {
match *self {
ResolvedPath { ref path, .. } => {
path.segments.last().and_then(|seg| {
if let GenericArgs::AngleBracketed { ref bindings, .. } = seg.args {
Some(&**bindings)
} else {
None
}
})
}
_ => None
}
}
}
impl GetDefId for Type {
fn def_id(&self) -> Option<DefId> {
match *self {
ResolvedPath { did, .. } => Some(did),
Primitive(p) => crate::html::render::cache().primitive_locations.get(&p).cloned(),
BorrowedRef { type_: box Generic(..), .. } =>
Primitive(PrimitiveType::Reference).def_id(),
BorrowedRef { ref type_, .. } => type_.def_id(),
Tuple(ref tys) => if tys.is_empty() {
Primitive(PrimitiveType::Unit).def_id()
} else {
Primitive(PrimitiveType::Tuple).def_id()
},
BareFunction(..) => Primitive(PrimitiveType::Fn).def_id(),
Never => Primitive(PrimitiveType::Never).def_id(),
Slice(..) => Primitive(PrimitiveType::Slice).def_id(),
Array(..) => Primitive(PrimitiveType::Array).def_id(),
RawPointer(..) => Primitive(PrimitiveType::RawPointer).def_id(),
QPath { ref self_type, .. } => self_type.def_id(),
_ => None,
}
}
}
impl PrimitiveType {
fn from_str(s: &str) -> Option<PrimitiveType> {
match s {
"isize" => Some(PrimitiveType::Isize),
"i8" => Some(PrimitiveType::I8),
"i16" => Some(PrimitiveType::I16),
"i32" => Some(PrimitiveType::I32),
"i64" => Some(PrimitiveType::I64),
"i128" => Some(PrimitiveType::I128),
"usize" => Some(PrimitiveType::Usize),
"u8" => Some(PrimitiveType::U8),
"u16" => Some(PrimitiveType::U16),
"u32" => Some(PrimitiveType::U32),
"u64" => Some(PrimitiveType::U64),
"u128" => Some(PrimitiveType::U128),
"bool" => Some(PrimitiveType::Bool),
"char" => Some(PrimitiveType::Char),
"str" => Some(PrimitiveType::Str),
"f32" => Some(PrimitiveType::F32),
"f64" => Some(PrimitiveType::F64),
"array" => Some(PrimitiveType::Array),
"slice" => Some(PrimitiveType::Slice),
"tuple" => Some(PrimitiveType::Tuple),
"unit" => Some(PrimitiveType::Unit),
"pointer" => Some(PrimitiveType::RawPointer),
"reference" => Some(PrimitiveType::Reference),
"fn" => Some(PrimitiveType::Fn),
"never" => Some(PrimitiveType::Never),
_ => None,
}
}
pub fn as_str(&self) -> &'static str {
use self::PrimitiveType::*;
match *self {
Isize => "isize",
I8 => "i8",
I16 => "i16",
I32 => "i32",
I64 => "i64",
I128 => "i128",
Usize => "usize",
U8 => "u8",
U16 => "u16",
U32 => "u32",
U64 => "u64",
U128 => "u128",
F32 => "f32",
F64 => "f64",
Str => "str",
Bool => "bool",
Char => "char",
Array => "array",
Slice => "slice",
Tuple => "tuple",
Unit => "unit",
RawPointer => "pointer",
Reference => "reference",
Fn => "fn",
Never => "never",
}
}
pub fn to_url_str(&self) -> &'static str {
self.as_str()
}
}
impl From<ast::IntTy> for PrimitiveType {
fn from(int_ty: ast::IntTy) -> PrimitiveType {
match int_ty {
ast::IntTy::Isize => PrimitiveType::Isize,
ast::IntTy::I8 => PrimitiveType::I8,
ast::IntTy::I16 => PrimitiveType::I16,
ast::IntTy::I32 => PrimitiveType::I32,
ast::IntTy::I64 => PrimitiveType::I64,
ast::IntTy::I128 => PrimitiveType::I128,
}
}
}
impl From<ast::UintTy> for PrimitiveType {
fn from(uint_ty: ast::UintTy) -> PrimitiveType {
match uint_ty {
ast::UintTy::Usize => PrimitiveType::Usize,
ast::UintTy::U8 => PrimitiveType::U8,
ast::UintTy::U16 => PrimitiveType::U16,
ast::UintTy::U32 => PrimitiveType::U32,
ast::UintTy::U64 => PrimitiveType::U64,
ast::UintTy::U128 => PrimitiveType::U128,
}
}
}
impl From<ast::FloatTy> for PrimitiveType {
fn from(float_ty: ast::FloatTy) -> PrimitiveType {
match float_ty {
ast::FloatTy::F32 => PrimitiveType::F32,
ast::FloatTy::F64 => PrimitiveType::F64,
}
}
}
impl Clean<Type> for hir::Ty {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Type {
use rustc::hir::*;
match self.node {
TyKind::Never => Never,
TyKind::Ptr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
TyKind::Rptr(ref l, ref m) => {
let lifetime = if l.is_elided() {
None
} else {
Some(l.clean(cx))
};
BorrowedRef {lifetime: lifetime, mutability: m.mutbl.clean(cx),
type_: box m.ty.clean(cx)}
}
TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
TyKind::Array(ref ty, ref length) => {
let def_id = cx.tcx.hir().local_def_id(length.id);
let param_env = cx.tcx.param_env(def_id);
let substs = Substs::identity_for_item(cx.tcx, def_id);
let cid = GlobalId {
instance: ty::Instance::new(def_id, substs),
promoted: None
};
let length = match cx.tcx.const_eval(param_env.and(cid)) {
Ok(length) => print_const(cx, ty::LazyConst::Evaluated(length)),
Err(_) => "_".to_string(),
};
Array(box ty.clean(cx), length)
},
TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
TyKind::Def(item_id, _) => {
let item = cx.tcx.hir().expect_item(item_id.id);
if let hir::ItemKind::Existential(ref ty) = item.node {
ImplTrait(ty.bounds.clean(cx))
} else {
unreachable!()
}
}
TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
if let Some(new_ty) = cx.ty_substs.borrow().get(&path.def).cloned() {
return new_ty;
}
if let Def::TyParam(did) = path.def {
if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did) {
return ImplTrait(bounds);
}
}
let mut alias = None;
if let Def::TyAlias(def_id) = path.def {
// Substitute private type aliases
if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(def_id) {
if !cx.renderinfo.borrow().access_levels.is_exported(def_id) {
alias = Some(&cx.tcx.hir().expect_item_by_hir_id(hir_id).node);
}
}
};
if let Some(&hir::ItemKind::Ty(ref ty, ref generics)) = alias {
let provided_params = &path.segments.last().expect("segments were empty");
let mut ty_substs = FxHashMap::default();
let mut lt_substs = FxHashMap::default();
let mut const_substs = FxHashMap::default();
provided_params.with_generic_args(|generic_args| {
let mut indices: GenericParamCount = Default::default();
for param in generics.params.iter() {
match param.kind {
hir::GenericParamKind::Lifetime { .. } => {
let mut j = 0;
let lifetime = generic_args.args.iter().find_map(|arg| {
match arg {
hir::GenericArg::Lifetime(lt) => {
if indices.lifetimes == j {
return Some(lt);
}
j += 1;
None
}
_ => None,
}
});
if let Some(lt) = lifetime.cloned() {
if !lt.is_elided() {
let lt_def_id =
cx.tcx.hir().local_def_id(param.id);
lt_substs.insert(lt_def_id, lt.clean(cx));
}
}
indices.lifetimes += 1;
}
hir::GenericParamKind::Type { ref default, .. } => {
let ty_param_def =
Def::TyParam(cx.tcx.hir().local_def_id(param.id));
let mut j = 0;
let type_ = generic_args.args.iter().find_map(|arg| {
match arg {
hir::GenericArg::Type(ty) => {
if indices.types == j {
return Some(ty);
}
j += 1;
None
}
_ => None,
}
});
if let Some(ty) = type_.cloned() {
ty_substs.insert(ty_param_def, ty.clean(cx));
} else if let Some(default) = default.clone() {
ty_substs.insert(ty_param_def,
default.into_inner().clean(cx));
}
indices.types += 1;
}
hir::GenericParamKind::Const { .. } => {
let const_param_def =
Def::ConstParam(cx.tcx.hir().local_def_id(param.id));
let mut j = 0;
let const_ = generic_args.args.iter().find_map(|arg| {
match arg {
hir::GenericArg::Const(ct) => {
if indices.consts == j {
return Some(ct);
}
j += 1;
None
}
_ => None,
}
});
if let Some(ct) = const_.cloned() {
const_substs.insert(const_param_def, ct.clean(cx));
}
// FIXME(const_generics:defaults)
indices.consts += 1;
}
}
}
});
return cx.enter_alias(ty_substs, lt_substs, const_substs, || ty.clean(cx));
}
resolve_type(cx, path.clean(cx), self.id)
}
TyKind::Path(hir::QPath::Resolved(Some(ref qself), ref p)) => {
let mut segments: Vec<_> = p.segments.clone().into();
segments.pop();
let trait_path = hir::Path {
span: p.span,
def: Def::Trait(cx.tcx.associated_item(p.def.def_id()).container.id()),
segments: segments.into(),
};
Type::QPath {
name: p.segments.last().expect("segments were empty").ident.name.clean(cx),
self_type: box qself.clean(cx),
trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
}
}
TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
let mut def = Def::Err;
let ty = hir_ty_to_ty(cx.tcx, self);
if let ty::Projection(proj) = ty.sty {
def = Def::Trait(proj.trait_ref(cx.tcx).def_id);
}
let trait_path = hir::Path {
span: self.span,
def,
segments: vec![].into(),
};
Type::QPath {
name: segment.ident.name.clean(cx),
self_type: box qself.clean(cx),
trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
}
}
TyKind::TraitObject(ref bounds, ref lifetime) => {
match bounds[0].clean(cx).trait_ {
ResolvedPath { path, typarams: None, did, is_generic } => {
let mut bounds: Vec<self::GenericBound> = bounds[1..].iter().map(|bound| {
self::GenericBound::TraitBound(bound.clean(cx),
hir::TraitBoundModifier::None)
}).collect();
if !lifetime.is_elided() {
bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
}
ResolvedPath { path, typarams: Some(bounds), did, is_generic, }
}
_ => Infer // shouldn't happen
}
}
TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
TyKind::Infer | TyKind::Err => Infer,
TyKind::Typeof(..) => panic!("Unimplemented type {:?}", self.node),
}
}
}
impl<'tcx> Clean<Type> for Ty<'tcx> {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Type {
match self.sty {
ty::Never => Never,
ty::Bool => Primitive(PrimitiveType::Bool),
ty::Char => Primitive(PrimitiveType::Char),
ty::Int(int_ty) => Primitive(int_ty.into()),
ty::Uint(uint_ty) => Primitive(uint_ty.into()),
ty::Float(float_ty) => Primitive(float_ty.into()),
ty::Str => Primitive(PrimitiveType::Str),
ty::Slice(ty) => Slice(box ty.clean(cx)),
ty::Array(ty, n) => {
let mut n = *cx.tcx.lift(&n).expect("array lift failed");
if let ty::LazyConst::Unevaluated(def_id, substs) = n {
let param_env = cx.tcx.param_env(def_id);
let cid = GlobalId {
instance: ty::Instance::new(def_id, substs),
promoted: None
};
if let Ok(new_n) = cx.tcx.const_eval(param_env.and(cid)) {
n = ty::LazyConst::Evaluated(new_n);
}
};
let n = print_const(cx, n);
Array(box ty.clean(cx), n)
}
ty::RawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
ty::Ref(r, ty, mutbl) => BorrowedRef {
lifetime: r.clean(cx),
mutability: mutbl.clean(cx),
type_: box ty.clean(cx),
},
ty::FnDef(..) |
ty::FnPtr(_) => {
let ty = cx.tcx.lift(self).expect("FnPtr lift failed");
let sig = ty.fn_sig(cx.tcx);
BareFunction(box BareFunctionDecl {
unsafety: sig.unsafety(),
generic_params: Vec::new(),
decl: (cx.tcx.hir().local_def_id(ast::CRATE_NODE_ID), sig).clean(cx),
abi: sig.abi(),
})
}
ty::Adt(def, substs) => {
let did = def.did;
let kind = match def.adt_kind() {
AdtKind::Struct => TypeKind::Struct,
AdtKind::Union => TypeKind::Union,
AdtKind::Enum => TypeKind::Enum,
};
inline::record_extern_fqn(cx, did, kind);
let path = external_path(cx, &cx.tcx.item_name(did).as_str(),
None, false, vec![], substs);
ResolvedPath {
path,
typarams: None,
did,
is_generic: false,
}
}
ty::Foreign(did) => {
inline::record_extern_fqn(cx, did, TypeKind::Foreign);
let path = external_path(cx, &cx.tcx.item_name(did).as_str(),
None, false, vec![], Substs::empty());
ResolvedPath {
path: path,
typarams: None,
did: did,
is_generic: false,
}
}
ty::Dynamic(ref obj, ref reg) => {
// HACK: pick the first `did` as the `did` of the trait object. Someone
// might want to implement "native" support for marker-trait-only
// trait objects.
let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
let did = dids.next().unwrap_or_else(|| {
panic!("found trait object `{:?}` with no traits?", self)
});
let substs = match obj.principal() {
Some(principal) => principal.skip_binder().substs,
// marker traits have no substs.
_ => cx.tcx.intern_substs(&[])
};
inline::record_extern_fqn(cx, did, TypeKind::Trait);
let mut typarams = vec![];
reg.clean(cx).map(|b| typarams.push(GenericBound::Outlives(b)));
for did in dids {
let empty = cx.tcx.intern_substs(&[]);
let path = external_path(cx, &cx.tcx.item_name(did).as_str(),
Some(did), false, vec![], empty);
inline::record_extern_fqn(cx, did, TypeKind::Trait);
let bound = GenericBound::TraitBound(PolyTrait {
trait_: ResolvedPath {
path,
typarams: None,
did,
is_generic: false,
},
generic_params: Vec::new(),
}, hir::TraitBoundModifier::None);
typarams.push(bound);
}
let mut bindings = vec![];
for pb in obj.projection_bounds() {
bindings.push(TypeBinding {
name: cx.tcx.associated_item(pb.item_def_id()).ident.name.clean(cx),
ty: pb.skip_binder().ty.clean(cx)
});
}
let path = external_path(cx, &cx.tcx.item_name(did).as_str(), Some(did),
false, bindings, substs);
ResolvedPath {
path,
typarams: Some(typarams),
did,
is_generic: false,
}
}
ty::Tuple(ref t) => Tuple(t.clean(cx)),
ty::Projection(ref data) => data.clean(cx),
ty::Param(ref p) => Generic(p.name.to_string()),
ty::Opaque(def_id, substs) => {
// Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
// by looking up the projections associated with the def_id.
let predicates_of = cx.tcx.predicates_of(def_id);
let substs = cx.tcx.lift(&substs).expect("Opaque lift failed");
let bounds = predicates_of.instantiate(cx.tcx, substs);
let mut regions = vec![];
let mut has_sized = false;
let mut bounds = bounds.predicates.iter().filter_map(|predicate| {
let trait_ref = if let Some(tr) = predicate.to_opt_poly_trait_ref() {
tr
} else if let ty::Predicate::TypeOutlives(pred) = *predicate {
// these should turn up at the end
pred.skip_binder().1.clean(cx).map(|r| {
regions.push(GenericBound::Outlives(r))
});
return None;
} else {
return None;
};
if let Some(sized) = cx.tcx.lang_items().sized_trait() {
if trait_ref.def_id() == sized {
has_sized = true;
return None;
}
}
let bounds = bounds.predicates.iter().filter_map(|pred|
if let ty::Predicate::Projection(proj) = *pred {
let proj = proj.skip_binder();
if proj.projection_ty.trait_ref(cx.tcx) == *trait_ref.skip_binder() {
Some(TypeBinding {
name: cx.tcx.associated_item(proj.projection_ty.item_def_id)
.ident.name.clean(cx),
ty: proj.ty.clean(cx),
})
} else {
None
}
} else {
None
}
).collect();
Some((trait_ref.skip_binder(), bounds).clean(cx))
}).collect::<Vec<_>>();
bounds.extend(regions);
if !has_sized && !bounds.is_empty() {
bounds.insert(0, GenericBound::maybe_sized(cx));
}
ImplTrait(bounds)
}
ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
ty::Bound(..) => panic!("Bound"),
ty::Placeholder(..) => panic!("Placeholder"),
ty::UnnormalizedProjection(..) => panic!("UnnormalizedProjection"),
ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
ty::Infer(..) => panic!("Infer"),
ty::Error => panic!("Error"),
}
}
}
impl Clean<Item> for hir::StructField {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
Item {
name: Some(self.ident.name).clean(cx),
attrs: self.attrs.clean(cx),
source: self.span.clean(cx),
visibility: self.vis.clean(cx),
stability: get_stability(cx, cx.tcx.hir().local_def_id(self.id)),
deprecation: get_deprecation(cx, cx.tcx.hir().local_def_id(self.id)),
def_id: cx.tcx.hir().local_def_id(self.id),
inner: StructFieldItem(self.ty.clean(cx)),
}
}
}
impl<'tcx> Clean<Item> for ty::FieldDef {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
Item {
name: Some(self.ident.name).clean(cx),
attrs: cx.tcx.get_attrs(self.did).clean(cx),
source: cx.tcx.def_span(self.did).clean(cx),
visibility: self.vis.clean(cx),
stability: get_stability(cx, self.did),
deprecation: get_deprecation(cx, self.did),
def_id: self.did,
inner: StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
}
}
}
#[derive(Clone, PartialEq, Eq, RustcDecodable, RustcEncodable, Debug)]
pub enum Visibility {
Public,
Inherited,
Crate,
Restricted(DefId, Path),
}
impl Clean<Option<Visibility>> for hir::Visibility {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Option<Visibility> {
Some(match self.node {
hir::VisibilityKind::Public => Visibility::Public,
hir::VisibilityKind::Inherited => Visibility::Inherited,
hir::VisibilityKind::Crate(_) => Visibility::Crate,
hir::VisibilityKind::Restricted { ref path, .. } => {
let path = path.clean(cx);
let did = register_def(cx, path.def);
Visibility::Restricted(did, path)
}
})
}
}
impl Clean<Option<Visibility>> for ty::Visibility {
fn clean(&self, _: &DocContext<'_, '_, '_>) -> Option<Visibility> {
Some(if *self == ty::Visibility::Public { Public } else { Inherited })
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Struct {
pub struct_type: doctree::StructType,
pub generics: Generics,
pub fields: Vec<Item>,
pub fields_stripped: bool,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Union {
pub struct_type: doctree::StructType,
pub generics: Generics,
pub fields: Vec<Item>,
pub fields_stripped: bool,
}
impl Clean<Item> for doctree::Struct {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
Item {
name: Some(self.name.clean(cx)),
attrs: self.attrs.clean(cx),
source: self.whence.clean(cx),
def_id: cx.tcx.hir().local_def_id(self.id),
visibility: self.vis.clean(cx),
stability: self.stab.clean(cx),
deprecation: self.depr.clean(cx),
inner: StructItem(Struct {
struct_type: self.struct_type,
generics: self.generics.clean(cx),
fields: self.fields.clean(cx),
fields_stripped: false,
}),
}
}
}
impl Clean<Item> for doctree::Union {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
Item {
name: Some(self.name.clean(cx)),
attrs: self.attrs.clean(cx),
source: self.whence.clean(cx),
def_id: cx.tcx.hir().local_def_id(self.id),
visibility: self.vis.clean(cx),
stability: self.stab.clean(cx),
deprecation: self.depr.clean(cx),
inner: UnionItem(Union {
struct_type: self.struct_type,
generics: self.generics.clean(cx),
fields: self.fields.clean(cx),
fields_stripped: false,
}),
}
}
}
/// This is a more limited form of the standard Struct, different in that
/// it lacks the things most items have (name, id, parameterization). Found
/// only as a variant in an enum.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct VariantStruct {
pub struct_type: doctree::StructType,
pub fields: Vec<Item>,
pub fields_stripped: bool,
}
impl Clean<VariantStruct> for ::rustc::hir::VariantData {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> VariantStruct {
VariantStruct {
struct_type: doctree::struct_type_from_def(self),
fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
fields_stripped: false,
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Enum {
pub variants: IndexVec<VariantIdx, Item>,
pub generics: Generics,
pub variants_stripped: bool,
}
impl Clean<Item> for doctree::Enum {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
Item {
name: Some(self.name.clean(cx)),
attrs: self.attrs.clean(cx),
source: self.whence.clean(cx),
def_id: cx.tcx.hir().local_def_id(self.id),
visibility: self.vis.clean(cx),
stability: self.stab.clean(cx),
deprecation: self.depr.clean(cx),
inner: EnumItem(Enum {
variants: self.variants.iter().map(|v| v.clean(cx)).collect(),
generics: self.generics.clean(cx),
variants_stripped: false,
}),
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Variant {
pub kind: VariantKind,
}
impl Clean<Item> for doctree::Variant {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
Item {
name: Some(self.name.clean(cx)),
attrs: self.attrs.clean(cx),
source: self.whence.clean(cx),
visibility: None,
stability: self.stab.clean(cx),
deprecation: self.depr.clean(cx),
def_id: cx.tcx.hir().local_def_id(self.def.id()),
inner: VariantItem(Variant {
kind: self.def.clean(cx),
}),
}
}
}
impl<'tcx> Clean<Item> for ty::VariantDef {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
let kind = match self.ctor_kind {
CtorKind::Const => VariantKind::CLike,
CtorKind::Fn => {
VariantKind::Tuple(
self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect()
)
}
CtorKind::Fictive => {
VariantKind::Struct(VariantStruct {
struct_type: doctree::Plain,
fields_stripped: false,
fields: self.fields.iter().map(|field| {
Item {
source: cx.tcx.def_span(field.did).clean(cx),
name: Some(field.ident.name.clean(cx)),
attrs: cx.tcx.get_attrs(field.did).clean(cx),
visibility: field.vis.clean(cx),
def_id: field.did,
stability: get_stability(cx, field.did),
deprecation: get_deprecation(cx, field.did),
inner: StructFieldItem(cx.tcx.type_of(field.did).clean(cx))
}
}).collect()
})
}
};
Item {
name: Some(self.ident.clean(cx)),
attrs: inline::load_attrs(cx, self.did),
source: cx.tcx.def_span(self.did).clean(cx),
visibility: Some(Inherited),
def_id: self.did,
inner: VariantItem(Variant { kind }),
stability: get_stability(cx, self.did),
deprecation: get_deprecation(cx, self.did),
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum VariantKind {
CLike,
Tuple(Vec<Type>),
Struct(VariantStruct),
}
impl Clean<VariantKind> for hir::VariantData {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> VariantKind {
if self.is_struct() {
VariantKind::Struct(self.clean(cx))
} else if self.is_unit() {
VariantKind::CLike
} else {
VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Span {
pub filename: FileName,
pub loline: usize,
pub locol: usize,
pub hiline: usize,
pub hicol: usize,
}
impl Span {
pub fn empty() -> Span {
Span {
filename: FileName::Anon(0),
loline: 0, locol: 0,
hiline: 0, hicol: 0,
}
}
}
impl Clean<Span> for syntax_pos::Span {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Span {
if self.is_dummy() {
return Span::empty();
}
let cm = cx.sess().source_map();
let filename = cm.span_to_filename(*self);
let lo = cm.lookup_char_pos(self.lo());
let hi = cm.lookup_char_pos(self.hi());
Span {
filename,
loline: lo.line,
locol: lo.col.to_usize(),
hiline: hi.line,
hicol: hi.col.to_usize(),
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
pub struct Path {
pub global: bool,
pub def: Def,
pub segments: Vec<PathSegment>,
}
impl Path {
pub fn last_name(&self) -> &str {
self.segments.last().expect("segments were empty").name.as_str()
}
}
impl Clean<Path> for hir::Path {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Path {
Path {
global: self.is_global(),
def: self.def,
segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
pub enum GenericArgs {
AngleBracketed {
lifetimes: Vec<Lifetime>,
types: Vec<Type>,
bindings: Vec<TypeBinding>,
},
Parenthesized {
inputs: Vec<Type>,
output: Option<Type>,
}
}
impl Clean<GenericArgs> for hir::GenericArgs {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> GenericArgs {
if self.parenthesized {
let output = self.bindings[0].ty.clean(cx);
GenericArgs::Parenthesized {
inputs: self.inputs().clean(cx),
output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None }
}
} else {
let (mut lifetimes, mut types) = (vec![], vec![]);
let mut elided_lifetimes = true;
for arg in &self.args {
match arg {
GenericArg::Lifetime(lt) => {
if !lt.is_elided() {
elided_lifetimes = false;
}
lifetimes.push(lt.clean(cx));
}
GenericArg::Type(ty) => {
types.push(ty.clean(cx));
}
GenericArg::Const(..) => {
unimplemented!() // FIXME(const_generics)
}
}
}
GenericArgs::AngleBracketed {
lifetimes: if elided_lifetimes { vec![] } else { lifetimes },
types,
bindings: self.bindings.clean(cx),
}
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
pub struct PathSegment {
pub name: String,
pub args: GenericArgs,
}
impl Clean<PathSegment> for hir::PathSegment {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> PathSegment {
PathSegment {
name: self.ident.name.clean(cx),
args: self.with_generic_args(|generic_args| generic_args.clean(cx))
}
}
}
fn strip_type(ty: Type) -> Type {
match ty {
Type::ResolvedPath { path, typarams, did, is_generic } => {
Type::ResolvedPath { path: strip_path(&path), typarams, did, is_generic }
}
Type::Tuple(inner_tys) => {
Type::Tuple(inner_tys.iter().map(|t| strip_type(t.clone())).collect())
}
Type::Slice(inner_ty) => Type::Slice(Box::new(strip_type(*inner_ty))),
Type::Array(inner_ty, s) => Type::Array(Box::new(strip_type(*inner_ty)), s),
Type::Unique(inner_ty) => Type::Unique(Box::new(strip_type(*inner_ty))),
Type::RawPointer(m, inner_ty) => Type::RawPointer(m, Box::new(strip_type(*inner_ty))),
Type::BorrowedRef { lifetime, mutability, type_ } => {
Type::BorrowedRef { lifetime, mutability, type_: Box::new(strip_type(*type_)) }
}
Type::QPath { name, self_type, trait_ } => {
Type::QPath {
name,
self_type: Box::new(strip_type(*self_type)), trait_: Box::new(strip_type(*trait_))
}
}
_ => ty
}
}
fn strip_path(path: &Path) -> Path {
let segments = path.segments.iter().map(|s| {
PathSegment {
name: s.name.clone(),
args: GenericArgs::AngleBracketed {
lifetimes: Vec::new(),
types: Vec::new(),
bindings: Vec::new(),
}
}
}).collect();
Path {
global: path.global,
def: path.def.clone(),
segments,
}
}
fn qpath_to_string(p: &hir::QPath) -> String {
let segments = match *p {
hir::QPath::Resolved(_, ref path) => &path.segments,
hir::QPath::TypeRelative(_, ref segment) => return segment.ident.to_string(),
};
let mut s = String::new();
for (i, seg) in segments.iter().enumerate() {
if i > 0 {
s.push_str("::");
}
if seg.ident.name != keywords::PathRoot.name() {
s.push_str(&*seg.ident.as_str());
}
}
s
}
impl Clean<String> for Ident {
#[inline]
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> String {
self.name.clean(cx)
}
}
impl Clean<String> for ast::Name {
#[inline]
fn clean(&self, _: &DocContext<'_, '_, '_>) -> String {
self.to_string()
}
}
impl Clean<String> for InternedString {
#[inline]
fn clean(&self, _: &DocContext<'_, '_, '_>) -> String {
self.to_string()
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Typedef {
pub type_: Type,
pub generics: Generics,
}
impl Clean<Item> for doctree::Typedef {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
Item {
name: Some(self.name.clean(cx)),
attrs: self.attrs.clean(cx),
source: self.whence.clean(cx),
def_id: cx.tcx.hir().local_def_id(self.id.clone()),
visibility: self.vis.clean(cx),
stability: self.stab.clean(cx),
deprecation: self.depr.clean(cx),
inner: TypedefItem(Typedef {
type_: self.ty.clean(cx),
generics: self.gen.clean(cx),
}, false),
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Existential {
pub bounds: Vec<GenericBound>,
pub generics: Generics,
}
impl Clean<Item> for doctree::Existential {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
Item {
name: Some(self.name.clean(cx)),
attrs: self.attrs.clean(cx),
source: self.whence.clean(cx),
def_id: cx.tcx.hir().local_def_id(self.id.clone()),
visibility: self.vis.clean(cx),
stability: self.stab.clean(cx),
deprecation: self.depr.clean(cx),
inner: ExistentialItem(Existential {
bounds: self.exist_ty.bounds.clean(cx),
generics: self.exist_ty.generics.clean(cx),
}, false),
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
pub struct BareFunctionDecl {
pub unsafety: hir::Unsafety,
pub generic_params: Vec<GenericParamDef>,
pub decl: FnDecl,
pub abi: Abi,
}
impl Clean<BareFunctionDecl> for hir::BareFnTy {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> BareFunctionDecl {
let (generic_params, decl) = enter_impl_trait(cx, || {
(self.generic_params.clean(cx), (&*self.decl, &self.arg_names[..]).clean(cx))
});
BareFunctionDecl {
unsafety: self.unsafety,
abi: self.abi,
decl,
generic_params,
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Static {
pub type_: Type,
pub mutability: Mutability,
/// It's useful to have the value of a static documented, but I have no
/// desire to represent expressions (that'd basically be all of the AST,
/// which is huge!). So, have a string.
pub expr: String,
}
impl Clean<Item> for doctree::Static {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
Item {
name: Some(self.name.clean(cx)),
attrs: self.attrs.clean(cx),
source: self.whence.clean(cx),
def_id: cx.tcx.hir().local_def_id(self.id),
visibility: self.vis.clean(cx),
stability: self.stab.clean(cx),
deprecation: self.depr.clean(cx),
inner: StaticItem(Static {
type_: self.type_.clean(cx),
mutability: self.mutability.clean(cx),
expr: print_const_expr(cx, self.expr),
}),
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Constant {
pub type_: Type,
pub expr: String,
}
impl Clean<Item> for doctree::Constant {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
Item {
name: Some(self.name.clean(cx)),
attrs: self.attrs.clean(cx),
source: self.whence.clean(cx),
def_id: cx.tcx.hir().local_def_id(self.id),
visibility: self.vis.clean(cx),
stability: self.stab.clean(cx),
deprecation: self.depr.clean(cx),
inner: ConstantItem(Constant {
type_: self.type_.clean(cx),
expr: print_const_expr(cx, self.expr),
}),
}
}
}
#[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Copy, Hash)]
pub enum Mutability {
Mutable,
Immutable,
}
impl Clean<Mutability> for hir::Mutability {
fn clean(&self, _: &DocContext<'_, '_, '_>) -> Mutability {
match self {
&hir::MutMutable => Mutable,
&hir::MutImmutable => Immutable,
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Copy, Debug, Hash)]
pub enum ImplPolarity {
Positive,
Negative,
}
impl Clean<ImplPolarity> for hir::ImplPolarity {
fn clean(&self, _: &DocContext<'_, '_, '_>) -> ImplPolarity {
match self {
&hir::ImplPolarity::Positive => ImplPolarity::Positive,
&hir::ImplPolarity::Negative => ImplPolarity::Negative,
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Impl {
pub unsafety: hir::Unsafety,
pub generics: Generics,
pub provided_trait_methods: FxHashSet<String>,
pub trait_: Option<Type>,
pub for_: Type,
pub items: Vec<Item>,
pub polarity: Option<ImplPolarity>,
pub synthetic: bool,
pub blanket_impl: Option<Type>,
}
pub fn get_auto_traits_with_node_id(
cx: &DocContext<'_, '_, '_>,
id: ast::NodeId,
name: String
) -> Vec<Item> {
let finder = AutoTraitFinder::new(cx);
finder.get_with_node_id(id, name)
}
pub fn get_auto_traits_with_def_id(
cx: &DocContext<'_, '_, '_>,
id: DefId
) -> Vec<Item> {
let finder = AutoTraitFinder::new(cx);
finder.get_with_def_id(id)
}
pub fn get_blanket_impls_with_node_id(
cx: &DocContext<'_, '_, '_>,
id: ast::NodeId,
name: String
) -> Vec<Item> {
let finder = BlanketImplFinder::new(cx);
finder.get_with_node_id(id, name)
}
pub fn get_blanket_impls_with_def_id(
cx: &DocContext<'_, '_, '_>,
id: DefId
) -> Vec<Item> {
let finder = BlanketImplFinder::new(cx);
finder.get_with_def_id(id)
}
impl Clean<Vec<Item>> for doctree::Impl {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Vec<Item> {
let mut ret = Vec::new();
let trait_ = self.trait_.clean(cx);
let items = self.items.clean(cx);
// If this impl block is an implementation of the Deref trait, then we
// need to try inlining the target's inherent impl blocks as well.
if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
build_deref_target_impls(cx, &items, &mut ret);
}
let provided = trait_.def_id().map(|did| {
cx.tcx.provided_trait_methods(did)
.into_iter()
.map(|meth| meth.ident.to_string())
.collect()
}).unwrap_or_default();
ret.push(Item {
name: None,
attrs: self.attrs.clean(cx),
source: self.whence.clean(cx),
def_id: cx.tcx.hir().local_def_id(self.id),
visibility: self.vis.clean(cx),
stability: self.stab.clean(cx),
deprecation: self.depr.clean(cx),
inner: ImplItem(Impl {
unsafety: self.unsafety,
generics: self.generics.clean(cx),
provided_trait_methods: provided,
trait_,
for_: self.for_.clean(cx),
items,
polarity: Some(self.polarity.clean(cx)),
synthetic: false,
blanket_impl: None,
})
});
ret
}
}
fn build_deref_target_impls(cx: &DocContext<'_, '_, '_>,
items: &[Item],
ret: &mut Vec<Item>) {
use self::PrimitiveType::*;
let tcx = cx.tcx;
for item in items {
let target = match item.inner {
TypedefItem(ref t, true) => &t.type_,
_ => continue,
};
let primitive = match *target {
ResolvedPath { did, .. } if did.is_local() => continue,
ResolvedPath { did, .. } => {
ret.extend(inline::build_impls(cx, did));
continue
}
_ => match target.primitive_type() {
Some(prim) => prim,
None => continue,
}
};
let did = match primitive {
Isize => tcx.lang_items().isize_impl(),
I8 => tcx.lang_items().i8_impl(),
I16 => tcx.lang_items().i16_impl(),
I32 => tcx.lang_items().i32_impl(),
I64 => tcx.lang_items().i64_impl(),
I128 => tcx.lang_items().i128_impl(),
Usize => tcx.lang_items().usize_impl(),
U8 => tcx.lang_items().u8_impl(),
U16 => tcx.lang_items().u16_impl(),
U32 => tcx.lang_items().u32_impl(),
U64 => tcx.lang_items().u64_impl(),
U128 => tcx.lang_items().u128_impl(),
F32 => tcx.lang_items().f32_impl(),
F64 => tcx.lang_items().f64_impl(),
Char => tcx.lang_items().char_impl(),
Bool => None,
Str => tcx.lang_items().str_impl(),
Slice => tcx.lang_items().slice_impl(),
Array => tcx.lang_items().slice_impl(),
Tuple => None,
Unit => None,
RawPointer => tcx.lang_items().const_ptr_impl(),
Reference => None,
Fn => None,
Never => None,
};
if let Some(did) = did {
if !did.is_local() {
inline::build_impl(cx, did, ret);
}
}
}
}
impl Clean<Vec<Item>> for doctree::ExternCrate {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Vec<Item> {
let please_inline = self.vis.node.is_pub() && self.attrs.iter().any(|a| {
a.name() == "doc" && match a.meta_item_list() {
Some(l) => attr::list_contains_name(&l, "inline"),
None => false,
}
});
if please_inline {
let mut visited = FxHashSet::default();
let def = Def::Mod(DefId {
krate: self.cnum,
index: CRATE_DEF_INDEX,
});
if let Some(items) = inline::try_inline(cx, def, self.name, &mut visited) {
return items;
}
}
vec![Item {
name: None,
attrs: self.attrs.clean(cx),
source: self.whence.clean(cx),
def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
visibility: self.vis.clean(cx),
stability: None,
deprecation: None,
inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
}]
}
}
impl Clean<Vec<Item>> for doctree::Import {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Vec<Item> {
// We consider inlining the documentation of `pub use` statements, but we
// forcefully don't inline if this is not public or if the
// #[doc(no_inline)] attribute is present.
// Don't inline doc(hidden) imports so they can be stripped at a later stage.
let mut denied = !self.vis.node.is_pub() || self.attrs.iter().any(|a| {
a.name() == "doc" && match a.meta_item_list() {
Some(l) => attr::list_contains_name(&l, "no_inline") ||
attr::list_contains_name(&l, "hidden"),
None => false,
}
});
// Also check whether imports were asked to be inlined, in case we're trying to re-export a
// crate in Rust 2018+
let please_inline = self.attrs.lists("doc").has_word("inline");
let path = self.path.clean(cx);
let inner = if self.glob {
if !denied {
let mut visited = FxHashSet::default();
if let Some(items) = inline::try_inline_glob(cx, path.def, &mut visited) {
return items;
}
}
Import::Glob(resolve_use_source(cx, path))
} else {
let name = self.name;
if !please_inline {
match path.def {
Def::Mod(did) => if !did.is_local() && did.index == CRATE_DEF_INDEX {
// if we're `pub use`ing an extern crate root, don't inline it unless we
// were specifically asked for it
denied = true;
}
_ => {}
}
}
if !denied {
let mut visited = FxHashSet::default();
if let Some(items) = inline::try_inline(cx, path.def, name, &mut visited) {
return items;
}
}
Import::Simple(name.clean(cx), resolve_use_source(cx, path))
};
vec![Item {
name: None,
attrs: self.attrs.clean(cx),
source: self.whence.clean(cx),
def_id: cx.tcx.hir().local_def_id(ast::CRATE_NODE_ID),
visibility: self.vis.clean(cx),
stability: None,
deprecation: None,
inner: ImportItem(inner)
}]
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum Import {
// use source as str;
Simple(String, ImportSource),
// use source::*;
Glob(ImportSource)
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct ImportSource {
pub path: Path,
pub did: Option<DefId>,
}
impl Clean<Vec<Item>> for hir::ForeignMod {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Vec<Item> {
let mut items = self.items.clean(cx);
for item in &mut items {
if let ForeignFunctionItem(ref mut f) = item.inner {
f.header.abi = self.abi;
}
}
items
}
}
impl Clean<Item> for hir::ForeignItem {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
let inner = match self.node {
hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
let (generics, decl) = enter_impl_trait(cx, || {
(generics.clean(cx), (&**decl, &names[..]).clean(cx))
});
ForeignFunctionItem(Function {
decl,
generics,
header: hir::FnHeader {
unsafety: hir::Unsafety::Unsafe,
abi: Abi::Rust,
constness: hir::Constness::NotConst,
asyncness: hir::IsAsync::NotAsync,
},
})
}
hir::ForeignItemKind::Static(ref ty, mutbl) => {
ForeignStaticItem(Static {
type_: ty.clean(cx),
mutability: if mutbl {Mutable} else {Immutable},
expr: String::new(),
})
}
hir::ForeignItemKind::Type => {
ForeignTypeItem
}
};
Item {
name: Some(self.ident.clean(cx)),
attrs: self.attrs.clean(cx),
source: self.span.clean(cx),
def_id: cx.tcx.hir().local_def_id(self.id),
visibility: self.vis.clean(cx),
stability: get_stability(cx, cx.tcx.hir().local_def_id(self.id)),
deprecation: get_deprecation(cx, cx.tcx.hir().local_def_id(self.id)),
inner,
}
}
}
// Utilities
pub trait ToSource {
fn to_src(&self, cx: &DocContext<'_, '_, '_>) -> String;
}
impl ToSource for syntax_pos::Span {
fn to_src(&self, cx: &DocContext<'_, '_, '_>) -> String {
debug!("converting span {:?} to snippet", self.clean(cx));
let sn = match cx.sess().source_map().span_to_snippet(*self) {
Ok(x) => x,
Err(_) => String::new()
};
debug!("got snippet {}", sn);
sn
}
}
fn name_from_pat(p: &hir::Pat) -> String {
use rustc::hir::*;
debug!("Trying to get a name from pattern: {:?}", p);
match p.node {
PatKind::Wild => "_".to_string(),
PatKind::Binding(_, _, _, ident, _) => ident.to_string(),
PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
PatKind::Struct(ref name, ref fields, etc) => {
format!("{} {{ {}{} }}", qpath_to_string(name),
fields.iter().map(|&Spanned { node: ref fp, .. }|
format!("{}: {}", fp.ident, name_from_pat(&*fp.pat)))
.collect::<Vec<String>>().join(", "),
if etc { ", .." } else { "" }
)
}
PatKind::Tuple(ref elts, _) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
.collect::<Vec<String>>().join(", ")),
PatKind::Box(ref p) => name_from_pat(&**p),
PatKind::Ref(ref p, _) => name_from_pat(&**p),
PatKind::Lit(..) => {
warn!("tried to get argument name from PatKind::Lit, \
which is silly in function arguments");
"()".to_string()
},
PatKind::Range(..) => panic!("tried to get argument name from PatKind::Range, \
which is not allowed in function arguments"),
PatKind::Slice(ref begin, ref mid, ref end) => {
let begin = begin.iter().map(|p| name_from_pat(&**p));
let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
let end = end.iter().map(|p| name_from_pat(&**p));
format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
},
}
}
fn print_const(cx: &DocContext<'_, '_, '_>, n: ty::LazyConst<'_>) -> String {
match n {
ty::LazyConst::Unevaluated(def_id, _) => {
if let Some(node_id) = cx.tcx.hir().as_local_node_id(def_id) {
print_const_expr(cx, cx.tcx.hir().body_owned_by(node_id))
} else {
inline::print_inlined_const(cx, def_id)
}
},
ty::LazyConst::Evaluated(n) => {
let mut s = String::new();
::rustc::mir::fmt_const_val(&mut s, n).expect("fmt_const_val failed");
// array lengths are obviously usize
if s.ends_with("usize") {
let n = s.len() - "usize".len();
s.truncate(n);
}
s
},
}
}
fn print_const_expr(cx: &DocContext<'_, '_, '_>, body: hir::BodyId) -> String {
cx.tcx.hir().hir_to_pretty_string(body.hir_id)
}
/// Given a type Path, resolve it to a Type using the TyCtxt
fn resolve_type(cx: &DocContext<'_, '_, '_>,
path: Path,
id: ast::NodeId) -> Type {
if id == ast::DUMMY_NODE_ID {
debug!("resolve_type({:?})", path);
} else {
debug!("resolve_type({:?},{:?})", path, id);
}
let is_generic = match path.def {
Def::PrimTy(p) => match p {
hir::Str => return Primitive(PrimitiveType::Str),
hir::Bool => return Primitive(PrimitiveType::Bool),
hir::Char => return Primitive(PrimitiveType::Char),
hir::Int(int_ty) => return Primitive(int_ty.into()),
hir::Uint(uint_ty) => return Primitive(uint_ty.into()),
hir::Float(float_ty) => return Primitive(float_ty.into()),
},
Def::SelfTy(..) if path.segments.len() == 1 => {
return Generic(keywords::SelfUpper.name().to_string());
}
Def::TyParam(..) if path.segments.len() == 1 => {
return Generic(format!("{:#}", path));
}
Def::SelfTy(..) | Def::TyParam(..) | Def::AssociatedTy(..) => true,
_ => false,
};
let did = register_def(&*cx, path.def);
ResolvedPath { path: path, typarams: None, did: did, is_generic: is_generic }
}
pub fn register_def(cx: &DocContext<'_, '_, '_>, def: Def) -> DefId {
debug!("register_def({:?})", def);
let (did, kind) = match def {
Def::Fn(i) => (i, TypeKind::Function),
Def::TyAlias(i) => (i, TypeKind::Typedef),
Def::Enum(i) => (i, TypeKind::Enum),
Def::Trait(i) => (i, TypeKind::Trait),
Def::Struct(i) => (i, TypeKind::Struct),
Def::Union(i) => (i, TypeKind::Union),
Def::Mod(i) => (i, TypeKind::Module),
Def::ForeignTy(i) => (i, TypeKind::Foreign),
Def::Const(i) => (i, TypeKind::Const),
Def::Static(i, _) => (i, TypeKind::Static),
Def::Variant(i) => (cx.tcx.parent_def_id(i).expect("cannot get parent def id"),
TypeKind::Enum),
Def::Macro(i, mac_kind) => match mac_kind {
MacroKind::Bang => (i, TypeKind::Macro),
MacroKind::Attr => (i, TypeKind::Attr),
MacroKind::Derive => (i, TypeKind::Derive),
MacroKind::ProcMacroStub => unreachable!(),
},
Def::TraitAlias(i) => (i, TypeKind::TraitAlias),
Def::SelfTy(Some(def_id), _) => (def_id, TypeKind::Trait),
Def::SelfTy(_, Some(impl_def_id)) => return impl_def_id,
_ => return def.def_id()
};
if did.is_local() { return did }
inline::record_extern_fqn(cx, did, kind);
if let TypeKind::Trait = kind {
inline::record_extern_trait(cx, did);
}
did
}
fn resolve_use_source(cx: &DocContext<'_, '_, '_>, path: Path) -> ImportSource {
ImportSource {
did: if path.def.opt_def_id().is_none() {
None
} else {
Some(register_def(cx, path.def))
},
path,
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Macro {
pub source: String,
pub imported_from: Option<String>,
}
impl Clean<Item> for doctree::Macro {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
let name = self.name.clean(cx);
Item {
name: Some(name.clone()),
attrs: self.attrs.clean(cx),
source: self.whence.clean(cx),
visibility: Some(Public),
stability: self.stab.clean(cx),
deprecation: self.depr.clean(cx),
def_id: self.def_id,
inner: MacroItem(Macro {
source: format!("macro_rules! {} {{\n{}}}",
name,
self.matchers.iter().map(|span| {
format!(" {} => {{ ... }};\n", span.to_src(cx))
}).collect::<String>()),
imported_from: self.imported_from.clean(cx),
}),
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct ProcMacro {
pub kind: MacroKind,
pub helpers: Vec<String>,
}
impl Clean<Item> for doctree::ProcMacro {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> Item {
Item {
name: Some(self.name.clean(cx)),
attrs: self.attrs.clean(cx),
source: self.whence.clean(cx),
visibility: Some(Public),
stability: self.stab.clean(cx),
deprecation: self.depr.clean(cx),
def_id: cx.tcx.hir().local_def_id(self.id),
inner: ProcMacroItem(ProcMacro {
kind: self.kind,
helpers: self.helpers.clean(cx),
}),
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Stability {
pub level: stability::StabilityLevel,
pub feature: Option<String>,
pub since: String,
pub deprecation: Option<Deprecation>,
pub unstable_reason: Option<String>,
pub issue: Option<u32>,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Deprecation {
pub since: Option<String>,
pub note: Option<String>,
}
impl Clean<Stability> for attr::Stability {
fn clean(&self, _: &DocContext<'_, '_, '_>) -> Stability {
Stability {
level: stability::StabilityLevel::from_attr_level(&self.level),
feature: Some(self.feature.to_string()).filter(|f| !f.is_empty()),
since: match self.level {
attr::Stable {ref since} => since.to_string(),
_ => String::new(),
},
deprecation: self.rustc_depr.as_ref().map(|d| {
Deprecation {
note: Some(d.reason.to_string()).filter(|r| !r.is_empty()),
since: Some(d.since.to_string()).filter(|d| !d.is_empty()),
}
}),
unstable_reason: match self.level {
attr::Unstable { reason: Some(ref reason), .. } => Some(reason.to_string()),
_ => None,
},
issue: match self.level {
attr::Unstable {issue, ..} => Some(issue),
_ => None,
}
}
}
}
impl<'a> Clean<Stability> for &'a attr::Stability {
fn clean(&self, dc: &DocContext<'_, '_, '_>) -> Stability {
(**self).clean(dc)
}
}
impl Clean<Deprecation> for attr::Deprecation {
fn clean(&self, _: &DocContext<'_, '_, '_>) -> Deprecation {
Deprecation {
since: self.since.map(|s| s.to_string()).filter(|s| !s.is_empty()),
note: self.note.map(|n| n.to_string()).filter(|n| !n.is_empty()),
}
}
}
/// An equality constraint on an associated type, e.g., `A = Bar` in `Foo<A = Bar>`
#[derive(Clone, PartialEq, Eq, RustcDecodable, RustcEncodable, Debug, Hash)]
pub struct TypeBinding {
pub name: String,
pub ty: Type
}
impl Clean<TypeBinding> for hir::TypeBinding {
fn clean(&self, cx: &DocContext<'_, '_, '_>) -> TypeBinding {
TypeBinding {
name: self.ident.name.clean(cx),
ty: self.ty.clean(cx)
}
}
}
pub fn def_id_to_path(
cx: &DocContext<'_, '_, '_>,
did: DefId,
name: Option<String>
) -> Vec<String> {
let crate_name = name.unwrap_or_else(|| cx.tcx.crate_name(did.krate).to_string());
let relative = cx.tcx.def_path(did).data.into_iter().filter_map(|elem| {
// extern blocks have an empty name
let s = elem.data.to_string();
if !s.is_empty() {
Some(s)
} else {
None
}
});
once(crate_name).chain(relative).collect()
}
pub fn enter_impl_trait<F, R>(cx: &DocContext<'_, '_, '_>, f: F) -> R
where
F: FnOnce() -> R,
{
let old_bounds = mem::replace(&mut *cx.impl_trait_bounds.borrow_mut(), Default::default());
let r = f();
assert!(cx.impl_trait_bounds.borrow().is_empty());
*cx.impl_trait_bounds.borrow_mut() = old_bounds;
r
}
// Start of code copied from rust-clippy
pub fn path_to_def_local(tcx: &TyCtxt<'_, '_, '_>, path: &[&str]) -> Option<DefId> {
let krate = tcx.hir().krate();
let mut items = krate.module.item_ids.clone();
let mut path_it = path.iter().peekable();
loop {
let segment = path_it.next()?;
for item_id in mem::replace(&mut items, HirVec::new()).iter() {
let item = tcx.hir().expect_item(item_id.id);
if item.ident.name == *segment {
if path_it.peek().is_none() {
return Some(tcx.hir().local_def_id(item_id.id))
}
items = match &item.node {
&hir::ItemKind::Mod(ref m) => m.item_ids.clone(),
_ => panic!("Unexpected item {:?} in path {:?} path")
};
break;
}
}
}
}
pub fn path_to_def(tcx: &TyCtxt<'_, '_, '_>, path: &[&str]) -> Option<DefId> {
let crates = tcx.crates();
let krate = crates
.iter()
.find(|&&krate| tcx.crate_name(krate) == path[0]);
if let Some(krate) = krate {
let krate = DefId {
krate: *krate,
index: CRATE_DEF_INDEX,
};
let mut items = tcx.item_children(krate);
let mut path_it = path.iter().skip(1).peekable();
loop {
let segment = path_it.next()?;
for item in mem::replace(&mut items, Lrc::new(vec![])).iter() {
if item.ident.name == *segment {
if path_it.peek().is_none() {
return match item.def {
def::Def::Trait(did) => Some(did),
_ => None,
}
}
items = tcx.item_children(item.def.def_id());
break;
}
}
}
} else {
None
}
}
pub fn get_path_for_type<F>(tcx: TyCtxt<'_, '_, '_>, def_id: DefId, def_ctor: F) -> hir::Path
where F: Fn(DefId) -> Def {
#[derive(Debug)]
struct AbsolutePathBuffer {
names: Vec<String>,
}
impl ty::item_path::ItemPathBuffer for AbsolutePathBuffer {
fn root_mode(&self) -> &ty::item_path::RootMode {
const ABSOLUTE: &'static ty::item_path::RootMode = &ty::item_path::RootMode::Absolute;
ABSOLUTE
}
fn push(&mut self, text: &str) {
self.names.push(text.to_owned());
}
}
let mut apb = AbsolutePathBuffer { names: vec![] };
tcx.push_item_path(&mut apb, def_id, false);
hir::Path {
span: DUMMY_SP,
def: def_ctor(def_id),
segments: hir::HirVec::from_vec(apb.names.iter().map(|s| hir::PathSegment {
ident: ast::Ident::from_str(&s),
id: None,
hir_id: None,
def: None,
args: None,
infer_types: false,
}).collect())
}
}
// End of code copied from rust-clippy
#[derive(Eq, PartialEq, Hash, Copy, Clone, Debug)]
enum RegionTarget<'tcx> {
Region(Region<'tcx>),
RegionVid(RegionVid)
}
#[derive(Default, Debug, Clone)]
struct RegionDeps<'tcx> {
larger: FxHashSet<RegionTarget<'tcx>>,
smaller: FxHashSet<RegionTarget<'tcx>>
}
#[derive(Eq, PartialEq, Hash, Debug)]
enum SimpleBound {
TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
Outlives(Lifetime),
}
enum AutoTraitResult {
ExplicitImpl,
PositiveImpl(Generics),
NegativeImpl,
}
impl AutoTraitResult {
fn is_auto(&self) -> bool {
match *self {
AutoTraitResult::PositiveImpl(_) | AutoTraitResult::NegativeImpl => true,
_ => false,
}
}
}
impl From<GenericBound> for SimpleBound {
fn from(bound: GenericBound) -> Self {
match bound.clone() {
GenericBound::Outlives(l) => SimpleBound::Outlives(l),
GenericBound::TraitBound(t, mod_) => match t.trait_ {
Type::ResolvedPath { path, typarams, .. } => {
SimpleBound::TraitBound(path.segments,
typarams
.map_or_else(|| Vec::new(), |v| v.iter()
.map(|p| SimpleBound::from(p.clone()))
.collect()),
t.generic_params,
mod_)
}
_ => panic!("Unexpected bound {:?}", bound),
}
}
}
}
| 35.851559 | 100 | 0.495386 |
f95494a569b2f6a31c6d79ad3df0cdd257c40d5e | 1,172 | use crate::structure::guid_prefix::GuidPrefix_t;
use speedy::{Readable, Writable};
/// This message is sent from an RTPS Writer to an RTPS Reader
/// to modify the GuidPrefix used to interpret the Reader entityIds
/// appearing in the Submessages that follow it.
#[derive(Debug, PartialEq, Readable, Writable)]
pub struct InfoDestination {
/// Provides the GuidPrefix that should be used to reconstruct the GUIDs
/// of all the RTPS Reader entities whose EntityIds appears
/// in the Submessages that follow.
pub guid_prefix: GuidPrefix_t,
}
#[cfg(test)]
mod tests {
use super::*;
serialization_test!( type = InfoDestination,
{
info_destination,
InfoDestination {
guid_prefix: GuidPrefix_t {
entity_key: [0x01, 0x02, 0x6D, 0x3F,
0x7E, 0x07, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00]
}
},
le = [0x01, 0x02, 0x6D, 0x3F,
0x7E, 0x07, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00],
be = [0x01, 0x02, 0x6D, 0x3F,
0x7E, 0x07, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00]
});
}
| 31.675676 | 76 | 0.590444 |
e246c3c9238b3b2116cb465ef8f0bde0069a618f | 1,554 | use js_sys::{ArrayBuffer, DataView};
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
use wasm_bindgen_test::*;
use web_sys::Response;
#[wasm_bindgen(module = "/tests/wasm/response.js")]
extern "wasm-bindgen" {
fn new_response() -> Response;
}
#[wasm_bindgen_test]
fn test_response_from_js() {
let response = new_response();
assert!(!response.ok());
assert!(!response.redirected());
assert_eq!(response.status(), 501);
}
#[wasm_bindgen_test]
async fn test_response_from_bytes() {
let mut bytes: [u8; 3] = [1, 3, 5];
let response = Response::new_with_opt_u8_array(Some(&mut bytes)).unwrap();
assert!(response.ok());
assert_eq!(response.status(), 200);
let buf_promise = response.array_buffer().unwrap();
let buf_val = JsFuture::from(buf_promise).await.unwrap();
assert!(buf_val.is_instance_of::<ArrayBuffer>());
let array_buf: ArrayBuffer = buf_val.dyn_into().unwrap();
let data_view = DataView::new(&array_buf, 0, bytes.len());
for (i, byte) in bytes.iter().enumerate() {
assert_eq!(&data_view.get_uint8(i), byte);
}
}
#[wasm_bindgen_test]
async fn test_response_from_other_body() {
let input = "Hello, world!";
let response_a = Response::new_with_opt_str(Some(input)).unwrap();
let body = response_a.body();
let response_b = Response::new_with_opt_readable_stream(body.as_ref()).unwrap();
let output = JsFuture::from(response_b.text().unwrap()).await.unwrap();
assert_eq!(JsValue::from_str(input), output);
}
| 33.06383 | 84 | 0.690476 |
09593afdb4b21d515f341c5dea6d8c903ec32f3a | 11,325 | //! Async-graphql integration with Wrap
#![warn(missing_docs)]
#![allow(clippy::type_complexity)]
#![allow(clippy::needless_doctest_main)]
use async_graphql::http::StreamBody;
use async_graphql::{
Data, FieldResult, IntoQueryBuilder, IntoQueryBuilderOpts, ObjectType, QueryBuilder,
QueryResponse, Schema, SubscriptionType, WebSocketTransport,
};
use bytes::Bytes;
use futures::select;
use futures::{SinkExt, StreamExt};
use std::sync::Arc;
use warp::filters::ws::Message;
use warp::filters::BoxedFilter;
use warp::reject::Reject;
use warp::reply::Response;
use warp::{Filter, Rejection, Reply};
/// Bad request error
///
/// It's a wrapper of `async_graphql::ParseRequestError`.
pub struct BadRequest(pub async_graphql::ParseRequestError);
impl std::fmt::Debug for BadRequest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl Reject for BadRequest {}
/// GraphQL request filter
///
/// It outputs a tuple containing the `Schema` and `QuertBuilder`.
///
/// # Examples
/// *[Full Example](<https://github.com/async-graphql/examples/blob/master/warp/starwars/src/main.rs>)*
///
/// ```no_run
///
/// use async_graphql::*;
/// use async_graphql_warp::*;
/// use warp::Filter;
/// use std::convert::Infallible;
///
/// struct QueryRoot;
///
/// #[Object]
/// impl QueryRoot {
/// #[field]
/// async fn value(&self, ctx: &Context<'_>) -> i32 {
/// unimplemented!()
/// }
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let schema = Schema::new(QueryRoot, EmptyMutation, EmptySubscription);
/// let filter = async_graphql_warp::graphql(schema).and_then(|(schema, builder): (_, QueryBuilder)| async move {
/// Ok::<_, Infallible>(GQLResponse::from(builder.execute(&schema).await))
/// });
/// warp::serve(filter).run(([0, 0, 0, 0], 8000)).await;
/// }
/// ```
pub fn graphql<Query, Mutation, Subscription>(
schema: Schema<Query, Mutation, Subscription>,
) -> BoxedFilter<((Schema<Query, Mutation, Subscription>, QueryBuilder),)>
where
Query: ObjectType + Send + Sync + 'static,
Mutation: ObjectType + Send + Sync + 'static,
Subscription: SubscriptionType + Send + Sync + 'static,
{
warp::any()
.and(warp::post())
.and(warp::header::optional::<String>("content-type"))
.and(warp::body::stream())
.and(warp::any().map(move || schema.clone()))
.and_then(|content_type, body, schema| async move {
let builder = (content_type, StreamBody::new(body))
.into_query_builder()
.await
.map_err(|err| warp::reject::custom(BadRequest(err)))?;
Ok::<_, Rejection>((schema, builder))
})
.boxed()
}
/// Similar to graphql, but you can set the options `IntoQueryBuilderOpts`.
pub fn graphql_opts<Query, Mutation, Subscription>(
schema: Schema<Query, Mutation, Subscription>,
opts: IntoQueryBuilderOpts,
) -> BoxedFilter<((Schema<Query, Mutation, Subscription>, QueryBuilder),)>
where
Query: ObjectType + Send + Sync + 'static,
Mutation: ObjectType + Send + Sync + 'static,
Subscription: SubscriptionType + Send + Sync + 'static,
{
let opts = Arc::new(opts);
warp::any()
.and(warp::post())
.and(warp::header::optional::<String>("content-type"))
.and(warp::body::stream())
.and(warp::any().map(move || opts.clone()))
.and(warp::any().map(move || schema.clone()))
.and_then(
|content_type, body, opts: Arc<IntoQueryBuilderOpts>, schema| async move {
let builder = (content_type, StreamBody::new(body))
.into_query_builder_opts(&opts)
.await
.map_err(|err| warp::reject::custom(BadRequest(err)))?;
Ok::<_, Rejection>((schema, builder))
},
)
.boxed()
}
/// GraphQL subscription filter
///
/// # Examples
///
/// ```no_run
/// use async_graphql::*;
/// use async_graphql_warp::*;
/// use warp::Filter;
/// use futures::{Stream, StreamExt};
/// use std::time::Duration;
///
/// struct QueryRoot;
///
/// #[Object]
/// impl QueryRoot {}
///
/// struct SubscriptionRoot;
///
/// #[Subscription]
/// impl SubscriptionRoot {
/// #[field]
/// async fn tick(&self) -> impl Stream<Item = String> {
/// tokio::time::interval(Duration::from_secs(1)).map(|n| format!("{}", n.elapsed().as_secs_f32()))
/// }
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let schema = Schema::new(QueryRoot, EmptyMutation, SubscriptionRoot);
/// let filter = async_graphql_warp::graphql_subscription(schema);
/// warp::serve(filter).run(([0, 0, 0, 0], 8000)).await;
/// }
/// ```
pub fn graphql_subscription<Query, Mutation, Subscription>(
schema: Schema<Query, Mutation, Subscription>,
) -> BoxedFilter<(impl Reply,)>
where
Query: ObjectType + Sync + Send + 'static,
Mutation: ObjectType + Sync + Send + 'static,
Subscription: SubscriptionType + Send + Sync + 'static,
{
warp::any()
.and(warp::ws())
.and(warp::any().map(move || schema.clone()))
.map(
|ws: warp::ws::Ws, schema: Schema<Query, Mutation, Subscription>| {
ws.on_upgrade(move |websocket| {
let (mut tx, rx) = websocket.split();
let (mut stx, srx) =
schema.subscription_connection(WebSocketTransport::default());
let mut rx = rx.fuse();
let mut srx = srx.fuse();
async move {
loop {
select! {
bytes = srx.next() => {
if let Some(bytes) = bytes {
if let Ok(text) = String::from_utf8(bytes.to_vec()) {
if tx.send(Message::text(text)).await.is_err()
{
return;
}
}
} else {
return;
}
}
msg = rx.next() => {
if let Some(Ok(msg)) = msg {
if msg.is_text() {
if stx.send(Bytes::copy_from_slice(msg.as_bytes())).await.is_err() {
return;
}
}
}
}
}
}
}
})
},
).map(|reply| {
warp::reply::with_header(reply, "Sec-WebSocket-Protocol", "graphql-ws")
})
.boxed()
}
/// GraphQL subscription filter
///
/// Specifies that a function converts the init payload to data.
pub fn graphql_subscription_with_data<Query, Mutation, Subscription, F>(
schema: Schema<Query, Mutation, Subscription>,
init_context_data: F,
) -> BoxedFilter<(impl Reply,)>
where
Query: ObjectType + Sync + Send + 'static,
Mutation: ObjectType + Sync + Send + 'static,
Subscription: SubscriptionType + Send + Sync + 'static,
F: Fn(serde_json::Value) -> FieldResult<Data> + Send + Sync + Clone + 'static,
{
warp::any()
.and(warp::ws())
.and(warp::any().map(move || schema.clone()))
.and(warp::any().map(move || init_context_data.clone()))
.map(
|ws: warp::ws::Ws, schema: Schema<Query, Mutation, Subscription>, init_context_data: F| {
ws.on_upgrade(move |websocket| {
let (mut tx, rx) = websocket.split();
let (mut stx, srx) =
schema.subscription_connection(WebSocketTransport::new(init_context_data));
let mut rx = rx.fuse();
let mut srx = srx.fuse();
async move {
loop {
select! {
bytes = srx.next() => {
if let Some(bytes) = bytes {
if let Ok(text) = String::from_utf8(bytes.to_vec()) {
if tx.send(Message::text(text)).await.is_err() {
return;
}
}
} else {
return;
}
}
msg = rx.next() => {
if let Some(Ok(msg)) = msg {
if msg.is_text() {
if stx.send(Bytes::copy_from_slice(msg.as_bytes())).await.is_err() {
return;
}
}
}
}
}
}
}
})
},
).map(|reply| {
warp::reply::with_header(reply, "Sec-WebSocket-Protocol", "graphql-ws")
})
.boxed()
}
/// GraphQL reply
pub struct GQLResponse(async_graphql::Result<QueryResponse>);
impl From<async_graphql::Result<QueryResponse>> for GQLResponse {
fn from(resp: async_graphql::Result<QueryResponse>) -> Self {
GQLResponse(resp)
}
}
fn add_cache_control(http_resp: &mut Response, resp: &async_graphql::Result<QueryResponse>) {
if let Ok(QueryResponse { cache_control, .. }) = resp {
if let Some(cache_control) = cache_control.value() {
if let Ok(value) = cache_control.parse() {
http_resp.headers_mut().insert("cache-control", value);
}
}
}
}
impl Reply for GQLResponse {
fn into_response(self) -> Response {
let gql_resp = async_graphql::http::GQLResponse(self.0);
let mut resp = warp::reply::with_header(
warp::reply::json(&gql_resp),
"content-type",
"application/json",
)
.into_response();
add_cache_control(&mut resp, &gql_resp.0);
resp
}
}
// Waiting for this release: https://github.com/hyperium/hyper/commit/042c770603a212f22387807efe4fc672959df40c
// /// GraphQL streaming reply
// pub struct GQLResponseStream(StreamResponse);
//
// impl From<StreamResponse> for GQLResponseStream {
// fn from(resp: StreamResponse) -> Self {
// GQLResponseStream(resp)
// }
// }
//
// impl Reply for GQLResponseStream {
// fn into_response(self) -> Response {
// match self.0 {
// StreamResponse::Single(resp) => GQLResponse(resp).into_response(),
// StreamResponse::Stream()
// }
// }
// }
| 35.280374 | 117 | 0.497572 |
6202daff418bfd42ae0561323bf9818381575a12 | 3,118 | // Copyright 2020 the Deno authors. All rights reserved. MIT license.
use super::{Context, LintRule};
use swc_common::Spanned;
use swc_ecma_ast::BinaryOp::{EqEq, EqEqEq, NotEq, NotEqEq};
use swc_ecma_ast::Expr::{Lit, Unary};
use swc_ecma_ast::Lit::Str;
use swc_ecma_ast::UnaryOp::TypeOf;
use swc_ecma_ast::{BinExpr, Module};
use swc_ecma_visit::{Node, Visit};
pub struct ValidTypeof;
impl LintRule for ValidTypeof {
fn new() -> Box<Self> {
Box::new(ValidTypeof)
}
fn code(&self) -> &'static str {
"valid-typeof"
}
fn lint_module(&self, context: Context, module: Module) {
let mut visitor = ValidTypeofVisitor::new(context);
visitor.visit_module(&module, &module);
}
}
pub struct ValidTypeofVisitor {
context: Context,
}
impl ValidTypeofVisitor {
pub fn new(context: Context) -> Self {
Self { context }
}
}
impl Visit for ValidTypeofVisitor {
fn visit_bin_expr(&mut self, bin_expr: &BinExpr, _parent: &dyn Node) {
if !bin_expr.is_eq_expr() {
return;
}
match (&*bin_expr.left, &*bin_expr.right) {
(Unary(unary), operand) | (operand, Unary(unary))
if unary.op == TypeOf =>
{
match operand {
Unary(unary) if unary.op == TypeOf => {}
Lit(Str(str)) => {
if !is_valid_typeof_string(&str.value) {
self.context.add_diagnostic(
str.span,
"valid-typeof",
"Invalid typeof comparison value",
);
}
}
_ => {
self.context.add_diagnostic(
operand.span(),
"valid-typeof",
"Invalid typeof comparison value",
);
}
}
}
_ => {}
}
}
}
fn is_valid_typeof_string(str: &str) -> bool {
match str {
"undefined" | "object" | "boolean" | "number" | "string" | "function"
| "symbol" | "bigint" => true,
_ => false,
}
}
trait EqExpr {
fn is_eq_expr(&self) -> bool;
}
impl EqExpr for BinExpr {
fn is_eq_expr(&self) -> bool {
match self.op {
EqEq | NotEq | EqEqEq | NotEqEq => true,
_ => false,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_util::*;
#[test]
fn it_passes_using_valid_strings() {
assert_lint_ok::<ValidTypeof>(
r#"
typeof foo === "string"
typeof bar == "undefined"
"#,
);
}
#[test]
fn it_passes_using_two_typeof_operations() {
assert_lint_ok::<ValidTypeof>(r#"typeof bar === typeof qux"#);
}
#[test]
fn it_fails_using_invalid_strings() {
assert_lint_err::<ValidTypeof>(r#"typeof foo === "strnig""#, 15);
assert_lint_err::<ValidTypeof>(r#"typeof foo == "undefimed""#, 14);
assert_lint_err::<ValidTypeof>(r#"typeof bar != "nunber""#, 14);
assert_lint_err::<ValidTypeof>(r#"typeof bar !== "fucntion""#, 15);
}
#[test]
fn it_fails_not_using_strings() {
assert_lint_err::<ValidTypeof>(r#"typeof foo === undefined"#, 15);
assert_lint_err::<ValidTypeof>(r#"typeof bar == Object"#, 14);
assert_lint_err::<ValidTypeof>(r#"typeof baz === anotherVariable"#, 15);
}
}
| 24.170543 | 76 | 0.589801 |
2f18554ffa3022acf09d3b188049c2f040b0340c | 15,125 | #![warn(rust_2018_idioms)]
use slab::*;
use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
#[test]
fn insert_get_remove_one() {
let mut slab = Slab::new();
assert!(slab.is_empty());
let key = slab.insert(10);
assert_eq!(slab[key], 10);
assert_eq!(slab.get(key), Some(&10));
assert!(!slab.is_empty());
assert!(slab.contains(key));
assert_eq!(slab.remove(key), 10);
assert!(!slab.contains(key));
assert!(slab.get(key).is_none());
}
#[test]
fn insert_get_many() {
let mut slab = Slab::with_capacity(10);
for i in 0..10 {
let key = slab.insert(i + 10);
assert_eq!(slab[key], i + 10);
}
assert_eq!(slab.capacity(), 10);
// Storing another one grows the slab
let key = slab.insert(20);
assert_eq!(slab[key], 20);
// Capacity grows by 2x
assert_eq!(slab.capacity(), 20);
}
#[test]
fn insert_get_remove_many() {
let mut slab = Slab::with_capacity(10);
let mut keys = vec![];
for i in 0..10 {
for j in 0..10 {
let val = (i * 10) + j;
let key = slab.insert(val);
keys.push((key, val));
assert_eq!(slab[key], val);
}
for (key, val) in keys.drain(..) {
assert_eq!(val, slab.remove(key));
}
}
assert_eq!(10, slab.capacity());
}
#[test]
fn insert_with_vacant_entry() {
let mut slab = Slab::with_capacity(1);
let key;
{
let entry = slab.vacant_entry();
key = entry.key();
entry.insert(123);
}
assert_eq!(123, slab[key]);
}
#[test]
fn get_vacant_entry_without_using() {
let mut slab = Slab::<usize>::with_capacity(1);
let key = slab.vacant_entry().key();
assert_eq!(key, slab.vacant_entry().key());
}
#[test]
#[should_panic(expected = "invalid key")]
fn invalid_get_panics() {
let slab = Slab::<usize>::with_capacity(1);
let _ = &slab[0];
}
#[test]
#[should_panic(expected = "invalid key")]
fn invalid_get_mut_panics() {
let mut slab = Slab::<usize>::new();
let _ = &mut slab[0];
}
#[test]
#[should_panic(expected = "invalid key")]
fn double_remove_panics() {
let mut slab = Slab::<usize>::with_capacity(1);
let key = slab.insert(123);
slab.remove(key);
slab.remove(key);
}
#[test]
#[should_panic(expected = "invalid key")]
fn invalid_remove_panics() {
let mut slab = Slab::<usize>::with_capacity(1);
slab.remove(0);
}
#[test]
fn slab_get_mut() {
let mut slab = Slab::new();
let key = slab.insert(1);
slab[key] = 2;
assert_eq!(slab[key], 2);
*slab.get_mut(key).unwrap() = 3;
assert_eq!(slab[key], 3);
}
#[test]
fn key_of_tagged() {
let mut slab = Slab::new();
slab.insert(0);
assert_eq!(slab.key_of(&slab[0]), 0);
}
#[test]
fn key_of_layout_optimizable() {
// Entry<&str> doesn't need a discriminant tag because it can use the
// nonzero-ness of ptr and store Vacant's next at the same offset as len
let mut slab = Slab::new();
slab.insert("foo");
slab.insert("bar");
let third = slab.insert("baz");
slab.insert("quux");
assert_eq!(slab.key_of(&slab[third]), third);
}
#[test]
fn key_of_zst() {
let mut slab = Slab::new();
slab.insert(());
let second = slab.insert(());
slab.insert(());
assert_eq!(slab.key_of(&slab[second]), second);
}
#[test]
fn reserve_does_not_allocate_if_available() {
let mut slab = Slab::with_capacity(10);
let mut keys = vec![];
for i in 0..6 {
keys.push(slab.insert(i));
}
for key in 0..4 {
slab.remove(key);
}
assert!(slab.capacity() - slab.len() == 8);
slab.reserve(8);
assert_eq!(10, slab.capacity());
}
#[test]
fn reserve_exact_does_not_allocate_if_available() {
let mut slab = Slab::with_capacity(10);
let mut keys = vec![];
for i in 0..6 {
keys.push(slab.insert(i));
}
for key in 0..4 {
slab.remove(key);
}
assert!(slab.capacity() - slab.len() == 8);
slab.reserve_exact(8);
assert_eq!(10, slab.capacity());
}
#[test]
#[should_panic(expected = "capacity overflow")]
fn reserve_does_panic_with_capacity_overflow() {
let mut slab = Slab::with_capacity(10);
slab.insert(true);
slab.reserve(std::usize::MAX);
}
#[test]
#[should_panic(expected = "capacity overflow")]
fn reserve_exact_does_panic_with_capacity_overflow() {
let mut slab = Slab::with_capacity(10);
slab.insert(true);
slab.reserve_exact(std::usize::MAX);
}
#[test]
fn retain() {
let mut slab = Slab::with_capacity(2);
let key1 = slab.insert(0);
let key2 = slab.insert(1);
slab.retain(|key, x| {
assert_eq!(key, *x);
*x % 2 == 0
});
assert_eq!(slab.len(), 1);
assert_eq!(slab[key1], 0);
assert!(!slab.contains(key2));
// Ensure consistency is retained
let key = slab.insert(123);
assert_eq!(key, key2);
assert_eq!(2, slab.len());
assert_eq!(2, slab.capacity());
// Inserting another element grows
let key = slab.insert(345);
assert_eq!(key, 2);
assert_eq!(4, slab.capacity());
}
#[test]
fn into_iter() {
let mut slab = Slab::new();
for i in 0..8 {
slab.insert(i);
}
slab.remove(0);
slab.remove(4);
slab.remove(5);
slab.remove(7);
let vals: Vec<_> = slab
.into_iter()
.inspect(|&(key, val)| assert_eq!(key, val))
.map(|(_, val)| val)
.collect();
assert_eq!(vals, vec![1, 2, 3, 6]);
}
#[test]
fn into_iter_rev() {
let mut slab = Slab::new();
for i in 0..4 {
slab.insert(i);
}
let mut iter = slab.into_iter();
assert_eq!(iter.next_back(), Some((3, 3)));
assert_eq!(iter.next_back(), Some((2, 2)));
assert_eq!(iter.next(), Some((0, 0)));
assert_eq!(iter.next_back(), Some((1, 1)));
assert_eq!(iter.next_back(), None);
assert_eq!(iter.next(), None);
}
#[test]
fn iter() {
let mut slab = Slab::new();
for i in 0..4 {
slab.insert(i);
}
let vals: Vec<_> = slab
.iter()
.enumerate()
.map(|(i, (key, val))| {
assert_eq!(i, key);
*val
})
.collect();
assert_eq!(vals, vec![0, 1, 2, 3]);
slab.remove(1);
let vals: Vec<_> = slab.iter().map(|(_, r)| *r).collect();
assert_eq!(vals, vec![0, 2, 3]);
}
#[test]
fn iter_rev() {
let mut slab = Slab::new();
for i in 0..4 {
slab.insert(i);
}
slab.remove(0);
let vals = slab.iter().rev().collect::<Vec<_>>();
assert_eq!(vals, vec![(3, &3), (2, &2), (1, &1)]);
}
#[test]
fn iter_mut() {
let mut slab = Slab::new();
for i in 0..4 {
slab.insert(i);
}
for (i, (key, e)) in slab.iter_mut().enumerate() {
assert_eq!(i, key);
*e += 1;
}
let vals: Vec<_> = slab.iter().map(|(_, r)| *r).collect();
assert_eq!(vals, vec![1, 2, 3, 4]);
slab.remove(2);
for (_, e) in slab.iter_mut() {
*e += 1;
}
let vals: Vec<_> = slab.iter().map(|(_, r)| *r).collect();
assert_eq!(vals, vec![2, 3, 5]);
}
#[test]
fn iter_mut_rev() {
let mut slab = Slab::new();
for i in 0..4 {
slab.insert(i);
}
slab.remove(2);
{
let mut iter = slab.iter_mut();
assert_eq!(iter.next(), Some((0, &mut 0)));
let mut prev_key = !0;
for (key, e) in iter.rev() {
*e += 10;
assert!(prev_key > key);
prev_key = key;
}
}
assert_eq!(slab[0], 0);
assert_eq!(slab[1], 11);
assert_eq!(slab[3], 13);
assert!(!slab.contains(2));
}
#[test]
fn from_iterator_sorted() {
let mut slab = (0..5).map(|i| (i, i)).collect::<Slab<_>>();
assert_eq!(slab.len(), 5);
assert_eq!(slab[0], 0);
assert_eq!(slab[2], 2);
assert_eq!(slab[4], 4);
assert_eq!(slab.vacant_entry().key(), 5);
}
#[test]
fn from_iterator_new_in_order() {
// all new keys come in increasing order, but existing keys are overwritten
let mut slab = [(0, 'a'), (1, 'a'), (1, 'b'), (0, 'b'), (9, 'a'), (0, 'c')]
.iter()
.cloned()
.collect::<Slab<_>>();
assert_eq!(slab.len(), 3);
assert_eq!(slab[0], 'c');
assert_eq!(slab[1], 'b');
assert_eq!(slab[9], 'a');
assert_eq!(slab.get(5), None);
assert_eq!(slab.vacant_entry().key(), 8);
}
#[test]
fn from_iterator_unordered() {
let mut slab = vec![(1, "one"), (50, "fifty"), (3, "three"), (20, "twenty")]
.into_iter()
.collect::<Slab<_>>();
assert_eq!(slab.len(), 4);
assert_eq!(slab.vacant_entry().key(), 0);
let mut iter = slab.iter();
assert_eq!(iter.next(), Some((1, &"one")));
assert_eq!(iter.next(), Some((3, &"three")));
assert_eq!(iter.next(), Some((20, &"twenty")));
assert_eq!(iter.next(), Some((50, &"fifty")));
assert_eq!(iter.next(), None);
}
#[test]
fn clear() {
let mut slab = Slab::new();
for i in 0..4 {
slab.insert(i);
}
// clear full
slab.clear();
let vals: Vec<_> = slab.iter().map(|(_, r)| *r).collect();
assert!(vals.is_empty());
assert_eq!(0, slab.len());
assert_eq!(4, slab.capacity());
for i in 0..2 {
slab.insert(i);
}
let vals: Vec<_> = slab.iter().map(|(_, r)| *r).collect();
assert_eq!(vals, vec![0, 1]);
// clear half-filled
slab.clear();
let vals: Vec<_> = slab.iter().map(|(_, r)| *r).collect();
assert!(vals.is_empty());
}
#[test]
fn shrink_to_fit_empty() {
let mut slab = Slab::<bool>::with_capacity(20);
slab.shrink_to_fit();
assert_eq!(slab.capacity(), 0);
}
#[test]
fn shrink_to_fit_no_vacant() {
let mut slab = Slab::with_capacity(20);
slab.insert(String::new());
slab.shrink_to_fit();
assert!(slab.capacity() < 10);
}
#[test]
fn shrink_to_fit_doesnt_move() {
let mut slab = Slab::with_capacity(8);
slab.insert("foo");
let bar = slab.insert("bar");
slab.insert("baz");
let quux = slab.insert("quux");
slab.remove(quux);
slab.remove(bar);
slab.shrink_to_fit();
assert_eq!(slab.len(), 2);
assert!(slab.capacity() >= 3);
assert_eq!(slab.get(0), Some(&"foo"));
assert_eq!(slab.get(2), Some(&"baz"));
assert_eq!(slab.vacant_entry().key(), bar);
}
#[test]
fn shrink_to_fit_doesnt_recreate_list_when_nothing_can_be_done() {
let mut slab = Slab::with_capacity(16);
for i in 0..4 {
slab.insert(Box::new(i));
}
slab.remove(0);
slab.remove(2);
slab.remove(1);
assert_eq!(slab.vacant_entry().key(), 1);
slab.shrink_to_fit();
assert_eq!(slab.len(), 1);
assert!(slab.capacity() >= 4);
assert_eq!(slab.vacant_entry().key(), 1);
}
#[test]
fn compact_empty() {
let mut slab = Slab::new();
slab.compact(|_, _, _| panic!());
assert_eq!(slab.len(), 0);
assert_eq!(slab.capacity(), 0);
slab.reserve(20);
slab.compact(|_, _, _| panic!());
assert_eq!(slab.len(), 0);
assert_eq!(slab.capacity(), 0);
slab.insert(0);
slab.insert(1);
slab.insert(2);
slab.remove(1);
slab.remove(2);
slab.remove(0);
slab.compact(|_, _, _| panic!());
assert_eq!(slab.len(), 0);
assert_eq!(slab.capacity(), 0);
}
#[test]
fn compact_no_moves_needed() {
let mut slab = Slab::new();
for i in 0..10 {
slab.insert(i);
}
slab.remove(8);
slab.remove(9);
slab.remove(6);
slab.remove(7);
slab.compact(|_, _, _| panic!());
assert_eq!(slab.len(), 6);
for ((index, &value), want) in slab.iter().zip(0..6) {
assert!(index == value);
assert_eq!(index, want);
}
assert!(slab.capacity() >= 6 && slab.capacity() < 10);
}
#[test]
fn compact_moves_successfully() {
let mut slab = Slab::with_capacity(20);
for i in 0..10 {
slab.insert(i);
}
for &i in &[0, 5, 9, 6, 3] {
slab.remove(i);
}
let mut moved = 0;
slab.compact(|&mut v, from, to| {
assert!(from > to);
assert!(from >= 5);
assert!(to < 5);
assert_eq!(from, v);
moved += 1;
true
});
assert_eq!(slab.len(), 5);
assert_eq!(moved, 2);
assert_eq!(slab.vacant_entry().key(), 5);
assert!(slab.capacity() >= 5 && slab.capacity() < 20);
let mut iter = slab.iter();
assert_eq!(iter.next(), Some((0, &8)));
assert_eq!(iter.next(), Some((1, &1)));
assert_eq!(iter.next(), Some((2, &2)));
assert_eq!(iter.next(), Some((3, &7)));
assert_eq!(iter.next(), Some((4, &4)));
assert_eq!(iter.next(), None);
}
#[test]
fn compact_doesnt_move_if_closure_errors() {
let mut slab = Slab::with_capacity(20);
for i in 0..10 {
slab.insert(i);
}
for &i in &[9, 3, 1, 4, 0] {
slab.remove(i);
}
slab.compact(|&mut v, from, to| {
assert!(from > to);
assert_eq!(from, v);
v != 6
});
assert_eq!(slab.len(), 5);
assert!(slab.capacity() >= 7 && slab.capacity() < 20);
assert_eq!(slab.vacant_entry().key(), 3);
let mut iter = slab.iter();
assert_eq!(iter.next(), Some((0, &8)));
assert_eq!(iter.next(), Some((1, &7)));
assert_eq!(iter.next(), Some((2, &2)));
assert_eq!(iter.next(), Some((5, &5)));
assert_eq!(iter.next(), Some((6, &6)));
assert_eq!(iter.next(), None);
}
#[test]
fn compact_handles_closure_panic() {
let mut slab = Slab::new();
for i in 0..10 {
slab.insert(i);
}
for i in 1..6 {
slab.remove(i);
}
let result = catch_unwind(AssertUnwindSafe(|| {
slab.compact(|&mut v, from, to| {
assert!(from > to);
assert_eq!(from, v);
if v == 7 {
panic!("test");
}
true
})
}));
match result {
Err(ref payload) if payload.downcast_ref() == Some(&"test") => {}
Err(bug) => resume_unwind(bug),
Ok(()) => unreachable!(),
}
assert_eq!(slab.len(), 5 - 1);
assert_eq!(slab.vacant_entry().key(), 3);
let mut iter = slab.iter();
assert_eq!(iter.next(), Some((0, &0)));
assert_eq!(iter.next(), Some((1, &9)));
assert_eq!(iter.next(), Some((2, &8)));
assert_eq!(iter.next(), Some((6, &6)));
assert_eq!(iter.next(), None);
}
#[test]
fn fully_consumed_drain() {
let mut slab = Slab::new();
for i in 0..3 {
slab.insert(i);
}
{
let mut drain = slab.drain();
assert_eq!(Some(0), drain.next());
assert_eq!(Some(1), drain.next());
assert_eq!(Some(2), drain.next());
assert_eq!(None, drain.next());
}
assert!(slab.is_empty());
}
#[test]
fn partially_consumed_drain() {
let mut slab = Slab::new();
for i in 0..3 {
slab.insert(i);
}
{
let mut drain = slab.drain();
assert_eq!(Some(0), drain.next());
}
assert!(slab.is_empty())
}
#[test]
fn drain_rev() {
let mut slab = Slab::new();
for i in 0..10 {
slab.insert(i);
}
slab.remove(9);
let vals: Vec<u64> = slab.drain().rev().collect();
assert_eq!(vals, (0..9).rev().collect::<Vec<u64>>());
}
| 22.847432 | 80 | 0.543802 |
6950df95da0959fa0f4525987a941917162fd1a5 | 1,344 | use conquer_once::spin::Lazy;
use x86_64::structures::gdt::{Descriptor, GlobalDescriptorTable, SegmentSelector};
use x86_64::structures::tss::TaskStateSegment;
use x86_64::VirtAddr;
pub const DOUBLE_FAULT_IST_INDEX: u16 = 0;
static TSS: Lazy<TaskStateSegment> = Lazy::new(|| {
let mut tss = TaskStateSegment::new();
tss.interrupt_stack_table[DOUBLE_FAULT_IST_INDEX as usize] = {
const STACK_SIZE: usize = 4096;
static mut STACK: [u8; STACK_SIZE] = [0; STACK_SIZE];
let stack_start = VirtAddr::from_ptr(unsafe { &STACK });
let stack_end = stack_start + STACK_SIZE;
stack_end
};
tss
});
static GDT: Lazy<(GlobalDescriptorTable, Selectors)> = Lazy::new(|| {
let mut gdt = GlobalDescriptorTable::new();
let code_selector = gdt.add_entry(Descriptor::kernel_code_segment());
let tss_selector = gdt.add_entry(Descriptor::tss_segment(&TSS));
(
gdt,
Selectors {
code_selector,
tss_selector,
},
)
});
struct Selectors {
code_selector: SegmentSelector,
tss_selector: SegmentSelector,
}
pub fn init() {
use x86_64::instructions::segmentation::set_cs;
use x86_64::instructions::tables::load_tss;
GDT.0.load();
unsafe {
set_cs(GDT.1.code_selector);
load_tss(GDT.1.tss_selector);
}
}
| 27.428571 | 82 | 0.659226 |
33b7483fb5620550dbcde0b6c1cea08179a3b140 | 11,363 | // Copyright Materialize, Inc. 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 SQL stream processor built on top of [timely dataflow] and
//! [differential dataflow].
//!
//! [differential dataflow]: ../differential_dataflow/index.html
//! [timely dataflow]: ../timely/index.html
use std::convert::TryInto;
use std::env;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::time::Duration;
use compile_time_run::run_command_str;
use futures::StreamExt;
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod, SslVerifyMode};
use tokio::net::TcpListener;
use tokio::sync::oneshot;
use tokio_stream::wrappers::TcpListenerStream;
use build_info::BuildInfo;
use coord::{CacheConfig, LoggingConfig, PersistenceConfig};
use crate::mux::Mux;
mod http;
mod mux;
mod server_metrics;
mod version_check;
// Disable jemalloc on macOS, as it is not well supported [0][1][2].
// The issues present as runaway latency on load test workloads that are
// comfortably handled by the macOS system allocator. Consider re-evaluating if
// jemalloc's macOS support improves.
//
// [0]: https://github.com/jemalloc/jemalloc/issues/26
// [1]: https://github.com/jemalloc/jemalloc/issues/843
// [2]: https://github.com/jemalloc/jemalloc/issues/1467
#[cfg(not(target_os = "macos"))]
#[global_allocator]
static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
pub const BUILD_INFO: BuildInfo = BuildInfo {
version: env!("CARGO_PKG_VERSION"),
sha: run_command_str!(
"sh",
"-c",
r#"if [ -n "$MZ_DEV_BUILD_SHA" ]; then
echo "$MZ_DEV_BUILD_SHA"
else
# Unfortunately we need to suppress error messages from `git`, as
# run_command_str will display no error message at all if we print
# more than one line of output to stderr.
git rev-parse --verify HEAD 2>/dev/null || {
printf "error: unable to determine Git SHA; " >&2
printf "either build from working Git clone " >&2
printf "(see https://materialize.com/docs/install/#build-from-source), " >&2
printf "or specify SHA manually by setting MZ_DEV_BUILD_SHA environment variable" >&2
exit 1
}
fi"#
),
time: run_command_str!("date", "-u", "+%Y-%m-%dT%H:%M:%SZ"),
target_triple: env!("TARGET_TRIPLE"),
};
/// Configuration for a `materialized` server.
#[derive(Debug, Clone)]
pub struct Config {
// === Timely and Differential worker options. ===
/// The number of Timely worker threads that this process should host.
pub workers: usize,
/// The Timely worker configuration.
pub timely_worker: timely::WorkerConfig,
// === Performance tuning options. ===
pub logging: Option<LoggingConfig>,
/// The historical window in which distinctions are maintained for
/// arrangements.
///
/// As arrangements accept new timestamps they may optionally collapse prior
/// timestamps to the same value, retaining their effect but removing their
/// distinction. A large value or `None` results in a large amount of
/// historical detail for arrangements; this increases the logical times at
/// which they can be accurately queried, but consumes more memory. A low
/// value reduces the amount of memory required but also risks not being
/// able to use the arrangement in a query that has other constraints on the
/// timestamps used (e.g. when joined with other arrangements).
pub logical_compaction_window: Option<Duration>,
/// The interval at which sources should be timestamped.
pub timestamp_frequency: Duration,
// === Connection options. ===
/// The IP address and port to listen on.
pub listen_addr: SocketAddr,
/// TLS encryption configuration.
pub tls: Option<TlsConfig>,
// === Storage options. ===
/// The directory in which `materialized` should store its own metadata.
pub data_directory: PathBuf,
pub persistence: Option<PersistenceConfig>,
pub cache: Option<CacheConfig>,
/// An optional symbiosis endpoint. See the
/// [`symbiosis`](../symbiosis/index.html) crate for details.
pub symbiosis_url: Option<String>,
/// Whether to permit usage of experimental features.
pub experimental_mode: bool,
/// Whether to run in safe mode.
pub safe_mode: bool,
/// An optional telemetry endpoint. Use None to disable telemetry.
pub telemetry_url: Option<String>,
/// The frequency at which to update introspection
pub introspection_frequency: Duration,
}
/// Configures TLS encryption for connections.
#[derive(Debug, Clone)]
pub struct TlsConfig {
/// The TLS mode to use.
pub mode: TlsMode,
/// The path to the TLS certificate.
pub cert: PathBuf,
/// The path to the TLS key.
pub key: PathBuf,
}
/// Configures how strictly to enforce TLS encryption and authentication.
#[derive(Debug, Clone)]
pub enum TlsMode {
/// Require that all clients connect with TLS, but do not require that they
/// present a client certificate.
Require,
/// Require that clients connect with TLS and present a certificate that
/// is signed by the specified CA.
VerifyCa {
/// The path to a TLS certificate authority.
ca: PathBuf,
},
/// Like [`TlsMode::VerifyCa`], but the `cn` (Common Name) field of the
/// certificate must additionally match the user named in the connection
/// request.
VerifyFull {
/// The path to a TLS certificate authority.
ca: PathBuf,
},
}
/// Start a `materialized` server.
pub async fn serve(config: Config) -> Result<Server, anyhow::Error> {
let workers = config.workers;
// Validate TLS configuration, if present.
let (pgwire_tls, http_tls) = match &config.tls {
None => (None, None),
Some(tls_config) => {
let context = {
// Mozilla publishes three presets: old, intermediate, and modern. They
// recommend the intermediate preset for general purpose servers, which
// is what we use, as it is compatible with nearly every client released
// in the last five years but does not include any known-problematic
// ciphers. We once tried to use the modern preset, but it was
// incompatible with Fivetran, and presumably other JDBC-based tools.
let mut builder = SslAcceptor::mozilla_intermediate_v5(SslMethod::tls())?;
if let TlsMode::VerifyCa { ca } | TlsMode::VerifyFull { ca } = &tls_config.mode {
builder.set_ca_file(ca)?;
builder.set_verify(SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT);
}
builder.set_certificate_file(&tls_config.cert, SslFiletype::PEM)?;
builder.set_private_key_file(&tls_config.key, SslFiletype::PEM)?;
builder.build().into_context()
};
let pgwire_tls = pgwire::TlsConfig {
context: context.clone(),
mode: match tls_config.mode {
TlsMode::Require | TlsMode::VerifyCa { .. } => pgwire::TlsMode::Require,
TlsMode::VerifyFull { .. } => pgwire::TlsMode::VerifyUser,
},
};
let http_tls = http::TlsConfig {
context,
mode: match tls_config.mode {
TlsMode::Require | TlsMode::VerifyCa { .. } => http::TlsMode::Require,
TlsMode::VerifyFull { .. } => http::TlsMode::AssumeUser,
},
};
(Some(pgwire_tls), Some(http_tls))
}
};
// Set this metric once so that it shows up in the metric export.
crate::server_metrics::WORKER_COUNT
.with_label_values(&[&workers.to_string()])
.set(workers.try_into().unwrap());
// Initialize network listener.
let listener = TcpListener::bind(&config.listen_addr).await?;
let local_addr = listener.local_addr()?;
// Initialize coordinator.
let (coord_handle, coord_client) = coord::serve(coord::Config {
workers,
timely_worker: config.timely_worker,
symbiosis_url: config.symbiosis_url.as_deref(),
logging: config.logging,
data_directory: &config.data_directory,
timestamp_frequency: config.timestamp_frequency,
cache: config.cache,
persistence: config.persistence,
logical_compaction_window: config.logical_compaction_window,
experimental_mode: config.experimental_mode,
safe_mode: config.safe_mode,
build_info: &BUILD_INFO,
})
.await?;
// Launch task to serve connections.
//
// The lifetime of this task is controlled by a trigger that activates on
// drop. Draining marks the beginning of the server shutdown process and
// indicates that new user connections (i.e., pgwire and HTTP connections)
// should be rejected. Once all existing user connections have gracefully
// terminated, this task exits.
let (drain_trigger, drain_tripwire) = oneshot::channel();
tokio::spawn({
let start_time = coord_handle.start_instant();
async move {
// TODO(benesch): replace with `listener.incoming()` if that is
// restored when the `Stream` trait stabilizes.
let mut incoming = TcpListenerStream::new(listener);
let mut mux = Mux::new();
mux.add_handler(pgwire::Server::new(pgwire::Config {
tls: pgwire_tls,
coord_client: coord_client.clone(),
}));
mux.add_handler(http::Server::new(http::Config {
tls: http_tls,
coord_client,
start_time,
}));
mux.serve(incoming.by_ref().take_until(drain_tripwire))
.await;
}
});
tokio::spawn({
let start_time = coord_handle.start_instant();
let frequency = config.introspection_frequency;
async move {
loop {
server_metrics::update_uptime(start_time);
tokio::time::sleep(frequency).await;
}
}
});
// Start a task that checks for the latest version and prints a warning if
// it finds a different version than currently running.
if let Some(telemetry_url) = config.telemetry_url {
tokio::spawn(version_check::check_version_loop(
telemetry_url,
coord_handle.cluster_id(),
coord_handle.session_id(),
coord_handle.start_instant(),
));
}
Ok(Server {
local_addr,
_drain_trigger: drain_trigger,
_coord_handle: coord_handle,
})
}
/// A running `materialized` server.
pub struct Server {
local_addr: SocketAddr,
// Drop order matters for these fields.
_drain_trigger: oneshot::Sender<()>,
_coord_handle: coord::Handle,
}
impl Server {
pub fn local_addr(&self) -> SocketAddr {
self.local_addr
}
}
| 38.259259 | 101 | 0.63918 |
0afa4c4cf01899cdcf7fe1be94acac41936835ce | 1,202 | use actix_web::{delete, get, post, web, Responder};
use sqlx::PgPool;
use crate::user::active_code::model::ActiveCode;
use crate::crud::{CRUD, deal_result};
#[post("/active_code/create")]
async fn create(new: web::Json<ActiveCode>, db_pool: web::Data<PgPool>) -> impl Responder {
let result = ActiveCode::create(new.into_inner(), db_pool.get_ref()).await;
deal_result(result)
}
#[get("/active_code/read")]
async fn read(db_pool: web::Data<PgPool>) -> impl Responder {
let result = ActiveCode::read(db_pool.get_ref()).await;
deal_result(result)
}
#[get("/active_code/read_by_code/{code}")]
async fn read_by_code(code: web::Path<String>, db_pool: web::Data<PgPool>) -> impl Responder {
let result = ActiveCode::read_by_key(code.into_inner(), db_pool.get_ref()).await;
deal_result(result)
}
#[delete("/active_code/delete/{code}")]
async fn delete(code: web::Path<String>, db_pool: web::Data<PgPool>) -> impl Responder {
let result = ActiveCode::delete(code.into_inner(), db_pool.get_ref()).await;
deal_result(result)
}
pub fn init(cfg: &mut web::ServiceConfig) {
cfg.service(create);
cfg.service(read);
cfg.service(read_by_code);
cfg.service(delete);
} | 34.342857 | 94 | 0.698835 |
d5a4827a142ffcd40ae82f341354e9f4c4915336 | 1,119 | use super::{error::Error, name_restriction::check_measurement};
use derive_more::{Deref, Display};
use std::{borrow::Borrow, convert::TryFrom};
///The part of the InfluxDB data structure that describes the data stored in the associated fields.
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Hash, Display, Deref)]
pub struct Measurement(String);
impl Measurement {
pub fn new(measurement: impl Into<String>) -> Result<Self, Error> {
let measurement = measurement.into();
check_measurement(&measurement)?;
Ok(Measurement(measurement))
}
}
impl TryFrom<String> for Measurement {
type Error = Error;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl TryFrom<&str> for Measurement {
type Error = Error;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl Borrow<str> for Measurement {
#[inline]
fn borrow(&self) -> &str {
self.0.borrow()
}
}
impl AsRef<str> for Measurement {
#[inline]
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
| 25.431818 | 99 | 0.643432 |
8985c13cd4b79cd7373c9266ce022cd239971078 | 2,516 | extern crate rand;
use std::hash::{Hash, Hasher};
use std::time::{Duration, Instant};
use rand::{thread_rng, Rng};
use crate::config::Config;
#[derive(Debug, Clone)]
pub struct Peer {
config: Config,
uri: String,
ping_at: Instant,
stable_at: Instant,
inactive_at: Instant,
remove_at: Instant,
}
impl Peer {
pub fn new(uri: String, config: Config) -> Self {
let now = Instant::now();
// Initial ping at should be immediate
let ping_at = now;
// The rest are regular
let stable_at = now + config.stable_delay;
// Until the peer pings - it should be treated as inactive
let inactive_at = now - config.ping_every.max;
let remove_at = now + config.remove_timeout;
Self {
config,
uri,
ping_at,
stable_at,
inactive_at,
remove_at,
}
}
fn ping_delay(config: &Config) -> Duration {
let min = config.ping_every.min;
let max = config.ping_every.max;
let min = min.as_secs() as f64 + f64::from(min.subsec_nanos()) * 1e-9;
let max = max.as_secs() as f64 + f64::from(max.subsec_nanos()) * 1e-9;
let val = thread_rng().gen_range(min, max);
let secs = val as u64;
let nsecs = ((val - secs as f64) * 1e9) as u32;
Duration::new(secs, nsecs)
}
pub fn uri(&self) -> &str {
&self.uri
}
pub fn mark_alive(&mut self) {
let now = Instant::now();
let was_active = self.is_active(now);
self.remove_at = now + self.config.alive_timeout + self.config.remove_timeout;
self.inactive_at = now + self.config.alive_timeout;
self.ping_at = now + Peer::ping_delay(&self.config);
// Re-instantiate stable delay
if !was_active {
self.stable_at = now + self.config.stable_delay;
}
}
pub fn should_remove(&self, now: Instant) -> bool {
self.remove_at <= now
}
pub fn should_ping(&self, now: Instant) -> bool {
self.ping_at <= now
}
pub fn is_stable(&self, now: Instant) -> bool {
self.stable_at <= now
}
pub fn is_active(&self, now: Instant) -> bool {
now < self.inactive_at
}
}
impl PartialEq for Peer {
fn eq(&self, other: &Self) -> bool {
self.uri == other.uri
}
}
impl Eq for Peer {}
impl Hash for Peer {
fn hash<H: Hasher>(&self, state: &mut H) {
self.uri.hash(state);
}
}
| 23.296296 | 86 | 0.566375 |
f95e48d37c20d734512ea5ffc8e341d35701f576 | 2,494 | // This file was ((taken|adapted)|contains (data|code)) from twitch_api,
// Copyright 2017 Matt Shanker
// It's licensed under the Apache License, Version 2.0.
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// (Modifications|Other (data|code)|Everything else) Copyright 2019 the
// libtwitch-rs authors. See copying.md for further legal info.
use std::{
self,
collections::HashMap,
io::Write,
};
use serde::Deserialize;
use super::super::{
response::TwitchResult,
TwitchClient,
};
/// Gets games sorted by number of current viewers on Twitch, most popular first
///
/// #### Authentication: `None`
pub fn top(c: &TwitchClient) -> TwitchResult<TopGames> {
let iter = TopGames {
client: c,
cur: None,
offset: 0,
};
Ok(iter)
}
///////////////////////////////////////
// GetTopGames
///////////////////////////////////////
pub struct TopGames<'c> {
client: &'c TwitchClient,
cur: Option<SerdeTopGames>,
offset: i32,
}
#[derive(Deserialize, Debug)]
pub struct TopGame {
pub channels: i32,
pub viewers: i32,
pub game: Game,
}
#[derive(Deserialize, Debug)]
pub struct Game {
#[serde(rename = "_id")]
pub id: i64,
#[serde(rename = "box")]
pub _box: HashMap<String, String>,
pub giantbomb_id: i64,
pub logo: HashMap<String, String>,
pub name: String,
#[serde(default)]
pub popularity: i32,
}
#[derive(Deserialize, Debug)]
struct SerdeTopGames {
top: Vec<TopGame>,
}
impl<'c> Iterator for TopGames<'c> {
type Item = TopGame;
fn next(&mut self) -> Option<TopGame> {
let url = &format!("/games/top?limit=100&offset={}", self.offset);
next_result!(self, &url, SerdeTopGames, top)
}
}
///////////////////////////////////////
// TESTS
///////////////////////////////////////
#[cfg(test)]
mod tests {
use crate::{
new,
tests::CLIENTID,
};
#[test]
fn top() {
let c = new(String::from(CLIENTID));
let mut r = super::top(&c).unwrap();
r.next();
}
}
| 23.980769 | 80 | 0.599038 |
b96e87c6545a8a83418dea3fbaa970fc45135b27 | 128 | use gdnative::prelude::*;
#[derive(ToVariant)]
pub struct Foo {
#[variant(aoeu = "aoeu")]
bar: String,
}
fn main() {}
| 12.8 | 29 | 0.585938 |
503e8b26912b89e81e9d871b75269b9fd56d0a93 | 1,165 | pub mod database;
pub mod external;
pub use database::LocalDatabase;
pub use external::AuthServer;
pub use super::key::KeyAttestation;
use sshcerts::ssh::{CertType, Extensions};
#[derive(Debug)]
pub enum AuthorizationError {
CertType,
NotAuthorized,
AuthorizerError,
}
#[derive(Debug)]
pub struct Authorization {
pub serial: u64,
pub valid_before: u64,
pub valid_after: u64,
pub principals: Vec<String>,
pub hosts: Option<Vec<String>>,
pub extensions: Extensions,
pub force_command: Option<String>,
pub force_source_ip: bool,
}
#[derive(Debug)]
pub struct AuthorizationRequestProperties {
pub fingerprint: String,
pub mtls_identities: Vec<String>,
pub requester_ip: String,
pub principals: Vec<String>,
pub servers: Vec<String>,
pub valid_before: u64,
pub valid_after: u64,
pub cert_type: CertType,
}
#[derive(Debug)]
pub struct RegisterKeyRequestProperties {
pub fingerprint: String,
pub mtls_identities: Vec<String>,
pub requester_ip: String,
pub attestation: Option<KeyAttestation>,
}
pub enum AuthMechanism {
Local(LocalDatabase),
External(AuthServer),
} | 22.403846 | 44 | 0.711588 |
1d7828d397b40fbd65dadcef7ff71928f7f96e02 | 283 | extern crate catalyst_protocol_sdk_rust;
use catalyst_protocol_sdk_rust::prelude::*;
use catalyst_protocol_sdk_rust::Cryptography::ErrorCode;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn can_access_value_of_error_code(){
ErrorCode::NO_ERROR.value();
}
} | 23.583333 | 56 | 0.720848 |
de031f4f1bca7e29ff244abc9b360d0afc3caa16 | 52 | pub mod css;
pub mod dom_creator;
pub mod printing;
| 13 | 20 | 0.769231 |
8fc4a88d1fe6bf8b201636de07deb1ab00b98584 | 1,893 | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_lambda::{Client, Error, Region, PKG_VERSION};
use std::str;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
#[structopt(short, long)]
region: Option<String>,
/// The Lambda function's ARN.
#[structopt(short, long)]
arn: String,
/// Whether to display additional runtime information.
#[structopt(short, long)]
verbose: bool,
}
/// Invokes a Lambda function by its ARN.
/// # Arguments
///
/// * `-a ARN` - The ARN of the Lambda function.
/// * `[-r REGION]` - The Region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() -> Result<(), Error> {
tracing_subscriber::fmt::init();
let Opt {
arn,
region,
verbose,
} = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
let shared_config = aws_config::from_env().region(region_provider).load().await;
if verbose {
println!("Lambda version: {}", PKG_VERSION);
println!("Region: {}", shared_config.region().unwrap());
println!("Function ARN: {}", arn);
println!();
}
let client = Client::new(&shared_config);
let resp = client.invoke().function_name(arn).send().await?;
if let Some(blob) = resp.payload {
let s = str::from_utf8(blob.as_ref()).expect("invalid utf-8");
println!("Response: {:?}", s);
}
Ok(())
}
| 29.578125 | 84 | 0.622293 |
abfb6bfdae6abad202e5aef3ed912a69eb02bae0 | 75 | pub use crate::{
regular_cell_data::*,
transition_cell_data::*,
};
| 15 | 28 | 0.64 |
3381377c4c2f1ae7b5c4bdd0e255f9e8c26a108d | 2,519 | #[doc = "Reader of register MICR"]
pub type R = crate::R<u32, super::MICR>;
#[doc = "Writer for register MICR"]
pub type W = crate::W<u32, super::MICR>;
#[doc = "Register MICR `reset()`'s with value 0"]
impl crate::ResetValue for super::MICR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `RESERVED1`"]
pub type RESERVED1_R = crate::R<u32, u32>;
#[doc = "Write proxy for field `RESERVED1`"]
pub struct RESERVED1_W<'a> {
w: &'a mut W,
}
impl<'a> RESERVED1_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x7fff_ffff << 1)) | (((value as u32) & 0x7fff_ffff) << 1);
self.w
}
}
#[doc = "Reader of field `IC`"]
pub type IC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `IC`"]
pub struct IC_W<'a> {
w: &'a mut W,
}
impl<'a> IC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
impl R {
#[doc = "Bits 1:31 - 31:1\\]
Software should not rely on the value of a reserved. Writing any other value than the reset value may result in undefined behavior."]
#[inline(always)]
pub fn reserved1(&self) -> RESERVED1_R {
RESERVED1_R::new(((self.bits >> 1) & 0x7fff_ffff) as u32)
}
#[doc = "Bit 0 - 0:0\\]
Interrupt clear Writing 1 to this bit clears MRIS.RIS and MMIS.MIS . Reading this register returns no meaningful data."]
#[inline(always)]
pub fn ic(&self) -> IC_R {
IC_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 1:31 - 31:1\\]
Software should not rely on the value of a reserved. Writing any other value than the reset value may result in undefined behavior."]
#[inline(always)]
pub fn reserved1(&mut self) -> RESERVED1_W {
RESERVED1_W { w: self }
}
#[doc = "Bit 0 - 0:0\\]
Interrupt clear Writing 1 to this bit clears MRIS.RIS and MMIS.MIS . Reading this register returns no meaningful data."]
#[inline(always)]
pub fn ic(&mut self) -> IC_W {
IC_W { w: self }
}
}
| 31.886076 | 133 | 0.588329 |