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
|
---|---|---|---|---|---|
ab68a354f32383796574341fdf9359f319d6ae0c | 10,174 | // Copyright (C) 2020-2021 Alibaba Cloud. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause
use std::num::Wrapping;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::Ordering;
use vm_memory::GuestMemory;
use crate::{AvailIter, Error, QueueState, QueueStateT};
/// A guard object to exclusively access an `Queue` object.
///
/// The guard object holds an exclusive lock to the underlying `QueueState` object, with an
/// associated guest memory object. It helps to guarantee that the whole session is served
/// with the same guest memory object.
///
/// # Example
///
/// ```rust
/// use virtio_queue::{Queue, QueueState};
/// use vm_memory::{Bytes, GuestAddress, GuestAddressSpace, GuestMemoryMmap};
///
/// let m = GuestMemoryMmap::<()>::from_ranges(&[(GuestAddress(0), 0x10000)]).unwrap();
/// let mut queue = Queue::<&GuestMemoryMmap, QueueState>::new(&m, 1024);
/// let mut queue_guard = queue.lock_with_memory();
///
/// // First, the driver sets up the queue; this set up is done via writes on the bus (PCI, MMIO).
/// queue_guard.set_size(8);
/// queue_guard.set_desc_table_address(Some(0x1000), None);
/// queue_guard.set_avail_ring_address(Some(0x2000), None);
/// queue_guard.set_used_ring_address(Some(0x3000), None);
/// queue_guard.set_event_idx(true);
/// queue_guard.set_ready(true);
/// // The user should check if the queue is valid before starting to use it.
/// assert!(queue_guard.is_valid());
///
/// // Here the driver would add entries in the available ring and then update the `idx` field of
/// // the available ring (address = 0x2000 + 2).
/// m.write_obj(3, GuestAddress(0x2002));
///
/// loop {
/// queue_guard.disable_notification().unwrap();
///
/// // Consume entries from the available ring.
/// while let Some(chain) = queue_guard.iter().unwrap().next() {
/// // Process the descriptor chain, and then add an entry in the used ring and optionally
/// // notify the driver.
/// queue_guard.add_used(chain.head_index(), 0x100).unwrap();
///
/// if queue_guard.needs_notification().unwrap() {
/// // Here we would notify the driver it has new entries in the used ring to consume.
/// }
/// }
/// if !queue_guard.enable_notification().unwrap() {
/// break;
/// }
/// }
/// ```
pub struct QueueGuard<M, S> {
state: S,
mem: M,
}
impl<M, S> QueueGuard<M, S>
where
M: Deref + Clone,
M::Target: GuestMemory + Sized,
S: DerefMut<Target = QueueState>,
{
/// Create a new instance of `QueueGuard`.
pub fn new(state: S, mem: M) -> Self {
QueueGuard { state, mem }
}
/// Check whether the queue configuration is valid.
pub fn is_valid(&self) -> bool {
self.state.is_valid(self.mem.deref())
}
/// Reset the queue to the initial state.
pub fn reset(&mut self) {
self.state.reset()
}
/// Get the maximum size of the virtio queue.
pub fn max_size(&self) -> u16 {
self.state.max_size()
}
/// Configure the queue size for the virtio queue.
pub fn set_size(&mut self, size: u16) {
self.state.set_size(size);
}
/// Check whether the queue is ready to be processed.
pub fn ready(&self) -> bool {
self.state.ready()
}
/// Configure the queue to `ready for processing` state.
pub fn set_ready(&mut self, ready: bool) {
self.state.set_ready(ready)
}
/// Set the descriptor table address for the queue.
///
/// The descriptor table address is 64-bit, the corresponding part will be updated if 'low'
/// and/or `high` is `Some` and valid.
pub fn set_desc_table_address(&mut self, low: Option<u32>, high: Option<u32>) {
self.state.set_desc_table_address(low, high);
}
/// Set the available ring address for the queue.
///
/// The available ring address is 64-bit, the corresponding part will be updated if 'low'
/// and/or `high` is `Some` and valid.
pub fn set_avail_ring_address(&mut self, low: Option<u32>, high: Option<u32>) {
self.state.set_avail_ring_address(low, high);
}
/// Set the used ring address for the queue.
///
/// The used ring address is 64-bit, the corresponding part will be updated if 'low'
/// and/or `high` is `Some` and valid.
pub fn set_used_ring_address(&mut self, low: Option<u32>, high: Option<u32>) {
self.state.set_used_ring_address(low, high);
}
/// Enable/disable the VIRTIO_F_RING_EVENT_IDX feature for interrupt coalescing.
pub fn set_event_idx(&mut self, enabled: bool) {
self.state.set_event_idx(enabled)
}
/// Read the `idx` field from the available ring.
pub fn avail_idx(&self, order: Ordering) -> Result<Wrapping<u16>, Error> {
self.state.avail_idx(self.mem.deref(), order)
}
/// Read the `idx` field from the used ring.
pub fn used_idx(&self, order: Ordering) -> Result<Wrapping<u16>, Error> {
self.state.used_idx(self.mem.deref(), order)
}
/// Put a used descriptor head into the used ring.
pub fn add_used(&mut self, head_index: u16, len: u32) -> Result<(), Error> {
self.state.add_used(self.mem.deref(), head_index, len)
}
/// Enable notification events from the guest driver.
///
/// Return true if one or more descriptors can be consumed from the available ring after
/// notifications were enabled (and thus it's possible there will be no corresponding
/// notification).
pub fn enable_notification(&mut self) -> Result<bool, Error> {
self.state.enable_notification(self.mem.deref())
}
/// Disable notification events from the guest driver.
pub fn disable_notification(&mut self) -> Result<(), Error> {
self.state.disable_notification(self.mem.deref())
}
/// Check whether a notification to the guest is needed.
///
/// Please note this method has side effects: once it returns `true`, it considers the
/// driver will actually be notified, remember the associated index in the used ring, and
/// won't return `true` again until the driver updates `used_event` and/or the notification
/// conditions hold once more.
pub fn needs_notification(&mut self) -> Result<bool, Error> {
self.state.needs_notification(self.mem.deref())
}
/// Return the index of the next entry in the available ring.
pub fn next_avail(&self) -> u16 {
self.state.next_avail()
}
/// Return the index of the next entry in the used ring.
pub fn next_used(&self) -> u16 {
self.state.next_used()
}
/// Set the index of the next entry in the available ring.
pub fn set_next_avail(&mut self, next_avail: u16) {
self.state.set_next_avail(next_avail);
}
/// Set the index of the next entry in the used ring.
pub fn set_next_used(&mut self, next_used: u16) {
self.state.set_next_used(next_used);
}
/// Get a consuming iterator over all available descriptor chain heads offered by the driver.
pub fn iter(&mut self) -> Result<AvailIter<'_, M>, Error> {
self.state.deref_mut().iter(self.mem.clone())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::defs::{VIRTQ_DESC_F_NEXT, VIRTQ_DESC_F_WRITE};
use crate::mock::MockSplitQueue;
use crate::Descriptor;
use vm_memory::{GuestAddress, GuestMemoryMmap};
#[test]
fn test_queue_guard_object() {
let m = &GuestMemoryMmap::<()>::from_ranges(&[(GuestAddress(0), 0x10000)]).unwrap();
let vq = MockSplitQueue::new(m, 0x100);
let mut q = vq.create_queue(m);
let mut g = q.lock_with_memory();
// g is currently valid.
assert!(g.is_valid());
assert!(g.ready());
assert_eq!(g.max_size(), 0x100);
g.set_size(16);
// The chains are (0, 1), (2, 3, 4), (5, 6).
for i in 0..7 {
let flags = match i {
1 | 4 | 6 => 0,
_ => VIRTQ_DESC_F_NEXT,
};
let desc = Descriptor::new((0x1000 * (i + 1)) as u64, 0x1000, flags, i + 1);
vq.desc_table().store(i, desc);
}
vq.avail().ring().ref_at(0).store(u16::to_le(0));
vq.avail().ring().ref_at(1).store(u16::to_le(2));
vq.avail().ring().ref_at(2).store(u16::to_le(5));
// Let the device know it can consume chains with the index < 2.
vq.avail().idx().store(u16::to_le(3));
// No descriptor chains are consumed at this point.
assert_eq!(g.next_avail(), 0);
assert_eq!(g.next_used(), 0);
loop {
g.disable_notification().unwrap();
while let Some(chain) = g.iter().unwrap().next() {
// Process the descriptor chain, and then add entries to the
// used ring.
let head_index = chain.head_index();
let mut desc_len = 0;
chain.for_each(|d| {
if d.flags() & VIRTQ_DESC_F_WRITE == VIRTQ_DESC_F_WRITE {
desc_len += d.len();
}
});
g.add_used(head_index, desc_len).unwrap();
}
if !g.enable_notification().unwrap() {
break;
}
}
// The next chain that can be consumed should have index 3.
assert_eq!(g.next_avail(), 3);
assert_eq!(g.avail_idx(Ordering::Acquire).unwrap(), Wrapping(3));
assert_eq!(g.next_used(), 3);
assert_eq!(g.used_idx(Ordering::Acquire).unwrap(), Wrapping(3));
assert!(g.ready());
// Decrement `idx` which should be forbidden. We don't enforce this thing, but we should
// test that we don't panic in case the driver decrements it.
vq.avail().idx().store(1);
loop {
g.disable_notification().unwrap();
while let Some(_chain) = g.iter().unwrap().next() {
// In a real use case, we would do something with the chain here.
}
if !g.enable_notification().unwrap() {
break;
}
}
}
}
| 35.573427 | 98 | 0.610478 |
fe496b1b7a6fedfa72eff2c2a1d9ab728fcb34cb | 182 | mod colour;
mod types;
mod scope;
mod list;
mod smallvec;
pub use self::colour::*;
pub use self::types::*;
pub use self::scope::*;
pub use self::list::*;
pub use self::smallvec::*;
| 15.166667 | 26 | 0.664835 |
8f53fa3e351a7b44eff18e4eb728efdb281ec9dd | 7,108 | use crate::{
fragment::{Bounds, Rect},
Fragment,
};
/// if a group of fragment can be endorse as rect, return the bounds point for the
/// rectangle
pub fn endorse_rect(fragments: &Vec<Fragment>) -> Option<Rect> {
if is_rect(fragments) {
let is_any_broken = fragments.iter().any(|fragment| fragment.is_broken());
let all_points = fragments.iter().fold(vec![], |mut acc, frag| {
let (p1, p2) = frag.bounds();
acc.push(p1);
acc.push(p2);
acc
});
let min = all_points.iter().min();
let max = all_points.iter().max();
if let (Some(min), Some(max)) = (min, max) {
Some(Rect::new(*min, *max, false, is_any_broken))
} else {
None
}
} else {
None
}
}
/// group of fragments can be check if they form:
/// - rectangle
fn is_rect(fragments: &Vec<Fragment>) -> bool {
if fragments.len() == 4 {
let parallels = parallel_aabb_group(fragments);
if parallels.len() == 2 {
let (a1, a2) = parallels[0];
let (b1, b2) = parallels[1];
let line_a1 = fragments[a1].as_line().expect("expecting a line");
let line_b1 = fragments[b1].as_line().expect("expecting a line");
let line_a2 = fragments[a2].as_line().expect("expecting a line");
let line_b2 = fragments[b2].as_line().expect("expecting a line");
line_a1.is_touching_aabb_perpendicular(line_b1)
&& line_a2.is_touching_aabb_perpendicular(line_b2)
} else {
false
}
} else {
false
}
}
/// qualifications:
/// - 8 fragments
/// - 2 parallell pair
/// - 4 aabb right angle arc (top_left, top_right, bottom_left, bottom_right)
/// - each of the right angle touches 2 lines that are aabb_perpendicular
pub fn endorse_rounded_rect(fragments: &Vec<Fragment>) -> Option<Rect> {
if let (true, arc_radius) = is_rounded_rect(fragments) {
let is_any_broken = fragments.iter().any(|fragment| fragment.is_broken());
let all_points = fragments.iter().fold(vec![], |mut acc, frag| {
let (p1, p2) = frag.bounds();
acc.push(p1);
acc.push(p2);
acc
});
let min = all_points.iter().min();
let max = all_points.iter().max();
if let (Some(min), Some(max)) = (min, max) {
//TODO: compute the radius from
Some(Rect::rounded_new(
*min,
*max,
false,
arc_radius.expect("expecting arc radius"),
is_any_broken,
))
} else {
None
}
} else {
None
}
}
fn is_rounded_rect(fragments: &Vec<Fragment>) -> (bool, Option<f32>) {
if fragments.len() == 8 {
let parallels = parallel_aabb_group(fragments);
let right_arcs = right_angle_arcs(fragments);
//TODO: throroughly check the arc composition to be top_left, top_right, bottom_left,
//bottom_right
if parallels.len() == 2 && right_arcs.len() == 4 {
let first_right_arc_index = right_arcs[0];
let arc_fragment = &fragments[first_right_arc_index];
let arc_radius = arc_fragment.as_arc().expect("expecting an arc").radius;
let (a1, a2) = parallels[0];
let (b1, b2) = parallels[1];
let line_a1 = fragments[a1].as_line().expect("expecting a line");
let line_b1 = fragments[b1].as_line().expect("expecting a line");
let line_a2 = fragments[a2].as_line().expect("expecting a line");
let line_b2 = fragments[b2].as_line().expect("expecting a line");
let passed =
line_a1.is_aabb_perpendicular(line_b1) && line_a2.is_aabb_perpendicular(line_b2);
(passed, Some(arc_radius))
} else {
(false, None)
}
} else {
(false, None)
}
}
/// return the index of the fragments that are right angle arc
fn right_angle_arcs(fragments: &Vec<Fragment>) -> Vec<usize> {
fragments
.iter()
.enumerate()
.filter_map(|(index, frag)| {
if let Some(arc) = frag.as_arc() {
if arc.is_aabb_right_angle_arc() {
Some(index)
} else {
None
}
} else {
None
}
})
.collect()
}
/// return the indexes of the fragments that are aabb parallel
fn parallel_aabb_group(fragments: &Vec<Fragment>) -> Vec<(usize, usize)> {
let mut parallels = vec![];
for (index1, frag1) in fragments.iter().enumerate() {
for (index2, frag2) in fragments.iter().enumerate() {
if index1 != index2
&& !parallels.iter().any(|(pair1, pair2)| {
index1 == *pair1 || index1 == *pair2 || index2 == *pair1 || index2 == *pair2
})
&& frag1.is_aabb_parallel(&frag2)
{
parallels.push((index1, index2));
}
}
}
parallels
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{buffer::CellGrid, fragment::line};
#[test]
fn test_parallel_grouping() {
let a = CellGrid::a();
let e = CellGrid::e();
let u = CellGrid::u();
let y = CellGrid::y();
let line_ae = line(a, e);
let line_uy = line(u, y);
let group = parallel_aabb_group(&vec![line_ae, line_uy]);
println!("group: {:#?}", group);
assert_eq!(group, vec![(0, 1)])
}
#[test]
fn test_parallel_grouping_with4() {
let a = CellGrid::a();
let e = CellGrid::e();
let u = CellGrid::u();
let y = CellGrid::y();
let line_ae = line(a, e);
let line_uy = line(u, y);
let line_au = line(a, u);
let line_ey = line(e, y);
let group = parallel_aabb_group(&vec![
line_ae.clone(),
line_au.clone(),
line_uy.clone(),
line_ey.clone(),
]);
println!("group: {:#?}", group);
assert_eq!(group, vec![(0, 2), (1, 3)]);
let rect = endorse_rect(&vec![
line_ae.clone(),
line_au.clone(),
line_uy.clone(),
line_ey.clone(),
]);
assert!(rect.is_some());
assert_eq!(rect, Some(Rect::new(a, y, false, false)));
assert!(is_rect(&vec![line_ae, line_au, line_uy, line_ey]));
}
#[test]
fn parallel_and_perpendicular_but_not_touching_should_not_be_rect() {
let a = CellGrid::a();
let e = CellGrid::e();
let u = CellGrid::u();
let y = CellGrid::y();
let g = CellGrid::g();
let q = CellGrid::q();
let i = CellGrid::i();
let s = CellGrid::s();
let line_ae = line(a, e);
let line_uy = line(u, y);
let line_gq = line(g, q);
let line_is = line(i, s);
assert!(!is_rect(&vec![line_ae, line_uy, line_gq, line_is]));
}
}
| 32.75576 | 97 | 0.527293 |
8947d5bf88f53c4fb3ed2bce3c1a2a8e9f5a5118 | 4,569 | use rapier::crossbeam::channel::Receiver;
use rapier::geometry::{ContactEvent, IntersectionEvent};
use rapier::pipeline::ChannelEventCollector;
use wasm_bindgen::prelude::*;
/// A structure responsible for collecting events generated
/// by the physics engine.
#[wasm_bindgen]
pub struct RawEventQueue {
pub(crate) collector: ChannelEventCollector,
contact_events: Receiver<ContactEvent>,
proximity_events: Receiver<IntersectionEvent>,
pub(crate) auto_drain: bool,
}
// #[wasm_bindgen]
// /// The proximity state of a sensor collider and another collider.
// pub enum RawIntersection {
// /// The sensor is intersecting the other collider.
// Intersecting = 0,
// /// The sensor is within tolerance margin of the other collider.
// WithinMargin = 1,
// /// The sensor is disjoint from the other collider.
// Disjoint = 2,
// }
#[wasm_bindgen]
impl RawEventQueue {
/// Creates a new event collector.
///
/// # Parameters
/// - `autoDrain`: setting this to `true` is strongly recommended. If true, the collector will
/// be automatically drained before each `world.step(collector)`. If false, the collector will
/// keep all events in memory unless it is manually drained/cleared; this may lead to unbounded use of
/// RAM if no drain is performed.
#[wasm_bindgen(constructor)]
pub fn new(autoDrain: bool) -> Self {
let contact_channel = rapier::crossbeam::channel::unbounded();
let proximity_channel = rapier::crossbeam::channel::unbounded();
let collector = ChannelEventCollector::new(proximity_channel.0, contact_channel.0);
Self {
collector,
contact_events: contact_channel.1,
proximity_events: proximity_channel.1,
auto_drain: autoDrain,
}
}
/// Applies the given javascript closure on each contact event of this collector, then clear
/// the internal contact event buffer.
///
/// # Parameters
/// - `f(handle1, handle2, started)`: JavaScript closure applied to each contact event. The
/// closure should take three arguments: two integers representing the handles of the colliders
/// involved in the contact, and a boolean indicating if the contact started (true) or stopped
/// (false).
pub fn drainContactEvents(&mut self, f: &js_sys::Function) {
let this = JsValue::null();
while let Ok(event) = self.contact_events.try_recv() {
match event {
ContactEvent::Started(co1, co2) => {
let h1 = co1.into_raw_parts().0 as u32;
let h2 = co2.into_raw_parts().0 as u32;
let _ = f.call3(
&this,
&JsValue::from(h1),
&JsValue::from(h2),
&JsValue::from_bool(true),
);
}
ContactEvent::Stopped(co1, co2) => {
let h1 = co1.into_raw_parts().0 as u32;
let h2 = co2.into_raw_parts().0 as u32;
let _ = f.call3(
&this,
&JsValue::from(h1),
&JsValue::from(h2),
&JsValue::from_bool(false),
);
}
}
}
}
/// Applies the given javascript closure on each proximity event of this collector, then clear
/// the internal proximity event buffer.
///
/// # Parameters
/// - `f(handle1, handle2, prev_prox, new_prox)`: JavaScript closure applied to each proximity event. The
/// closure should take four arguments: two integers representing the handles of the colliders
/// involved in the proximity, and one boolean representing the intersection status.
pub fn drainIntersectionEvents(&mut self, f: &js_sys::Function) {
let this = JsValue::null();
while let Ok(event) = self.proximity_events.try_recv() {
let h1 = event.collider1.into_raw_parts().0 as u32;
let h2 = event.collider2.into_raw_parts().0 as u32;
let intersecting = event.intersecting;
let _ = f
.bind2(&this, &JsValue::from(h1), &JsValue::from(h2))
.call1(&this, &JsValue::from(intersecting));
}
}
/// Removes all events contained by this collector.
pub fn clear(&self) {
while let Ok(_) = self.contact_events.try_recv() {}
while let Ok(_) = self.proximity_events.try_recv() {}
}
}
| 40.794643 | 110 | 0.600569 |
5b975424512d45a5426d9604faafc666c9a37e4f | 3,853 | // pp-exact
fn main() { }
#[cfg(FALSE)]
fn syntax() {
let _ = #[attr] box 0;
let _ = #[attr] [#![attr] ];
let _ = #[attr] [#![attr] 0];
let _ = #[attr] [#![attr] 0; 0];
let _ = #[attr] [#![attr] 0, 0, 0];
let _ = #[attr] foo();
let _ = #[attr] x.foo();
let _ = #[attr] (#![attr] );
let _ = #[attr] (#![attr] #[attr] 0,);
let _ = #[attr] (#![attr] #[attr] 0, 0);
let _ = #[attr] 0 + #[attr] 0;
let _ = #[attr] 0 / #[attr] 0;
let _ = #[attr] 0 & #[attr] 0;
let _ = #[attr] 0 % #[attr] 0;
let _ = #[attr] (0 + 0);
let _ = #[attr] !0;
let _ = #[attr] -0;
let _ = #[attr] false;
let _ = #[attr] 0;
let _ = #[attr] 'c';
let _ = #[attr] x as Y;
let _ = #[attr] (x as Y);
let _ =
#[attr] while true {
#![attr]
};
let _ =
#[attr] while let Some(false) = true {
#![attr]
};
let _ =
#[attr] for x in y {
#![attr]
};
let _ =
#[attr] loop {
#![attr]
};
let _ =
#[attr] match true {
#![attr]
#[attr]
_ => false,
};
let _ = #[attr] || #[attr] foo;
let _ = #[attr] move || #[attr] foo;
let _ =
#[attr] ||
#[attr] {
#![attr]
foo
};
let _ =
#[attr] move ||
#[attr] {
#![attr]
foo
};
let _ =
#[attr] ||
{
#![attr]
foo
};
let _ =
#[attr] move ||
{
#![attr]
foo
};
let _ =
#[attr] {
#![attr]
};
let _ =
#[attr] {
#![attr]
let _ = ();
};
let _ =
#[attr] {
#![attr]
let _ = ();
foo
};
let _ = #[attr] x = y;
let _ = #[attr] (x = y);
let _ = #[attr] x += y;
let _ = #[attr] (x += y);
let _ = #[attr] foo.bar;
let _ = (#[attr] foo).bar;
let _ = #[attr] foo.0;
let _ = (#[attr] foo).0;
let _ = #[attr] foo[bar];
let _ = (#[attr] foo)[bar];
let _ = #[attr] 0..#[attr] 0;
let _ = #[attr] 0..;
let _ = #[attr] (0..0);
let _ = #[attr] (0..);
let _ = #[attr] (..0);
let _ = #[attr] (..);
let _ = #[attr] foo::bar::baz;
let _ = #[attr] &0;
let _ = #[attr] &mut 0;
let _ = #[attr] &#[attr] 0;
let _ = #[attr] &mut #[attr] 0;
let _ = #[attr] break ;
let _ = #[attr] continue ;
let _ = #[attr] return;
let _ = #[attr] foo!();
let _ = #[attr] foo!(# ! [attr]);
let _ = #[attr] foo![];
let _ = #[attr] foo![# ! [attr]];
let _ = #[attr] foo! { };
let _ = #[attr] foo! { # ! [attr] };
let _ = #[attr] Foo{#![attr] bar: baz,};
let _ = #[attr] Foo{#![attr] ..foo};
let _ = #[attr] Foo{#![attr] bar: baz, ..foo};
let _ = #[attr] (#![attr] 0);
{
#[attr]
let _ = 0;
#[attr]
0;
#[attr]
foo!();
#[attr]
foo! { }
#[attr]
foo![];
}
{
#[attr]
let _ = 0;
}
{
#[attr]
0
}
{
#[attr]
{
#![attr]
}
}
{
#[attr]
foo!()
}
{
#[attr]
foo![]
}
{
#[attr]
foo! { }
}
}
| 21.892045 | 50 | 0.286011 |
f8dbe1da49af26d9db57a36d8c4d2c80faef1383 | 4,405 | extern crate num;
extern crate nalgebra as na;
use self::num::{Float, FromPrimitive};
use super::*;
/// Anything that implements this trait permits its space to be infinitely wrapping.
pub trait Toroid<V> {
/// Wrap a delta vector between two positions inside of the toroidal space
fn wrap_delta(&self, delta: V) -> V;
/// Wrap a position to keep it inside of the space
fn wrap_position(&self, pos: V) -> V;
}
pub trait Ball<D> {
fn radius(&self) -> D;
fn space<V>(&self) -> D
where V: Vector<D>, D: Float
{
V::space_ball(self.radius())
}
}
/// A Box with a center at origin and one of the corners created by offset
///
/// The box is aligned so that the face normals point along each axis.
pub struct Box<V> {
pub origin: V,
pub offset: V,
}
impl<V> Box<V> {
pub fn new(origin: V, offset: V) -> Self {
Box{
origin: origin,
offset: offset,
}
}
//Compute the amount of space contained in the box
pub fn space<D>(&self) -> D
where V: Vector<D>, D: Float
{
self.offset.space_box()
}
}
fn wrap_scalar<D>(pos: D, bound: D) -> D where D: Float + FromPrimitive {
// Bound must be positive
let bound = bound.abs();
let twobound = D::from_u32(2u32).unwrap() * bound;
// Create shrunk_pos, which may still not be inside the space, but is within one stride of it
let shrunk_pos = pos % twobound;
if shrunk_pos < -bound {
shrunk_pos + twobound
} else if shrunk_pos > bound {
shrunk_pos - twobound
} else {
shrunk_pos
}
}
impl<D> Toroid<Cartesian1<D>> for Box<Cartesian1<D>>
where D: Float + FromPrimitive
{
fn wrap_delta(&self, delta: Cartesian1<D>) -> Cartesian1<D> {
Cartesian1{
x: wrap_scalar(delta.x, self.offset.x),
}
}
fn wrap_position(&self, pos: Cartesian1<D>) -> Cartesian1<D> {
self.wrap_delta(pos - self.origin) + self.origin
}
}
impl<D> Toroid<Cartesian2<D>> for Box<Cartesian2<D>>
where D: Float + FromPrimitive
{
fn wrap_delta(&self, delta: Cartesian2<D>) -> Cartesian2<D> {
Cartesian2{
x: wrap_scalar(delta.x, self.offset.x),
y: wrap_scalar(delta.y, self.offset.y),
}
}
fn wrap_position(&self, pos: Cartesian2<D>) -> Cartesian2<D> {
self.wrap_delta(pos - self.origin) + self.origin
}
}
impl<D> Toroid<Cartesian3<D>> for Box<Cartesian3<D>>
where D: Float + FromPrimitive
{
fn wrap_delta(&self, delta: Cartesian3<D>) -> Cartesian3<D> {
Cartesian3{
x: wrap_scalar(delta.x, self.offset.x),
y: wrap_scalar(delta.y, self.offset.y),
z: wrap_scalar(delta.z, self.offset.z),
}
}
fn wrap_position(&self, pos: Cartesian3<D>) -> Cartesian3<D> {
self.wrap_delta(pos - self.origin) + self.origin
}
}
impl<D> Toroid<na::Vector1<D>> for Box<na::Vector1<D>>
where D: Float + FromPrimitive
{
fn wrap_delta(&self, delta: na::Vector1<D>) -> na::Vector1<D> {
na::Vector1{
x: wrap_scalar(delta.x, self.offset.x),
}
}
fn wrap_position(&self, pos: na::Vector1<D>) -> na::Vector1<D> {
self.wrap_delta(pos - self.origin) + self.origin
}
}
impl<D> Toroid<na::Vector2<D>> for Box<na::Vector2<D>>
where D: Float + FromPrimitive
{
fn wrap_delta(&self, delta: na::Vector2<D>) -> na::Vector2<D> {
na::Vector2{
x: wrap_scalar(delta.x, self.offset.x),
y: wrap_scalar(delta.y, self.offset.y),
}
}
fn wrap_position(&self, pos: na::Vector2<D>) -> na::Vector2<D> {
self.wrap_delta(pos - self.origin) + self.origin
}
}
impl<D> Toroid<na::Vector3<D>> for Box<na::Vector3<D>>
where D: Float + FromPrimitive
{
fn wrap_delta(&self, delta: na::Vector3<D>) -> na::Vector3<D> {
na::Vector3{
x: wrap_scalar(delta.x, self.offset.x),
y: wrap_scalar(delta.y, self.offset.y),
z: wrap_scalar(delta.z, self.offset.z),
}
}
fn wrap_position(&self, pos: na::Vector3<D>) -> na::Vector3<D> {
self.wrap_delta(pos - self.origin) + self.origin
}
}
impl<V> Clone for Box<V>
where V: Clone
{
fn clone(&self) -> Self {
Box{
origin: self.origin.clone(),
offset: self.offset.clone(),
}
}
}
| 26.69697 | 97 | 0.58479 |
1616fdfad4c05457daf374d56302d22d4bf08ea0 | 3,967 | #![allow(clippy::module_inception)]
#![allow(clippy::upper_case_acronyms)]
#![allow(clippy::large_enum_variant)]
#![allow(clippy::wrong_self_convention)]
#![allow(clippy::should_implement_trait)]
#![allow(clippy::blacklisted_name)]
#![allow(clippy::vec_init_then_push)]
#![allow(rustdoc::bare_urls)]
#![warn(missing_docs)]
//! <p>Amazon EMR on EKS provides a deployment option for Amazon EMR that allows you to run
//! open-source big data frameworks on Amazon Elastic Kubernetes Service (Amazon EKS). With
//! this deployment option, you can focus on running analytics workloads while Amazon EMR on
//! EKS builds, configures, and manages containers for open-source applications. For more
//! information about Amazon EMR on EKS concepts and tasks, see <a href="https://docs.aws.amazon.com/emr/latest/EMR-on-EKS-DevelopmentGuide/emr-eks.html">What is Amazon EMR on EKS</a>.</p>
//! <p>
//! <i>Amazon EMR containers</i> is the API name for Amazon EMR on EKS. The
//! <code>emr-containers</code> prefix is used in the following scenarios: </p>
//! <ul>
//! <li>
//! <p>It is the prefix in the CLI commands for Amazon EMR on EKS. For example, <code>aws
//! emr-containers start-job-run</code>.</p>
//! </li>
//! <li>
//! <p>It is the prefix before IAM policy actions for Amazon EMR on EKS. For example, <code>"Action": [
//! "emr-containers:StartJobRun"]</code>. For more information, see <a href="https://docs.aws.amazon.com/emr/latest/EMR-on-EKS-DevelopmentGuide/security_iam_service-with-iam.html#security_iam_service-with-iam-id-based-policies-actions">Policy actions for Amazon EMR on EKS</a>.</p>
//! </li>
//! <li>
//! <p>It is the prefix used in Amazon EMR on EKS service endpoints. For example, <code>emr-containers.us-east-2.amazonaws.com</code>. For more
//! information, see <a href="https://docs.aws.amazon.com/emr/latest/EMR-on-EKS-DevelopmentGuide/service-quotas.html#service-endpoints">Amazon EMR on EKS Service Endpoints</a>.</p>
//! </li>
//! </ul>
//!
//! # Crate Organization
//!
//! The entry point for most customers will be [`Client`]. [`Client`] exposes one method for each API offered
//! by the service.
//!
//! Some APIs require complex or nested arguments. These exist in [`model`](crate::model).
//!
//! Lastly, errors that can be returned by the service are contained within [`error`]. [`Error`] defines a meta
//! error encompassing all possible errors that can be returned by the service.
//!
//! The other modules within this crate are not required for normal usage.
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub use error_meta::Error;
#[doc(inline)]
pub use config::Config;
mod aws_endpoint;
/// Client and fluent builders for calling the service.
pub mod client;
/// Configuration for the service.
pub mod config;
/// Errors that can occur when calling the service.
pub mod error;
mod error_meta;
mod idempotency_token;
/// Input structures for operations.
pub mod input;
mod json_deser;
mod json_errors;
mod json_ser;
/// Generated accessors for nested fields
mod lens;
pub mod middleware;
/// Data structures used by operation inputs/outputs.
pub mod model;
mod no_credentials;
/// All operations that this crate can perform.
pub mod operation;
mod operation_deser;
mod operation_ser;
/// Output structures for operations.
pub mod output;
/// Paginators for the service
pub mod paginator;
/// Crate version number.
pub static PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
/// Re-exported types from supporting crates.
pub mod types {
pub use aws_smithy_http::result::SdkError;
pub use aws_smithy_types::DateTime;
}
static API_METADATA: aws_http::user_agent::ApiMetadata =
aws_http::user_agent::ApiMetadata::new("emrcontainers", PKG_VERSION);
pub use aws_smithy_http::endpoint::Endpoint;
pub use aws_smithy_types::retry::RetryConfig;
pub use aws_types::app_name::AppName;
pub use aws_types::region::Region;
pub use aws_types::Credentials;
#[doc(inline)]
pub use client::Client;
| 41.757895 | 281 | 0.739854 |
3930d5371315465a146678568fe1a8432766800a | 90 | fn main() {
let y: int = 42;
let mut x: int;
x <- y;
assert (x == 42);
}
| 11.25 | 21 | 0.4 |
030c9576a396a33943c6d78b8f121add9700cd49 | 3,076 | //! # Simple Clap Logger
//!
//! A simple cli logger, which aims to mimic the clap format of error reporting in order to create a seamless cli experience without formatting inconsistencies.
//!
//! ## Example
//!
//! ```rust
//! use simple_clap_logger::Logger;
//! use log::Level;
//!
//! // Initialize the logger with Info logging level
//! Logger::init_with_level(Level::Info);
//!
//! ```
use colored::{ColoredString, Colorize};
use log::{Level, Log};
/// Main logger struct
pub struct Logger {
level: Level,
}
impl Logger {
/// Initializes logger with a standard logging level of [`Level::Error`]
///
/// # Panics
/// This function may only be called once in the application, as it registers the logger as global logger. In case any init function is called more than once the application panics.
pub fn init() {
Self::init_with_level(Level::Error);
}
/// Initializes logger with provided logging level
///
/// # Panics
/// This function may only be called once in the application, as it registers the logger as global logger. In case any init function is called more than once the application panics.
pub fn init_with_level(level: Level) {
let logger = Logger { level };
log::set_boxed_logger(Box::new(logger))
.expect("Failed to setup logger, as another one is already registered");
log::set_max_level(level.to_level_filter());
}
}
impl Log for Logger {
fn enabled(&self, metadata: &log::Metadata) -> bool {
metadata.level() <= self.level
}
fn log(&self, record: &log::Record) {
if self.level < record.level() {
return;
}
let prefix = get_prefix(&record.level());
if record.level() == Level::Error {
eprintln!("{:6} {}", prefix, record.args());
} else {
println!("{:6} {}", prefix, record.args());
}
}
fn flush(&self) {}
}
/// Returns a colored prefix for each log level
fn get_prefix(level: &Level) -> ColoredString {
match level {
Level::Error => "error:".red().bold(),
Level::Warn => "warn:".yellow().bold(),
Level::Info => "info:".green().bold(),
Level::Debug => "debug:".blue().bold(),
Level::Trace => "trace:".magenta().bold(),
}
}
#[cfg(test)]
mod tests {
use crate::Logger;
use log::{Level, Log, MetadataBuilder};
#[test]
fn check_log_level() {
let logger = Logger { level: Level::Info };
assert!(logger.enabled(&MetadataBuilder::new().level(Level::Error).build()));
assert!(logger.enabled(&MetadataBuilder::new().level(Level::Warn).build()));
assert!(logger.enabled(&MetadataBuilder::new().level(Level::Info).build()));
assert!(!logger.enabled(&MetadataBuilder::new().level(Level::Debug).build()));
assert!(!logger.enabled(&MetadataBuilder::new().level(Level::Trace).build()));
}
#[test]
#[should_panic]
fn check_panic() {
let _logger_1 = Logger::init();
let _logger_2 = Logger::init();
}
}
| 30.156863 | 185 | 0.607932 |
188169907be9879c05d24f4c0f6f34fd9be9b1a0 | 476,955 | //! The `bank` module tracks client accounts and the progress of on-chain
//! programs. It offers a high-level API that signs transactions
//! on behalf of the caller, and a low-level API for when they have
//! already been signed and verified.
use crate::{
accounts::{
AccountAddressFilter, Accounts, TransactionAccountDeps, TransactionAccounts,
TransactionLoadResult, TransactionLoaders,
},
accounts_db::{ErrorCounters, SnapshotStorages},
accounts_index::{AccountIndex, Ancestors, IndexKey},
blockhash_queue::BlockhashQueue,
builtins::{self, ActivationType},
epoch_stakes::{EpochStakes, NodeVoteAccounts},
hashed_transaction::{HashedTransaction, HashedTransactionSlice},
inline_spl_token_v2_0,
instruction_recorder::InstructionRecorder,
log_collector::LogCollector,
message_processor::{ExecuteDetailsTimings, Executors, MessageProcessor},
rent_collector::RentCollector,
stakes::Stakes,
status_cache::{SlotDelta, StatusCache},
system_instruction_processor::{get_system_account_kind, SystemAccountKind},
transaction_batch::TransactionBatch,
vote_account::ArcVoteAccount,
};
use byteorder::{ByteOrder, LittleEndian};
use itertools::Itertools;
use log::*;
use rayon::ThreadPool;
use solana_measure::measure::Measure;
use solana_metrics::{datapoint_debug, inc_new_counter_debug, inc_new_counter_info};
use solana_sdk::{
account::{
create_account_shared_data_with_fields as create_account, from_account, Account,
AccountSharedData, InheritableAccountFields, ReadableAccount, WritableAccount,
},
clock::{
Epoch, Slot, SlotCount, SlotIndex, UnixTimestamp, DEFAULT_TICKS_PER_SECOND,
INITIAL_RENT_EPOCH, MAX_PROCESSING_AGE, MAX_RECENT_BLOCKHASHES,
MAX_TRANSACTION_FORWARDING_DELAY, SECONDS_PER_DAY,
},
epoch_info::EpochInfo,
epoch_schedule::EpochSchedule,
feature,
feature_set::{self, FeatureSet},
fee_calculator::{FeeCalculator, FeeConfig, FeeRateGovernor},
genesis_config::{ClusterType, GenesisConfig},
hard_forks::HardForks,
hash::{extend_and_hash, hashv, Hash},
incinerator,
inflation::Inflation,
instruction::CompiledInstruction,
message::Message,
native_loader,
native_token::sol_to_lamports,
nonce, nonce_account,
process_instruction::{BpfComputeBudget, Executor, ProcessInstructionWithContext},
program_utils::limited_deserialize,
pubkey::Pubkey,
recent_blockhashes_account,
sanitize::Sanitize,
signature::{Keypair, Signature},
slot_hashes::SlotHashes,
slot_history::SlotHistory,
stake_weighted_timestamp::{
calculate_stake_weighted_timestamp, MaxAllowableDrift, MAX_ALLOWABLE_DRIFT_PERCENTAGE,
MAX_ALLOWABLE_DRIFT_PERCENTAGE_FAST, MAX_ALLOWABLE_DRIFT_PERCENTAGE_SLOW,
},
system_transaction,
sysvar::{self},
timing::years_as_slots,
transaction::{self, Result, Transaction, TransactionError},
};
use solana_stake_program::stake_state::{
self, Delegation, InflationPointCalculationEvent, PointValue,
};
use solana_vote_program::vote_instruction::VoteInstruction;
use std::{
borrow::Cow,
cell::RefCell,
collections::{HashMap, HashSet},
convert::{TryFrom, TryInto},
fmt, mem,
ops::RangeInclusive,
path::PathBuf,
ptr,
rc::Rc,
sync::{
atomic::{AtomicBool, AtomicU64, Ordering::Relaxed},
LockResult, RwLockWriteGuard, {Arc, RwLock, RwLockReadGuard},
},
time::Duration,
time::Instant,
};
pub const SECONDS_PER_YEAR: f64 = 365.25 * 24.0 * 60.0 * 60.0;
pub const MAX_LEADER_SCHEDULE_STAKES: Epoch = 5;
#[derive(Default, Debug)]
pub struct ExecuteTimings {
pub check_us: u64,
pub load_us: u64,
pub execute_us: u64,
pub store_us: u64,
pub details: ExecuteDetailsTimings,
}
impl ExecuteTimings {
pub fn accumulate(&mut self, other: &ExecuteTimings) {
self.check_us += other.check_us;
self.load_us += other.load_us;
self.execute_us += other.execute_us;
self.store_us += other.store_us;
self.details.accumulate(&other.details);
}
}
type BankStatusCache = StatusCache<Result<()>>;
#[frozen_abi(digest = "F3Ubz2Sx973pKSYNHTEmj6LY3te1DKUo3fs3cgzQ1uqJ")]
pub type BankSlotDelta = SlotDelta<Result<()>>;
type TransactionAccountRefCells = Vec<Rc<RefCell<AccountSharedData>>>;
type TransactionAccountDepRefCells = Vec<(Pubkey, Rc<RefCell<AccountSharedData>>)>;
type TransactionLoaderRefCells = Vec<Vec<(Pubkey, Rc<RefCell<AccountSharedData>>)>>;
// Eager rent collection repeats in cyclic manner.
// Each cycle is composed of <partition_count> number of tiny pubkey subranges
// to scan, which is always multiple of the number of slots in epoch.
type PartitionIndex = u64;
type PartitionsPerCycle = u64;
type Partition = (PartitionIndex, PartitionIndex, PartitionsPerCycle);
type RentCollectionCycleParams = (
Epoch,
SlotCount,
bool,
Epoch,
EpochCount,
PartitionsPerCycle,
);
type EpochCount = u64;
#[derive(Clone)]
pub struct Builtin {
pub name: String,
pub id: Pubkey,
pub process_instruction_with_context: ProcessInstructionWithContext,
}
impl Builtin {
pub fn new(
name: &str,
id: Pubkey,
process_instruction_with_context: ProcessInstructionWithContext,
) -> Self {
Self {
name: name.to_string(),
id,
process_instruction_with_context,
}
}
}
impl fmt::Debug for Builtin {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Builtin [name={}, id={}]", self.name, self.id)
}
}
/// Copy-on-write holder of CachedExecutors
#[derive(AbiExample, Debug, Default)]
struct CowCachedExecutors {
shared: bool,
executors: Arc<RwLock<CachedExecutors>>,
}
impl Clone for CowCachedExecutors {
fn clone(&self) -> Self {
Self {
shared: true,
executors: self.executors.clone(),
}
}
}
impl CowCachedExecutors {
fn new(executors: Arc<RwLock<CachedExecutors>>) -> Self {
Self {
shared: true,
executors,
}
}
fn read(&self) -> LockResult<RwLockReadGuard<CachedExecutors>> {
self.executors.read()
}
fn write(&mut self) -> LockResult<RwLockWriteGuard<CachedExecutors>> {
if self.shared {
self.shared = false;
let local_cache = (*self.executors.read().unwrap()).clone();
self.executors = Arc::new(RwLock::new(local_cache));
}
self.executors.write()
}
}
#[cfg(RUSTC_WITH_SPECIALIZATION)]
impl AbiExample for Builtin {
fn example() -> Self {
Self {
name: String::default(),
id: Pubkey::default(),
process_instruction_with_context: |_, _, _| Ok(()),
}
}
}
#[derive(Clone, Debug)]
pub struct Builtins {
/// Builtin programs that are always available
pub genesis_builtins: Vec<Builtin>,
/// Builtin programs activated dynamically by feature
pub feature_builtins: Vec<(Builtin, Pubkey, ActivationType)>,
}
const MAX_CACHED_EXECUTORS: usize = 100; // 10 MB assuming programs are around 100k
/// LFU Cache of executors
#[derive(Debug)]
struct CachedExecutors {
max: usize,
executors: HashMap<Pubkey, (AtomicU64, Arc<dyn Executor>)>,
}
impl Default for CachedExecutors {
fn default() -> Self {
Self {
max: MAX_CACHED_EXECUTORS,
executors: HashMap::new(),
}
}
}
#[cfg(RUSTC_WITH_SPECIALIZATION)]
impl AbiExample for CachedExecutors {
fn example() -> Self {
// Delegate AbiExample impl to Default before going deep and stuck with
// not easily impl-able Arc<dyn Executor> due to rust's coherence issue
// This is safe because CachedExecutors isn't serializable by definition.
Self::default()
}
}
impl Clone for CachedExecutors {
fn clone(&self) -> Self {
let mut executors = HashMap::new();
for (key, (count, executor)) in self.executors.iter() {
executors.insert(
*key,
(AtomicU64::new(count.load(Relaxed)), executor.clone()),
);
}
Self {
max: self.max,
executors,
}
}
}
impl CachedExecutors {
fn new(max: usize) -> Self {
Self {
max,
executors: HashMap::new(),
}
}
fn get(&self, pubkey: &Pubkey) -> Option<Arc<dyn Executor>> {
self.executors.get(pubkey).map(|(count, executor)| {
count.fetch_add(1, Relaxed);
executor.clone()
})
}
fn put(&mut self, pubkey: &Pubkey, executor: Arc<dyn Executor>) {
if !self.executors.contains_key(pubkey) && self.executors.len() >= self.max {
let mut least = u64::MAX;
let default_key = Pubkey::default();
let mut least_key = &default_key;
for (key, (count, _)) in self.executors.iter() {
let count = count.load(Relaxed);
if count < least {
least = count;
least_key = key;
}
}
let least_key = *least_key;
let _ = self.executors.remove(&least_key);
}
let _ = self
.executors
.insert(*pubkey, (AtomicU64::new(0), executor));
}
fn remove(&mut self, pubkey: &Pubkey) {
let _ = self.executors.remove(pubkey);
}
}
#[derive(Default, Debug)]
pub struct BankRc {
/// where all the Accounts are stored
pub accounts: Arc<Accounts>,
/// Previous checkpoint of this bank
pub(crate) parent: RwLock<Option<Arc<Bank>>>,
/// Current slot
pub(crate) slot: Slot,
}
#[cfg(RUSTC_WITH_SPECIALIZATION)]
use solana_frozen_abi::abi_example::AbiExample;
#[cfg(RUSTC_WITH_SPECIALIZATION)]
impl AbiExample for BankRc {
fn example() -> Self {
BankRc {
// Set parent to None to cut the recursion into another Bank
parent: RwLock::new(None),
// AbiExample for Accounts is specially implemented to contain a storage example
accounts: AbiExample::example(),
slot: AbiExample::example(),
}
}
}
impl BankRc {
pub(crate) fn new(accounts: Accounts, slot: Slot) -> Self {
Self {
accounts: Arc::new(accounts),
parent: RwLock::new(None),
slot,
}
}
pub fn get_snapshot_storages(&self, slot: Slot) -> SnapshotStorages {
self.accounts.accounts_db.get_snapshot_storages(slot)
}
}
#[derive(Default, Debug, AbiExample)]
pub struct StatusCacheRc {
/// where all the Accounts are stored
/// A cache of signature statuses
pub status_cache: Arc<RwLock<BankStatusCache>>,
}
impl StatusCacheRc {
pub fn slot_deltas(&self, slots: &[Slot]) -> Vec<BankSlotDelta> {
let sc = self.status_cache.read().unwrap();
sc.slot_deltas(slots)
}
pub fn roots(&self) -> Vec<Slot> {
self.status_cache
.read()
.unwrap()
.roots()
.iter()
.cloned()
.sorted()
.collect()
}
pub fn append(&self, slot_deltas: &[BankSlotDelta]) {
let mut sc = self.status_cache.write().unwrap();
sc.append(slot_deltas);
}
}
pub type TransactionCheckResult = (Result<()>, Option<NonceRollbackPartial>);
pub type TransactionExecutionResult = (Result<()>, Option<NonceRollbackFull>);
pub struct TransactionResults {
pub fee_collection_results: Vec<Result<()>>,
pub execution_results: Vec<TransactionExecutionResult>,
pub overwritten_vote_accounts: Vec<OverwrittenVoteAccount>,
}
pub struct TransactionBalancesSet {
pub pre_balances: TransactionBalances,
pub post_balances: TransactionBalances,
}
pub struct OverwrittenVoteAccount {
pub account: ArcVoteAccount,
pub transaction_index: usize,
pub transaction_result_index: usize,
}
impl TransactionBalancesSet {
pub fn new(pre_balances: TransactionBalances, post_balances: TransactionBalances) -> Self {
assert_eq!(pre_balances.len(), post_balances.len());
Self {
pre_balances,
post_balances,
}
}
}
pub type TransactionBalances = Vec<Vec<u64>>;
/// An ordered list of instructions that were invoked during a transaction instruction
pub type InnerInstructions = Vec<CompiledInstruction>;
/// A list of instructions that were invoked during each instruction of a transaction
pub type InnerInstructionsList = Vec<InnerInstructions>;
/// A list of log messages emitted during a transaction
pub type TransactionLogMessages = Vec<String>;
#[derive(Serialize, Deserialize, AbiExample, AbiEnumVisitor, Debug, PartialEq)]
pub enum TransactionLogCollectorFilter {
All,
AllWithVotes,
None,
OnlyMentionedAddresses,
}
impl Default for TransactionLogCollectorFilter {
fn default() -> Self {
Self::None
}
}
#[derive(AbiExample, Debug, Default)]
pub struct TransactionLogCollectorConfig {
pub mentioned_addresses: HashSet<Pubkey>,
pub filter: TransactionLogCollectorFilter,
}
#[derive(AbiExample, Clone, Debug)]
pub struct TransactionLogInfo {
pub signature: Signature,
pub result: Result<()>,
pub is_vote: bool,
pub log_messages: TransactionLogMessages,
}
#[derive(AbiExample, Default, Debug)]
pub struct TransactionLogCollector {
// All the logs collected for from this Bank. Exact contents depend on the
// active `TransactionLogCollectorFilter`
pub logs: Vec<TransactionLogInfo>,
// For each `mentioned_addresses`, maintain a list of indices into `logs` to easily
// locate the logs from transactions that included the mentioned addresses.
pub mentioned_address_map: HashMap<Pubkey, Vec<usize>>,
}
pub trait NonceRollbackInfo {
fn nonce_address(&self) -> &Pubkey;
fn nonce_account(&self) -> &AccountSharedData;
fn fee_calculator(&self) -> Option<FeeCalculator>;
fn fee_account(&self) -> Option<&AccountSharedData>;
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct NonceRollbackPartial {
nonce_address: Pubkey,
nonce_account: AccountSharedData,
}
impl NonceRollbackPartial {
pub fn new(nonce_address: Pubkey, nonce_account: AccountSharedData) -> Self {
Self {
nonce_address,
nonce_account,
}
}
}
impl NonceRollbackInfo for NonceRollbackPartial {
fn nonce_address(&self) -> &Pubkey {
&self.nonce_address
}
fn nonce_account(&self) -> &AccountSharedData {
&self.nonce_account
}
fn fee_calculator(&self) -> Option<FeeCalculator> {
nonce_account::fee_calculator_of(&self.nonce_account)
}
fn fee_account(&self) -> Option<&AccountSharedData> {
None
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct NonceRollbackFull {
nonce_address: Pubkey,
nonce_account: AccountSharedData,
fee_account: Option<AccountSharedData>,
}
impl NonceRollbackFull {
#[cfg(test)]
pub fn new(
nonce_address: Pubkey,
nonce_account: AccountSharedData,
fee_account: Option<AccountSharedData>,
) -> Self {
Self {
nonce_address,
nonce_account,
fee_account,
}
}
pub fn from_partial(
partial: NonceRollbackPartial,
message: &Message,
accounts: &[AccountSharedData],
) -> Result<Self> {
let NonceRollbackPartial {
nonce_address,
nonce_account,
} = partial;
let fee_payer = message
.account_keys
.iter()
.enumerate()
.find(|(i, k)| message.is_non_loader_key(k, *i))
.and_then(|(i, k)| accounts.get(i).cloned().map(|a| (*k, a)));
if let Some((fee_pubkey, fee_account)) = fee_payer {
if fee_pubkey == nonce_address {
Ok(Self {
nonce_address,
nonce_account: fee_account,
fee_account: None,
})
} else {
Ok(Self {
nonce_address,
nonce_account,
fee_account: Some(fee_account),
})
}
} else {
Err(TransactionError::AccountNotFound)
}
}
}
impl NonceRollbackInfo for NonceRollbackFull {
fn nonce_address(&self) -> &Pubkey {
&self.nonce_address
}
fn nonce_account(&self) -> &AccountSharedData {
&self.nonce_account
}
fn fee_calculator(&self) -> Option<FeeCalculator> {
nonce_account::fee_calculator_of(&self.nonce_account)
}
fn fee_account(&self) -> Option<&AccountSharedData> {
self.fee_account.as_ref()
}
}
// Bank's common fields shared by all supported snapshot versions for deserialization.
// Sync fields with BankFieldsToSerialize! This is paired with it.
// All members are made public to remain Bank's members private and to make versioned deserializer workable on this
#[derive(Clone, Debug, Default)]
pub(crate) struct BankFieldsToDeserialize {
pub(crate) blockhash_queue: BlockhashQueue,
pub(crate) ancestors: Ancestors,
pub(crate) hash: Hash,
pub(crate) parent_hash: Hash,
pub(crate) parent_slot: Slot,
pub(crate) hard_forks: HardForks,
pub(crate) transaction_count: u64,
pub(crate) tick_height: u64,
pub(crate) signature_count: u64,
pub(crate) capitalization: u64,
pub(crate) max_tick_height: u64,
pub(crate) hashes_per_tick: Option<u64>,
pub(crate) ticks_per_slot: u64,
pub(crate) ns_per_slot: u128,
pub(crate) genesis_creation_time: UnixTimestamp,
pub(crate) slots_per_year: f64,
pub(crate) unused: u64,
pub(crate) slot: Slot,
pub(crate) epoch: Epoch,
pub(crate) block_height: u64,
pub(crate) collector_id: Pubkey,
pub(crate) collector_fees: u64,
pub(crate) fee_calculator: FeeCalculator,
pub(crate) fee_rate_governor: FeeRateGovernor,
pub(crate) collected_rent: u64,
pub(crate) rent_collector: RentCollector,
pub(crate) epoch_schedule: EpochSchedule,
pub(crate) inflation: Inflation,
pub(crate) stakes: Stakes,
pub(crate) epoch_stakes: HashMap<Epoch, EpochStakes>,
pub(crate) is_delta: bool,
}
// Bank's common fields shared by all supported snapshot versions for serialization.
// This is separated from BankFieldsToDeserialize to avoid cloning by using refs.
// So, sync fields with BankFieldsToDeserialize!
// all members are made public to remain Bank private and to make versioned serializer workable on this
#[derive(Debug)]
pub(crate) struct BankFieldsToSerialize<'a> {
pub(crate) blockhash_queue: &'a RwLock<BlockhashQueue>,
pub(crate) ancestors: &'a Ancestors,
pub(crate) hash: Hash,
pub(crate) parent_hash: Hash,
pub(crate) parent_slot: Slot,
pub(crate) hard_forks: &'a RwLock<HardForks>,
pub(crate) transaction_count: u64,
pub(crate) tick_height: u64,
pub(crate) signature_count: u64,
pub(crate) capitalization: u64,
pub(crate) max_tick_height: u64,
pub(crate) hashes_per_tick: Option<u64>,
pub(crate) ticks_per_slot: u64,
pub(crate) ns_per_slot: u128,
pub(crate) genesis_creation_time: UnixTimestamp,
pub(crate) slots_per_year: f64,
pub(crate) unused: u64,
pub(crate) slot: Slot,
pub(crate) epoch: Epoch,
pub(crate) block_height: u64,
pub(crate) collector_id: Pubkey,
pub(crate) collector_fees: u64,
pub(crate) fee_calculator: FeeCalculator,
pub(crate) fee_rate_governor: FeeRateGovernor,
pub(crate) collected_rent: u64,
pub(crate) rent_collector: RentCollector,
pub(crate) epoch_schedule: EpochSchedule,
pub(crate) inflation: Inflation,
pub(crate) stakes: &'a RwLock<Stakes>,
pub(crate) epoch_stakes: &'a HashMap<Epoch, EpochStakes>,
pub(crate) is_delta: bool,
}
// Can't derive PartialEq because RwLock doesn't implement PartialEq
impl PartialEq for Bank {
fn eq(&self, other: &Self) -> bool {
if ptr::eq(self, other) {
return true;
}
*self.blockhash_queue.read().unwrap() == *other.blockhash_queue.read().unwrap()
&& self.ancestors == other.ancestors
&& *self.hash.read().unwrap() == *other.hash.read().unwrap()
&& self.parent_hash == other.parent_hash
&& self.parent_slot == other.parent_slot
&& *self.hard_forks.read().unwrap() == *other.hard_forks.read().unwrap()
&& self.transaction_count.load(Relaxed) == other.transaction_count.load(Relaxed)
&& self.tick_height.load(Relaxed) == other.tick_height.load(Relaxed)
&& self.signature_count.load(Relaxed) == other.signature_count.load(Relaxed)
&& self.capitalization.load(Relaxed) == other.capitalization.load(Relaxed)
&& self.max_tick_height == other.max_tick_height
&& self.hashes_per_tick == other.hashes_per_tick
&& self.ticks_per_slot == other.ticks_per_slot
&& self.ns_per_slot == other.ns_per_slot
&& self.genesis_creation_time == other.genesis_creation_time
&& self.slots_per_year == other.slots_per_year
&& self.unused == other.unused
&& self.slot == other.slot
&& self.epoch == other.epoch
&& self.block_height == other.block_height
&& self.collector_id == other.collector_id
&& self.collector_fees.load(Relaxed) == other.collector_fees.load(Relaxed)
&& self.fee_calculator == other.fee_calculator
&& self.fee_rate_governor == other.fee_rate_governor
&& self.collected_rent.load(Relaxed) == other.collected_rent.load(Relaxed)
&& self.rent_collector == other.rent_collector
&& self.epoch_schedule == other.epoch_schedule
&& *self.inflation.read().unwrap() == *other.inflation.read().unwrap()
&& *self.stakes.read().unwrap() == *other.stakes.read().unwrap()
&& self.epoch_stakes == other.epoch_stakes
&& self.is_delta.load(Relaxed) == other.is_delta.load(Relaxed)
}
}
#[derive(Debug, PartialEq, Serialize, Deserialize, AbiExample, AbiEnumVisitor, Clone, Copy)]
pub enum RewardType {
Fee,
Rent,
Staking,
Voting,
}
#[derive(Debug)]
pub enum RewardCalculationEvent<'a, 'b> {
Staking(&'a Pubkey, &'b InflationPointCalculationEvent),
}
fn null_tracer() -> Option<impl FnMut(&RewardCalculationEvent)> {
None::<fn(&RewardCalculationEvent)>
}
impl fmt::Display for RewardType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match self {
RewardType::Fee => "fee",
RewardType::Rent => "rent",
RewardType::Staking => "staking",
RewardType::Voting => "voting",
}
)
}
}
pub trait DropCallback: fmt::Debug {
fn callback(&self, b: &Bank);
fn clone_box(&self) -> Box<dyn DropCallback + Send + Sync>;
}
#[derive(Debug, PartialEq, Serialize, Deserialize, AbiExample, Clone, Copy)]
pub struct RewardInfo {
pub reward_type: RewardType,
pub lamports: i64, // Reward amount
pub post_balance: u64, // Account balance in lamports after `lamports` was applied
}
#[derive(Debug, Default)]
pub struct OptionalDropCallback(Option<Box<dyn DropCallback + Send + Sync>>);
#[cfg(RUSTC_WITH_SPECIALIZATION)]
impl AbiExample for OptionalDropCallback {
fn example() -> Self {
Self(None)
}
}
/// Manager for the state of all accounts and programs after processing its entries.
/// AbiExample is needed even without Serialize/Deserialize; actual (de-)serialization
/// are implemented elsewhere for versioning
#[derive(AbiExample, Debug, Default)]
pub struct Bank {
/// References to accounts, parent and signature status
pub rc: BankRc,
pub src: StatusCacheRc,
/// FIFO queue of `recent_blockhash` items
blockhash_queue: RwLock<BlockhashQueue>,
/// The set of parents including this bank
pub ancestors: Ancestors,
/// Hash of this Bank's state. Only meaningful after freezing.
hash: RwLock<Hash>,
/// Hash of this Bank's parent's state
parent_hash: Hash,
/// parent's slot
parent_slot: Slot,
/// slots to hard fork at
hard_forks: Arc<RwLock<HardForks>>,
/// The number of transactions processed without error
transaction_count: AtomicU64,
/// The number of transaction errors in this slot
transaction_error_count: AtomicU64,
/// The number of transaction entries in this slot
transaction_entries_count: AtomicU64,
/// The max number of transaction in an entry in this slot
transactions_per_entry_max: AtomicU64,
/// Bank tick height
tick_height: AtomicU64,
/// The number of signatures from valid transactions in this slot
signature_count: AtomicU64,
/// Total capitalization, used to calculate inflation
capitalization: AtomicU64,
// Bank max_tick_height
max_tick_height: u64,
/// The number of hashes in each tick. None value means hashing is disabled.
hashes_per_tick: Option<u64>,
/// The number of ticks in each slot.
ticks_per_slot: u64,
/// length of a slot in ns
pub ns_per_slot: u128,
/// genesis time, used for computed clock
genesis_creation_time: UnixTimestamp,
/// The number of slots per year, used for inflation
slots_per_year: f64,
/// Unused
unused: u64,
/// Bank slot (i.e. block)
slot: Slot,
/// Bank epoch
epoch: Epoch,
/// Bank block_height
block_height: u64,
/// The pubkey to send transactions fees to.
collector_id: Pubkey,
/// Fees that have been collected
collector_fees: AtomicU64,
/// Latest transaction fees for transactions processed by this bank
fee_calculator: FeeCalculator,
/// Track cluster signature throughput and adjust fee rate
fee_rate_governor: FeeRateGovernor,
/// Rent that has been collected
collected_rent: AtomicU64,
/// latest rent collector, knows the epoch
rent_collector: RentCollector,
/// initialized from genesis
epoch_schedule: EpochSchedule,
/// inflation specs
inflation: Arc<RwLock<Inflation>>,
/// cache of vote_account and stake_account state for this fork
stakes: RwLock<Stakes>,
/// staked nodes on epoch boundaries, saved off when a bank.slot() is at
/// a leader schedule calculation boundary
epoch_stakes: HashMap<Epoch, EpochStakes>,
/// A boolean reflecting whether any entries were recorded into the PoH
/// stream for the slot == self.slot
is_delta: AtomicBool,
/// The Message processor
message_processor: MessageProcessor,
bpf_compute_budget: Option<BpfComputeBudget>,
/// Builtin programs activated dynamically by feature
#[allow(clippy::rc_buffer)]
feature_builtins: Arc<Vec<(Builtin, Pubkey, ActivationType)>>,
/// Last time when the cluster info vote listener has synced with this bank
pub last_vote_sync: AtomicU64,
/// Protocol-level rewards that were distributed by this bank
pub rewards: RwLock<Vec<(Pubkey, RewardInfo)>>,
pub skip_drop: AtomicBool,
pub cluster_type: Option<ClusterType>,
pub lazy_rent_collection: AtomicBool,
pub no_stake_rewrite: AtomicBool,
// this is temporary field only to remove rewards_pool entirely
pub rewards_pool_pubkeys: Arc<HashSet<Pubkey>>,
/// Cached executors
cached_executors: RwLock<CowCachedExecutors>,
transaction_debug_keys: Option<Arc<HashSet<Pubkey>>>,
// Global configuration for how transaction logs should be collected across all banks
pub transaction_log_collector_config: Arc<RwLock<TransactionLogCollectorConfig>>,
// Logs from transactions that this Bank executed collected according to the criteria in
// `transaction_log_collector_config`
pub transaction_log_collector: Arc<RwLock<TransactionLogCollector>>,
pub feature_set: Arc<FeatureSet>,
pub drop_callback: RwLock<OptionalDropCallback>,
pub freeze_started: AtomicBool,
}
impl Default for BlockhashQueue {
fn default() -> Self {
Self::new(MAX_RECENT_BLOCKHASHES)
}
}
impl Bank {
pub fn new(genesis_config: &GenesisConfig) -> Self {
Self::new_with_paths(
&genesis_config,
Vec::new(),
&[],
None,
None,
HashSet::new(),
false,
)
}
pub fn new_no_wallclock_throttle(genesis_config: &GenesisConfig) -> Self {
let mut bank = Self::new_with_paths(
&genesis_config,
Vec::new(),
&[],
None,
None,
HashSet::new(),
false,
);
bank.ns_per_slot = std::u128::MAX;
bank
}
#[cfg(test)]
pub(crate) fn new_with_config(
genesis_config: &GenesisConfig,
account_indexes: HashSet<AccountIndex>,
accounts_db_caching_enabled: bool,
) -> Self {
Self::new_with_paths(
&genesis_config,
Vec::new(),
&[],
None,
None,
account_indexes,
accounts_db_caching_enabled,
)
}
pub fn new_with_paths(
genesis_config: &GenesisConfig,
paths: Vec<PathBuf>,
frozen_account_pubkeys: &[Pubkey],
debug_keys: Option<Arc<HashSet<Pubkey>>>,
additional_builtins: Option<&Builtins>,
account_indexes: HashSet<AccountIndex>,
accounts_db_caching_enabled: bool,
) -> Self {
let mut bank = Self::default();
bank.ancestors.insert(bank.slot(), 0);
bank.transaction_debug_keys = debug_keys;
bank.cluster_type = Some(genesis_config.cluster_type);
bank.rc.accounts = Arc::new(Accounts::new_with_config(
paths,
&genesis_config.cluster_type,
account_indexes,
accounts_db_caching_enabled,
));
bank.process_genesis_config(genesis_config);
bank.finish_init(genesis_config, additional_builtins);
// Freeze accounts after process_genesis_config creates the initial append vecs
Arc::get_mut(&mut Arc::get_mut(&mut bank.rc.accounts).unwrap().accounts_db)
.unwrap()
.freeze_accounts(&bank.ancestors, frozen_account_pubkeys);
// genesis needs stakes for all epochs up to the epoch implied by
// slot = 0 and genesis configuration
{
let stakes = bank.stakes.read().unwrap();
for epoch in 0..=bank.get_leader_schedule_epoch(bank.slot) {
bank.epoch_stakes
.insert(epoch, EpochStakes::new(&stakes, epoch));
}
bank.update_stake_history(None);
}
bank.update_clock(None);
bank.update_rent();
bank.update_epoch_schedule();
bank.update_recent_blockhashes();
bank
}
/// Create a new bank that points to an immutable checkpoint of another bank.
pub fn new_from_parent(parent: &Arc<Bank>, collector_id: &Pubkey, slot: Slot) -> Self {
Self::_new_from_parent(parent, collector_id, slot, &mut null_tracer())
}
pub fn new_from_parent_with_tracer(
parent: &Arc<Bank>,
collector_id: &Pubkey,
slot: Slot,
reward_calc_tracer: impl FnMut(&RewardCalculationEvent),
) -> Self {
Self::_new_from_parent(parent, collector_id, slot, &mut Some(reward_calc_tracer))
}
fn _new_from_parent(
parent: &Arc<Bank>,
collector_id: &Pubkey,
slot: Slot,
reward_calc_tracer: &mut Option<impl FnMut(&RewardCalculationEvent)>,
) -> Self {
parent.freeze();
assert_ne!(slot, parent.slot());
let epoch_schedule = parent.epoch_schedule;
let epoch = epoch_schedule.get_epoch(slot);
let rc = BankRc {
accounts: Arc::new(Accounts::new_from_parent(
&parent.rc.accounts,
slot,
parent.slot(),
)),
parent: RwLock::new(Some(parent.clone())),
slot,
};
let src = StatusCacheRc {
status_cache: parent.src.status_cache.clone(),
};
let fee_rate_governor =
FeeRateGovernor::new_derived(&parent.fee_rate_governor, parent.signature_count());
let mut new = Bank {
rc,
src,
slot,
epoch,
blockhash_queue: RwLock::new(parent.blockhash_queue.read().unwrap().clone()),
// TODO: clean this up, so much special-case copying...
hashes_per_tick: parent.hashes_per_tick,
ticks_per_slot: parent.ticks_per_slot,
ns_per_slot: parent.ns_per_slot,
genesis_creation_time: parent.genesis_creation_time,
unused: parent.unused,
slots_per_year: parent.slots_per_year,
epoch_schedule,
collected_rent: AtomicU64::new(0),
rent_collector: parent.rent_collector.clone_with_epoch(epoch),
max_tick_height: (slot + 1) * parent.ticks_per_slot,
block_height: parent.block_height + 1,
fee_calculator: fee_rate_governor.create_fee_calculator(),
fee_rate_governor,
capitalization: AtomicU64::new(parent.capitalization()),
inflation: parent.inflation.clone(),
transaction_count: AtomicU64::new(parent.transaction_count()),
transaction_error_count: AtomicU64::new(0),
transaction_entries_count: AtomicU64::new(0),
transactions_per_entry_max: AtomicU64::new(0),
// we will .clone_with_epoch() this soon after stake data update; so just .clone() for now
stakes: RwLock::new(parent.stakes.read().unwrap().clone()),
epoch_stakes: parent.epoch_stakes.clone(),
parent_hash: parent.hash(),
parent_slot: parent.slot(),
collector_id: *collector_id,
collector_fees: AtomicU64::new(0),
ancestors: Ancestors::default(),
hash: RwLock::new(Hash::default()),
is_delta: AtomicBool::new(false),
tick_height: AtomicU64::new(parent.tick_height.load(Relaxed)),
signature_count: AtomicU64::new(0),
message_processor: parent.message_processor.clone(),
bpf_compute_budget: parent.bpf_compute_budget,
feature_builtins: parent.feature_builtins.clone(),
hard_forks: parent.hard_forks.clone(),
last_vote_sync: AtomicU64::new(parent.last_vote_sync.load(Relaxed)),
rewards: RwLock::new(vec![]),
skip_drop: AtomicBool::new(false),
cluster_type: parent.cluster_type,
lazy_rent_collection: AtomicBool::new(parent.lazy_rent_collection.load(Relaxed)),
no_stake_rewrite: AtomicBool::new(parent.no_stake_rewrite.load(Relaxed)),
rewards_pool_pubkeys: parent.rewards_pool_pubkeys.clone(),
cached_executors: RwLock::new((*parent.cached_executors.read().unwrap()).clone()),
transaction_debug_keys: parent.transaction_debug_keys.clone(),
transaction_log_collector_config: parent.transaction_log_collector_config.clone(),
transaction_log_collector: Arc::new(RwLock::new(TransactionLogCollector::default())),
feature_set: parent.feature_set.clone(),
drop_callback: RwLock::new(OptionalDropCallback(
parent
.drop_callback
.read()
.unwrap()
.0
.as_ref()
.map(|drop_callback| drop_callback.clone_box()),
)),
freeze_started: AtomicBool::new(false),
};
datapoint_info!(
"bank-new_from_parent-heights",
("slot_height", slot, i64),
("block_height", new.block_height, i64)
);
new.ancestors.insert(new.slot(), 0);
new.parents().iter().enumerate().for_each(|(i, p)| {
new.ancestors.insert(p.slot(), i + 1);
});
// Following code may touch AccountsDb, requiring proper ancestors
let parent_epoch = parent.epoch();
if parent_epoch < new.epoch() {
new.apply_feature_activations(false);
}
let cloned = new
.stakes
.read()
.unwrap()
.clone_with_epoch(epoch, new.stake_program_v2_enabled());
*new.stakes.write().unwrap() = cloned;
let leader_schedule_epoch = epoch_schedule.get_leader_schedule_epoch(slot);
new.update_epoch_stakes(leader_schedule_epoch);
new.update_slot_hashes();
new.update_rewards(parent_epoch, reward_calc_tracer);
new.update_stake_history(Some(parent_epoch));
new.update_clock(Some(parent_epoch));
new.update_fees();
if !new.fix_recent_blockhashes_sysvar_delay() {
new.update_recent_blockhashes();
}
new
}
/// Returns all ancestors excluding self.slot.
pub(crate) fn proper_ancestors(&self) -> impl Iterator<Item = Slot> + '_ {
self.ancestors
.keys()
.copied()
.filter(move |slot| *slot != self.slot)
}
pub fn set_callback(&self, callback: Option<Box<dyn DropCallback + Send + Sync>>) {
*self.drop_callback.write().unwrap() = OptionalDropCallback(callback);
}
/// Like `new_from_parent` but additionally:
/// * Doesn't assume that the parent is anywhere near `slot`, parent could be millions of slots
/// in the past
/// * Adjusts the new bank's tick height to avoid having to run PoH for millions of slots
/// * Freezes the new bank, assuming that the user will `Bank::new_from_parent` from this bank
pub fn warp_from_parent(parent: &Arc<Bank>, collector_id: &Pubkey, slot: Slot) -> Self {
let parent_timestamp = parent.clock().unix_timestamp;
let mut new = Bank::new_from_parent(parent, collector_id, slot);
new.apply_feature_activations(true);
new.update_epoch_stakes(new.epoch_schedule().get_epoch(slot));
new.tick_height.store(new.max_tick_height(), Relaxed);
let mut clock = new.clock();
clock.epoch_start_timestamp = parent_timestamp;
clock.unix_timestamp = parent_timestamp;
new.update_sysvar_account(&sysvar::clock::id(), |account| {
create_account(
&clock,
new.inherit_specially_retained_account_fields(account),
)
});
new.freeze();
new
}
/// Create a bank from explicit arguments and deserialized fields from snapshot
#[allow(clippy::float_cmp)]
pub(crate) fn new_from_fields(
bank_rc: BankRc,
genesis_config: &GenesisConfig,
fields: BankFieldsToDeserialize,
debug_keys: Option<Arc<HashSet<Pubkey>>>,
additional_builtins: Option<&Builtins>,
) -> Self {
fn new<T: Default>() -> T {
T::default()
}
let mut bank = Self {
rc: bank_rc,
src: new(),
blockhash_queue: RwLock::new(fields.blockhash_queue),
ancestors: fields.ancestors,
hash: RwLock::new(fields.hash),
parent_hash: fields.parent_hash,
parent_slot: fields.parent_slot,
hard_forks: Arc::new(RwLock::new(fields.hard_forks)),
transaction_count: AtomicU64::new(fields.transaction_count),
transaction_error_count: new(),
transaction_entries_count: new(),
transactions_per_entry_max: new(),
tick_height: AtomicU64::new(fields.tick_height),
signature_count: AtomicU64::new(fields.signature_count),
capitalization: AtomicU64::new(fields.capitalization),
max_tick_height: fields.max_tick_height,
hashes_per_tick: fields.hashes_per_tick,
ticks_per_slot: fields.ticks_per_slot,
ns_per_slot: fields.ns_per_slot,
genesis_creation_time: fields.genesis_creation_time,
slots_per_year: fields.slots_per_year,
unused: genesis_config.unused,
slot: fields.slot,
epoch: fields.epoch,
block_height: fields.block_height,
collector_id: fields.collector_id,
collector_fees: AtomicU64::new(fields.collector_fees),
fee_calculator: fields.fee_calculator,
fee_rate_governor: fields.fee_rate_governor,
collected_rent: AtomicU64::new(fields.collected_rent),
// clone()-ing is needed to consider a gated behavior in rent_collector
rent_collector: fields.rent_collector.clone_with_epoch(fields.epoch),
epoch_schedule: fields.epoch_schedule,
inflation: Arc::new(RwLock::new(fields.inflation)),
stakes: RwLock::new(fields.stakes),
epoch_stakes: fields.epoch_stakes,
is_delta: AtomicBool::new(fields.is_delta),
message_processor: new(),
bpf_compute_budget: None,
feature_builtins: new(),
last_vote_sync: new(),
rewards: new(),
skip_drop: new(),
cluster_type: Some(genesis_config.cluster_type),
lazy_rent_collection: new(),
no_stake_rewrite: new(),
rewards_pool_pubkeys: new(),
cached_executors: RwLock::new(CowCachedExecutors::new(Arc::new(RwLock::new(
CachedExecutors::new(MAX_CACHED_EXECUTORS),
)))),
transaction_debug_keys: debug_keys,
transaction_log_collector_config: new(),
transaction_log_collector: new(),
feature_set: new(),
drop_callback: RwLock::new(OptionalDropCallback(None)),
freeze_started: AtomicBool::new(fields.hash != Hash::default()),
};
bank.finish_init(genesis_config, additional_builtins);
// Sanity assertions between bank snapshot and genesis config
// Consider removing from serializable bank state
// (BankFieldsToSerialize/BankFieldsToDeserialize) and initializing
// from the passed in genesis_config instead (as new()/new_with_paths() already do)
assert_eq!(
bank.hashes_per_tick,
genesis_config.poh_config.hashes_per_tick
);
assert_eq!(bank.ticks_per_slot, genesis_config.ticks_per_slot);
assert_eq!(
bank.ns_per_slot,
genesis_config.poh_config.target_tick_duration.as_nanos()
* genesis_config.ticks_per_slot as u128
);
assert_eq!(bank.genesis_creation_time, genesis_config.creation_time);
assert_eq!(bank.unused, genesis_config.unused);
assert_eq!(bank.max_tick_height, (bank.slot + 1) * bank.ticks_per_slot);
assert_eq!(
bank.slots_per_year,
years_as_slots(
1.0,
&genesis_config.poh_config.target_tick_duration,
bank.ticks_per_slot,
)
);
assert_eq!(bank.epoch_schedule, genesis_config.epoch_schedule);
assert_eq!(bank.epoch, bank.epoch_schedule.get_epoch(bank.slot));
bank.fee_rate_governor.lamports_per_signature = bank.fee_calculator.lamports_per_signature;
assert_eq!(
bank.fee_rate_governor.create_fee_calculator(),
bank.fee_calculator
);
bank
}
/// Return subset of bank fields representing serializable state
pub(crate) fn get_fields_to_serialize(&self) -> BankFieldsToSerialize {
BankFieldsToSerialize {
blockhash_queue: &self.blockhash_queue,
ancestors: &self.ancestors,
hash: *self.hash.read().unwrap(),
parent_hash: self.parent_hash,
parent_slot: self.parent_slot,
hard_forks: &*self.hard_forks,
transaction_count: self.transaction_count.load(Relaxed),
tick_height: self.tick_height.load(Relaxed),
signature_count: self.signature_count.load(Relaxed),
capitalization: self.capitalization.load(Relaxed),
max_tick_height: self.max_tick_height,
hashes_per_tick: self.hashes_per_tick,
ticks_per_slot: self.ticks_per_slot,
ns_per_slot: self.ns_per_slot,
genesis_creation_time: self.genesis_creation_time,
slots_per_year: self.slots_per_year,
unused: self.unused,
slot: self.slot,
epoch: self.epoch,
block_height: self.block_height,
collector_id: self.collector_id,
collector_fees: self.collector_fees.load(Relaxed),
fee_calculator: self.fee_calculator.clone(),
fee_rate_governor: self.fee_rate_governor.clone(),
collected_rent: self.collected_rent.load(Relaxed),
rent_collector: self.rent_collector.clone(),
epoch_schedule: self.epoch_schedule,
inflation: *self.inflation.read().unwrap(),
stakes: &self.stakes,
epoch_stakes: &self.epoch_stakes,
is_delta: self.is_delta.load(Relaxed),
}
}
pub fn collector_id(&self) -> &Pubkey {
&self.collector_id
}
pub fn slot(&self) -> Slot {
self.slot
}
pub fn epoch(&self) -> Epoch {
self.epoch
}
pub fn first_normal_epoch(&self) -> Epoch {
self.epoch_schedule.first_normal_epoch
}
pub fn freeze_lock(&self) -> RwLockReadGuard<Hash> {
self.hash.read().unwrap()
}
pub fn hash(&self) -> Hash {
*self.hash.read().unwrap()
}
pub fn is_frozen(&self) -> bool {
*self.hash.read().unwrap() != Hash::default()
}
pub fn freeze_started(&self) -> bool {
self.freeze_started.load(Relaxed)
}
pub fn status_cache_ancestors(&self) -> Vec<u64> {
let mut roots = self.src.status_cache.read().unwrap().roots().clone();
let min = roots.iter().min().cloned().unwrap_or(0);
for ancestor in self.ancestors.keys() {
if *ancestor >= min {
roots.insert(*ancestor);
}
}
let mut ancestors: Vec<_> = roots.into_iter().collect();
#[allow(clippy::stable_sort_primitive)]
ancestors.sort();
ancestors
}
/// computed unix_timestamp at this slot height
pub fn unix_timestamp_from_genesis(&self) -> i64 {
self.genesis_creation_time + ((self.slot as u128 * self.ns_per_slot) / 1_000_000_000) as i64
}
fn update_sysvar_account<F>(&self, pubkey: &Pubkey, updater: F)
where
F: Fn(&Option<AccountSharedData>) -> AccountSharedData,
{
let old_account = self.get_sysvar_account_with_fixed_root(pubkey);
let new_account = updater(&old_account);
self.store_account_and_update_capitalization(pubkey, &new_account);
}
fn inherit_specially_retained_account_fields(
&self,
old_account: &Option<AccountSharedData>,
) -> InheritableAccountFields {
(
old_account.as_ref().map(|a| a.lamports).unwrap_or(1),
INITIAL_RENT_EPOCH,
)
}
/// Unused conversion
pub fn get_unused_from_slot(rooted_slot: Slot, unused: u64) -> u64 {
(rooted_slot + (unused - 1)) / unused
}
pub fn clock(&self) -> sysvar::clock::Clock {
from_account(&self.get_account(&sysvar::clock::id()).unwrap_or_default())
.unwrap_or_default()
}
fn update_clock(&self, parent_epoch: Option<Epoch>) {
let mut unix_timestamp = self.clock().unix_timestamp;
let warp_timestamp_again = self
.feature_set
.activated_slot(&feature_set::warp_timestamp_again::id());
let epoch_start_timestamp = if warp_timestamp_again == Some(self.slot()) {
None
} else {
let epoch = if let Some(epoch) = parent_epoch {
epoch
} else {
self.epoch()
};
let first_slot_in_epoch = self.epoch_schedule.get_first_slot_in_epoch(epoch);
Some((first_slot_in_epoch, self.clock().epoch_start_timestamp))
};
let max_allowable_drift = if self
.feature_set
.is_active(&feature_set::warp_timestamp_again::id())
{
MaxAllowableDrift {
fast: MAX_ALLOWABLE_DRIFT_PERCENTAGE_FAST,
slow: MAX_ALLOWABLE_DRIFT_PERCENTAGE_SLOW,
}
} else {
MaxAllowableDrift {
fast: MAX_ALLOWABLE_DRIFT_PERCENTAGE,
slow: MAX_ALLOWABLE_DRIFT_PERCENTAGE,
}
};
let ancestor_timestamp = self.clock().unix_timestamp;
if let Some(timestamp_estimate) =
self.get_timestamp_estimate(max_allowable_drift, epoch_start_timestamp)
{
unix_timestamp = timestamp_estimate;
if timestamp_estimate < ancestor_timestamp {
unix_timestamp = ancestor_timestamp;
}
}
datapoint_info!(
"bank-timestamp-correction",
("slot", self.slot(), i64),
("from_genesis", self.unix_timestamp_from_genesis(), i64),
("corrected", unix_timestamp, i64),
("ancestor_timestamp", ancestor_timestamp, i64),
);
let mut epoch_start_timestamp =
// On epoch boundaries, update epoch_start_timestamp
if parent_epoch.is_some() && parent_epoch.unwrap() != self.epoch() {
unix_timestamp
} else {
self.clock().epoch_start_timestamp
};
if self.slot == 0 {
unix_timestamp = self.unix_timestamp_from_genesis();
epoch_start_timestamp = self.unix_timestamp_from_genesis();
}
let clock = sysvar::clock::Clock {
slot: self.slot,
epoch_start_timestamp,
epoch: self.epoch_schedule.get_epoch(self.slot),
leader_schedule_epoch: self.epoch_schedule.get_leader_schedule_epoch(self.slot),
unix_timestamp,
};
self.update_sysvar_account(&sysvar::clock::id(), |account| {
create_account(
&clock,
self.inherit_specially_retained_account_fields(account),
)
});
}
fn update_slot_history(&self) {
self.update_sysvar_account(&sysvar::slot_history::id(), |account| {
let mut slot_history = account
.as_ref()
.map(|account| from_account::<SlotHistory, _>(account).unwrap())
.unwrap_or_default();
slot_history.add(self.slot());
create_account(
&slot_history,
self.inherit_specially_retained_account_fields(account),
)
});
}
fn update_slot_hashes(&self) {
self.update_sysvar_account(&sysvar::slot_hashes::id(), |account| {
let mut slot_hashes = account
.as_ref()
.map(|account| from_account::<SlotHashes, _>(account).unwrap())
.unwrap_or_default();
slot_hashes.add(self.parent_slot, self.parent_hash);
create_account(
&slot_hashes,
self.inherit_specially_retained_account_fields(account),
)
});
}
pub fn get_slot_history(&self) -> SlotHistory {
from_account(&self.get_account(&sysvar::slot_history::id()).unwrap()).unwrap()
}
fn update_epoch_stakes(&mut self, leader_schedule_epoch: Epoch) {
// update epoch_stakes cache
// if my parent didn't populate for this staker's epoch, we've
// crossed a boundary
if self.epoch_stakes.get(&leader_schedule_epoch).is_none() {
self.epoch_stakes.retain(|&epoch, _| {
epoch >= leader_schedule_epoch.saturating_sub(MAX_LEADER_SCHEDULE_STAKES)
});
let new_epoch_stakes =
EpochStakes::new(&self.stakes.read().unwrap(), leader_schedule_epoch);
{
let vote_stakes: HashMap<_, _> = self
.stakes
.read()
.unwrap()
.vote_accounts()
.iter()
.map(|(pubkey, (stake, _))| (*pubkey, *stake))
.collect();
info!(
"new epoch stakes, epoch: {}, stakes: {:#?}, total_stake: {}",
leader_schedule_epoch,
vote_stakes,
new_epoch_stakes.total_stake(),
);
}
self.epoch_stakes
.insert(leader_schedule_epoch, new_epoch_stakes);
}
}
fn update_fees(&self) {
self.update_sysvar_account(&sysvar::fees::id(), |account| {
create_account(
&sysvar::fees::Fees::new(&self.fee_calculator),
self.inherit_specially_retained_account_fields(account),
)
});
}
fn update_rent(&self) {
self.update_sysvar_account(&sysvar::rent::id(), |account| {
create_account(
&self.rent_collector.rent,
self.inherit_specially_retained_account_fields(account),
)
});
}
fn update_epoch_schedule(&self) {
self.update_sysvar_account(&sysvar::epoch_schedule::id(), |account| {
create_account(
&self.epoch_schedule,
self.inherit_specially_retained_account_fields(account),
)
});
}
fn update_stake_history(&self, epoch: Option<Epoch>) {
if epoch == Some(self.epoch()) {
return;
}
// if I'm the first Bank in an epoch, ensure stake_history is updated
self.update_sysvar_account(&sysvar::stake_history::id(), |account| {
create_account::<sysvar::stake_history::StakeHistory>(
&self.stakes.read().unwrap().history(),
self.inherit_specially_retained_account_fields(account),
)
});
}
pub fn epoch_duration_in_years(&self, prev_epoch: Epoch) -> f64 {
// period: time that has passed as a fraction of a year, basically the length of
// an epoch as a fraction of a year
// calculated as: slots_elapsed / (slots / year)
self.epoch_schedule.get_slots_in_epoch(prev_epoch) as f64 / self.slots_per_year
}
fn rewrite_stakes(&self) -> (usize, usize) {
let mut examined_count = 0;
let mut rewritten_count = 0;
self.cloned_stake_delegations()
.into_iter()
.for_each(|(stake_pubkey, _delegation)| {
examined_count += 1;
if let Some(mut stake_account) = self.get_account_with_fixed_root(&stake_pubkey) {
if let Ok(result) =
stake_state::rewrite_stakes(&mut stake_account, &self.rent_collector.rent)
{
self.store_account(&stake_pubkey, &stake_account);
let message = format!("rewrote stake: {}, {:?}", stake_pubkey, result);
info!("{}", message);
datapoint_info!("stake_info", ("info", message, String));
rewritten_count += 1;
}
}
});
info!(
"bank (slot: {}): rewrite_stakes: {} accounts rewritten / {} accounts examined",
self.slot(),
rewritten_count,
examined_count,
);
datapoint_info!(
"rewrite-stakes",
("examined_count", examined_count, i64),
("rewritten_count", rewritten_count, i64)
);
(examined_count, rewritten_count)
}
// Calculates the starting-slot for inflation from the activation slot.
// This method assumes that `pico_inflation` will be enabled before `full_inflation`, giving
// precedence to the latter. However, since `pico_inflation` is fixed-rate Inflation, should
// `pico_inflation` be enabled 2nd, the incorrect start slot provided here should have no
// effect on the inflation calculation.
fn get_inflation_start_slot(&self) -> Slot {
let mut slots = self
.feature_set
.full_inflation_features_enabled()
.iter()
.filter_map(|id| self.feature_set.activated_slot(&id))
.collect::<Vec<_>>();
slots.sort_unstable();
slots.get(0).cloned().unwrap_or_else(|| {
self.feature_set
.activated_slot(&feature_set::pico_inflation::id())
.unwrap_or(0)
})
}
fn get_inflation_num_slots(&self) -> u64 {
let inflation_activation_slot = self.get_inflation_start_slot();
// Normalize inflation_start to align with the start of rewards accrual.
let inflation_start_slot = self.epoch_schedule.get_first_slot_in_epoch(
self.epoch_schedule
.get_epoch(inflation_activation_slot)
.saturating_sub(1),
);
self.epoch_schedule.get_first_slot_in_epoch(self.epoch()) - inflation_start_slot
}
pub fn slot_in_year_for_inflation(&self) -> f64 {
let num_slots = self.get_inflation_num_slots();
// calculated as: num_slots / (slots / year)
num_slots as f64 / self.slots_per_year
}
// update rewards based on the previous epoch
fn update_rewards(
&mut self,
prev_epoch: Epoch,
reward_calc_tracer: &mut Option<impl FnMut(&RewardCalculationEvent)>,
) {
if prev_epoch == self.epoch() {
return;
}
// if I'm the first Bank in an epoch, count, claim, disburse rewards from Inflation
let slot_in_year = self.slot_in_year_for_inflation();
let epoch_duration_in_years = self.epoch_duration_in_years(prev_epoch);
let (validator_rate, foundation_rate) = {
let inflation = self.inflation.read().unwrap();
(
(*inflation).validator(slot_in_year),
(*inflation).foundation(slot_in_year),
)
};
let capitalization = self.capitalization();
let validator_rewards =
(validator_rate * capitalization as f64 * epoch_duration_in_years) as u64;
let old_vote_balance_and_staked = self.stakes.read().unwrap().vote_balance_and_staked();
let validator_point_value = self.pay_validator_rewards(
prev_epoch,
validator_rewards,
reward_calc_tracer,
self.stake_program_v2_enabled(),
);
if !self
.feature_set
.is_active(&feature_set::deprecate_rewards_sysvar::id())
{
// this sysvar can be retired once `pico_inflation` is enabled on all clusters
self.update_sysvar_account(&sysvar::rewards::id(), |account| {
create_account(
&sysvar::rewards::Rewards::new(validator_point_value),
self.inherit_specially_retained_account_fields(account),
)
});
}
let new_vote_balance_and_staked = self.stakes.read().unwrap().vote_balance_and_staked();
let validator_rewards_paid = new_vote_balance_and_staked - old_vote_balance_and_staked;
assert_eq!(
validator_rewards_paid,
u64::try_from(
self.rewards
.read()
.unwrap()
.iter()
.map(|(_address, reward_info)| {
match reward_info.reward_type {
RewardType::Voting | RewardType::Staking => reward_info.lamports,
_ => 0,
}
})
.sum::<i64>()
)
.unwrap()
);
// verify that we didn't pay any more than we expected to
assert!(validator_rewards >= validator_rewards_paid);
info!(
"distributed inflation: {} (rounded from: {})",
validator_rewards_paid, validator_rewards
);
self.capitalization
.fetch_add(validator_rewards_paid, Relaxed);
let active_stake = if let Some(stake_history_entry) =
self.stakes.read().unwrap().history().get(&prev_epoch)
{
stake_history_entry.effective
} else {
0
};
datapoint_warn!(
"epoch_rewards",
("slot", self.slot, i64),
("epoch", prev_epoch, i64),
("validator_rate", validator_rate, f64),
("foundation_rate", foundation_rate, f64),
("epoch_duration_in_years", epoch_duration_in_years, f64),
("validator_rewards", validator_rewards_paid, i64),
("active_stake", active_stake, i64),
("pre_capitalization", capitalization, i64),
("post_capitalization", self.capitalization(), i64)
);
}
/// map stake delegations into resolved (pubkey, account) pairs
/// returns a map (has to be copied) of loaded
/// ( Vec<(staker info)> (voter account) ) keyed by voter pubkey
///
/// Filters out invalid pairs
fn stake_delegation_accounts(
&self,
reward_calc_tracer: &mut Option<impl FnMut(&RewardCalculationEvent)>,
) -> HashMap<Pubkey, (Vec<(Pubkey, AccountSharedData)>, AccountSharedData)> {
let mut accounts = HashMap::new();
self.stakes
.read()
.unwrap()
.stake_delegations()
.iter()
.for_each(|(stake_pubkey, delegation)| {
match (
self.get_account_with_fixed_root(&stake_pubkey),
self.get_account_with_fixed_root(&delegation.voter_pubkey),
) {
(Some(stake_account), Some(vote_account)) => {
// call tracer to catch any illegal data if any
if let Some(reward_calc_tracer) = reward_calc_tracer {
reward_calc_tracer(&RewardCalculationEvent::Staking(
stake_pubkey,
&InflationPointCalculationEvent::Delegation(
*delegation,
*vote_account.owner(),
),
));
}
if self
.feature_set
.is_active(&feature_set::filter_stake_delegation_accounts::id())
&& (stake_account.owner() != &solana_stake_program::id()
|| vote_account.owner() != &solana_vote_program::id())
{
datapoint_warn!(
"bank-stake_delegation_accounts-invalid-account",
("slot", self.slot() as i64, i64),
("stake-address", format!("{:?}", stake_pubkey), String),
(
"vote-address",
format!("{:?}", delegation.voter_pubkey),
String
),
);
return;
}
let entry = accounts
.entry(delegation.voter_pubkey)
.or_insert((Vec::new(), vote_account));
entry.0.push((*stake_pubkey, stake_account));
}
(_, _) => {}
}
});
accounts
}
/// iterate over all stakes, redeem vote credits for each stake we can
/// successfully load and parse, return the lamport value of one point
fn pay_validator_rewards(
&mut self,
rewarded_epoch: Epoch,
rewards: u64,
reward_calc_tracer: &mut Option<impl FnMut(&RewardCalculationEvent)>,
fix_stake_deactivate: bool,
) -> f64 {
let stake_history = self.stakes.read().unwrap().history().clone();
let mut stake_delegation_accounts = self.stake_delegation_accounts(reward_calc_tracer);
let points: u128 = stake_delegation_accounts
.iter()
.flat_map(|(_vote_pubkey, (stake_group, vote_account))| {
stake_group
.iter()
.map(move |(_stake_pubkey, stake_account)| (stake_account, vote_account))
})
.map(|(stake_account, vote_account)| {
stake_state::calculate_points(
&stake_account,
&vote_account,
Some(&stake_history),
fix_stake_deactivate,
)
.unwrap_or(0)
})
.sum();
if points == 0 {
return 0.0;
}
let point_value = PointValue { rewards, points };
let mut rewards = vec![];
// pay according to point value
for (vote_pubkey, (stake_group, vote_account)) in stake_delegation_accounts.iter_mut() {
let mut vote_account_changed = false;
let voters_account_pre_balance = vote_account.lamports;
for (stake_pubkey, stake_account) in stake_group.iter_mut() {
// curry closure to add the contextual stake_pubkey
let mut reward_calc_tracer = reward_calc_tracer.as_mut().map(|outer| {
let stake_pubkey = *stake_pubkey;
// inner
move |inner_event: &_| {
outer(&RewardCalculationEvent::Staking(&stake_pubkey, inner_event))
}
});
let redeemed = stake_state::redeem_rewards(
rewarded_epoch,
stake_account,
vote_account,
&point_value,
Some(&stake_history),
&mut reward_calc_tracer.as_mut(),
fix_stake_deactivate,
);
if let Ok((stakers_reward, _voters_reward)) = redeemed {
self.store_account(&stake_pubkey, &stake_account);
vote_account_changed = true;
if stakers_reward > 0 {
rewards.push((
*stake_pubkey,
RewardInfo {
reward_type: RewardType::Staking,
lamports: stakers_reward as i64,
post_balance: stake_account.lamports,
},
));
}
} else {
debug!(
"stake_state::redeem_rewards() failed for {}: {:?}",
stake_pubkey, redeemed
);
}
}
if vote_account_changed {
let post_balance = vote_account.lamports;
let lamports = (post_balance - voters_account_pre_balance) as i64;
if lamports != 0 {
rewards.push((
*vote_pubkey,
RewardInfo {
reward_type: RewardType::Voting,
lamports,
post_balance,
},
));
}
self.store_account(&vote_pubkey, &vote_account);
}
}
self.rewards.write().unwrap().append(&mut rewards);
point_value.rewards as f64 / point_value.points as f64
}
fn update_recent_blockhashes_locked(&self, locked_blockhash_queue: &BlockhashQueue) {
self.update_sysvar_account(&sysvar::recent_blockhashes::id(), |account| {
let recent_blockhash_iter = locked_blockhash_queue.get_recent_blockhashes();
recent_blockhashes_account::create_account_with_data_and_fields(
recent_blockhash_iter,
self.inherit_specially_retained_account_fields(account),
)
});
}
pub fn update_recent_blockhashes(&self) {
let blockhash_queue = self.blockhash_queue.read().unwrap();
self.update_recent_blockhashes_locked(&blockhash_queue);
}
fn get_timestamp_estimate(
&self,
max_allowable_drift: MaxAllowableDrift,
epoch_start_timestamp: Option<(Slot, UnixTimestamp)>,
) -> Option<UnixTimestamp> {
let mut get_timestamp_estimate_time = Measure::start("get_timestamp_estimate");
let slots_per_epoch = self.epoch_schedule().slots_per_epoch;
let recent_timestamps =
self.vote_accounts()
.into_iter()
.filter_map(|(pubkey, (_, account))| {
let vote_state = account.vote_state();
let vote_state = vote_state.as_ref().ok()?;
let slot_delta = self.slot().checked_sub(vote_state.last_timestamp.slot)?;
if slot_delta <= slots_per_epoch {
Some((
pubkey,
(
vote_state.last_timestamp.slot,
vote_state.last_timestamp.timestamp,
),
))
} else {
None
}
});
let slot_duration = Duration::from_nanos(self.ns_per_slot as u64);
let epoch = self.epoch_schedule().get_epoch(self.slot());
let stakes = self.epoch_vote_accounts(epoch)?;
let stake_weighted_timestamp = calculate_stake_weighted_timestamp(
recent_timestamps,
stakes,
self.slot(),
slot_duration,
epoch_start_timestamp,
max_allowable_drift,
self.feature_set
.is_active(&feature_set::warp_timestamp_again::id()),
);
get_timestamp_estimate_time.stop();
datapoint_info!(
"bank-timestamp",
(
"get_timestamp_estimate_us",
get_timestamp_estimate_time.as_us(),
i64
),
);
stake_weighted_timestamp
}
// Distribute collected transaction fees for this slot to collector_id (= current leader).
//
// Each validator is incentivized to process more transactions to earn more transaction fees.
// Transaction fees are rewarded for the computing resource utilization cost, directly
// proportional to their actual processing power.
//
// collector_id is rotated according to stake-weighted leader schedule. So the opportunity of
// earning transaction fees are fairly distributed by stake. And missing the opportunity
// (not producing a block as a leader) earns nothing. So, being online is incentivized as a
// form of transaction fees as well.
//
// On the other hand, rent fees are distributed under slightly different philosophy, while
// still being stake-weighted.
// Ref: distribute_rent_to_validators
fn collect_fees(&self) {
let collector_fees = self.collector_fees.load(Relaxed) as u64;
if collector_fees != 0 {
let (unburned, burned) = self.fee_rate_governor.burn(collector_fees);
// burn a portion of fees
debug!(
"distributed fee: {} (rounded from: {}, burned: {})",
unburned, collector_fees, burned
);
let post_balance = self.deposit(&self.collector_id, unburned);
if unburned != 0 {
self.rewards.write().unwrap().push((
self.collector_id,
RewardInfo {
reward_type: RewardType::Fee,
lamports: unburned as i64,
post_balance,
},
));
}
self.capitalization.fetch_sub(burned, Relaxed);
}
}
pub fn rehash(&self) {
let mut hash = self.hash.write().unwrap();
let new = self.hash_internal_state();
if new != *hash {
warn!("Updating bank hash to {}", new);
*hash = new;
}
}
pub fn freeze(&self) {
// This lock prevents any new commits from BankingStage
// `process_and_record_transactions_locked()` from coming
// in after the last tick is observed. This is because in
// BankingStage, any transaction successfully recorded in
// `record_transactions()` is recorded after this `hash` lock
// is grabbed. At the time of the successful record,
// this means the PoH has not yet reached the last tick,
// so this means freeze() hasn't been called yet. And because
// BankingStage doesn't release this hash lock until both
// record and commit are finished, those transactions will be
// committed before this write lock can be obtained here.
let mut hash = self.hash.write().unwrap();
if *hash == Hash::default() {
// finish up any deferred changes to account state
self.collect_rent_eagerly();
self.collect_fees();
self.distribute_rent();
self.update_slot_history();
self.run_incinerator();
// freeze is a one-way trip, idempotent
self.freeze_started.store(true, Relaxed);
*hash = self.hash_internal_state();
self.rc.accounts.accounts_db.mark_slot_frozen(self.slot());
}
}
// Should not be called outside of startup, will race with
// concurrent cleaning logic in AccountsBackgroundService
pub fn exhaustively_free_unused_resource(&self) {
let mut flush = Measure::start("flush");
// Flush all the rooted accounts. Must be called after `squash()`,
// so that AccountsDb knows what the roots are.
self.force_flush_accounts_cache();
flush.stop();
let mut clean = Measure::start("clean");
// Don't clean the slot we're snapshotting because it may have zero-lamport
// accounts that were included in the bank delta hash when the bank was frozen,
// and if we clean them here, any newly created snapshot's hash for this bank
// may not match the frozen hash.
self.clean_accounts(true);
clean.stop();
let mut shrink = Measure::start("shrink");
self.shrink_all_slots();
shrink.stop();
info!(
"exhaustively_free_unused_resource() {} {} {}",
flush, clean, shrink,
);
}
pub fn epoch_schedule(&self) -> &EpochSchedule {
&self.epoch_schedule
}
/// squash the parent's state up into this Bank,
/// this Bank becomes a root
pub fn squash(&self) {
self.freeze();
//this bank and all its parents are now on the rooted path
let mut roots = vec![self.slot()];
roots.append(&mut self.parents().iter().map(|p| p.slot()).collect());
let mut squash_accounts_time = Measure::start("squash_accounts_time");
for slot in roots.iter().rev() {
// root forks cannot be purged
self.rc.accounts.add_root(*slot);
}
squash_accounts_time.stop();
*self.rc.parent.write().unwrap() = None;
let mut squash_cache_time = Measure::start("squash_cache_time");
roots
.iter()
.for_each(|slot| self.src.status_cache.write().unwrap().add_root(*slot));
squash_cache_time.stop();
datapoint_debug!(
"tower-observed",
("squash_accounts_ms", squash_accounts_time.as_ms(), i64),
("squash_cache_ms", squash_cache_time.as_ms(), i64)
);
}
/// Return the more recent checkpoint of this bank instance.
pub fn parent(&self) -> Option<Arc<Bank>> {
self.rc.parent.read().unwrap().clone()
}
pub fn parent_slot(&self) -> Slot {
self.parent_slot
}
pub fn parent_hash(&self) -> Hash {
self.parent_hash
}
fn process_genesis_config(&mut self, genesis_config: &GenesisConfig) {
// Bootstrap validator collects fees until `new_from_parent` is called.
self.fee_rate_governor = genesis_config.fee_rate_governor.clone();
self.fee_calculator = self.fee_rate_governor.create_fee_calculator();
for (pubkey, account) in genesis_config.accounts.iter() {
if self.get_account(&pubkey).is_some() {
panic!("{} repeated in genesis config", pubkey);
}
self.store_account(pubkey, &AccountSharedData::from(account.clone()));
self.capitalization.fetch_add(account.lamports, Relaxed);
}
// updating sysvars (the fees sysvar in this case) now depends on feature activations in
// genesis_config.accounts above
self.update_fees();
for (pubkey, account) in genesis_config.rewards_pools.iter() {
if self.get_account(&pubkey).is_some() {
panic!("{} repeated in genesis config", pubkey);
}
self.store_account(pubkey, &AccountSharedData::from(account.clone()));
}
// highest staked node is the first collector
self.collector_id = self
.stakes
.read()
.unwrap()
.highest_staked_node()
.unwrap_or_default();
self.blockhash_queue
.write()
.unwrap()
.genesis_hash(&genesis_config.hash(), &self.fee_calculator);
self.hashes_per_tick = genesis_config.hashes_per_tick();
self.ticks_per_slot = genesis_config.ticks_per_slot();
self.ns_per_slot = genesis_config.ns_per_slot();
self.genesis_creation_time = genesis_config.creation_time;
self.unused = genesis_config.unused;
self.max_tick_height = (self.slot + 1) * self.ticks_per_slot;
self.slots_per_year = genesis_config.slots_per_year();
self.epoch_schedule = genesis_config.epoch_schedule;
self.inflation = Arc::new(RwLock::new(genesis_config.inflation));
self.rent_collector = RentCollector::new(
self.epoch,
&self.epoch_schedule,
self.slots_per_year,
&genesis_config.rent,
);
// Add additional native programs specified in the genesis config
for (name, program_id) in &genesis_config.native_instruction_processors {
self.add_native_program(name, program_id, false);
}
}
// NOTE: must hold idempotent for the same set of arguments
pub fn add_native_program(&self, name: &str, program_id: &Pubkey, must_replace: bool) {
let existing_genuine_program =
if let Some(mut account) = self.get_account_with_fixed_root(&program_id) {
// it's very unlikely to be squatted at program_id as non-system account because of burden to
// find victim's pubkey/hash. So, when account.owner is indeed native_loader's, it's
// safe to assume it's a genuine program.
if native_loader::check_id(&account.owner()) {
Some(account)
} else {
// malicious account is pre-occupying at program_id
// forcibly burn and purge it
self.capitalization.fetch_sub(account.lamports, Relaxed);
// Resetting account balance to 0 is needed to really purge from AccountsDb and
// flush the Stakes cache
account.set_lamports(0);
self.store_account(&program_id, &account);
None
}
} else {
None
};
if must_replace {
// updating native program
match &existing_genuine_program {
None => panic!(
"There is no account to replace with native program ({}, {}).",
name, program_id
),
Some(account) => {
if *name == String::from_utf8_lossy(&account.data()) {
// nop; it seems that already AccountsDb is updated.
return;
}
// continue to replace account
}
}
} else {
// introducing native program
match &existing_genuine_program {
None => (), // continue to add account
Some(_account) => {
// nop; it seems that we already have account
// before returning here to retain idempotent just make sure
// the existing native program name is same with what we're
// supposed to add here (but skipping) But I can't:
// following assertion already catches several different names for same
// program_id
// depending on clusters...
// assert_eq!(name.to_owned(), String::from_utf8_lossy(&account.data));
return;
}
}
}
assert!(
!self.freeze_started(),
"Can't change frozen bank by adding not-existing new native program ({}, {}). \
Maybe, inconsistent program activation is detected on snapshot restore?",
name,
program_id
);
// Add a bogus executable native account, which will be loaded and ignored.
let account = native_loader::create_loadable_account_with_fields(
name,
self.inherit_specially_retained_account_fields(&existing_genuine_program),
);
self.store_account_and_update_capitalization(&program_id, &account);
debug!("Added native program {} under {:?}", name, program_id);
}
pub fn set_rent_burn_percentage(&mut self, burn_percent: u8) {
self.rent_collector.rent.burn_percent = burn_percent;
}
pub fn set_hashes_per_tick(&mut self, hashes_per_tick: Option<u64>) {
self.hashes_per_tick = hashes_per_tick;
}
/// Return the last block hash registered.
pub fn last_blockhash(&self) -> Hash {
self.blockhash_queue.read().unwrap().last_hash()
}
pub fn get_minimum_balance_for_rent_exemption(&self, data_len: usize) -> u64 {
self.rent_collector.rent.minimum_balance(data_len)
}
pub fn last_blockhash_with_fee_calculator(&self) -> (Hash, FeeCalculator) {
let blockhash_queue = self.blockhash_queue.read().unwrap();
let last_hash = blockhash_queue.last_hash();
(
last_hash,
blockhash_queue
.get_fee_calculator(&last_hash)
.unwrap()
.clone(),
)
}
pub fn get_fee_calculator(&self, hash: &Hash) -> Option<FeeCalculator> {
let blockhash_queue = self.blockhash_queue.read().unwrap();
blockhash_queue.get_fee_calculator(hash).cloned()
}
pub fn get_fee_rate_governor(&self) -> &FeeRateGovernor {
&self.fee_rate_governor
}
pub fn get_blockhash_last_valid_slot(&self, blockhash: &Hash) -> Option<Slot> {
let blockhash_queue = self.blockhash_queue.read().unwrap();
// This calculation will need to be updated to consider epoch boundaries if BlockhashQueue
// length is made variable by epoch
blockhash_queue
.get_hash_age(blockhash)
.map(|age| self.slot + blockhash_queue.len() as u64 - age)
}
pub fn confirmed_last_blockhash(&self) -> (Hash, FeeCalculator) {
const NUM_BLOCKHASH_CONFIRMATIONS: usize = 3;
let parents = self.parents();
if parents.is_empty() {
self.last_blockhash_with_fee_calculator()
} else {
let index = NUM_BLOCKHASH_CONFIRMATIONS.min(parents.len() - 1);
parents[index].last_blockhash_with_fee_calculator()
}
}
/// Forget all signatures. Useful for benchmarking.
pub fn clear_signatures(&self) {
self.src.status_cache.write().unwrap().clear();
}
pub fn clear_slot_signatures(&self, slot: Slot) {
self.src
.status_cache
.write()
.unwrap()
.clear_slot_entries(slot);
}
pub fn can_commit(result: &Result<()>) -> bool {
match result {
Ok(_) => true,
Err(TransactionError::InstructionError(_, _)) => true,
Err(_) => false,
}
}
fn update_transaction_statuses(
&self,
hashed_txs: &[HashedTransaction],
res: &[TransactionExecutionResult],
) {
let mut status_cache = self.src.status_cache.write().unwrap();
assert_eq!(hashed_txs.len(), res.len());
for (hashed_tx, (res, _nonce_rollback)) in hashed_txs.iter().zip(res) {
let tx = hashed_tx.transaction();
if Self::can_commit(res) && !tx.signatures.is_empty() {
status_cache.insert(
&tx.message().recent_blockhash,
&tx.signatures[0],
self.slot(),
res.clone(),
);
status_cache.insert(
&tx.message().recent_blockhash,
&hashed_tx.message_hash,
self.slot(),
res.clone(),
);
}
}
}
/// Tell the bank which Entry IDs exist on the ledger. This function
/// assumes subsequent calls correspond to later entries, and will boot
/// the oldest ones once its internal cache is full. Once boot, the
/// bank will reject transactions using that `hash`.
pub fn register_tick(&self, hash: &Hash) {
assert!(
!self.freeze_started(),
"register_tick() working on a bank that is already frozen or is undergoing freezing!"
);
inc_new_counter_debug!("bank-register_tick-registered", 1);
let mut w_blockhash_queue = self.blockhash_queue.write().unwrap();
if self.is_block_boundary(self.tick_height.load(Relaxed) + 1) {
w_blockhash_queue.register_hash(hash, &self.fee_calculator);
if self.fix_recent_blockhashes_sysvar_delay() {
self.update_recent_blockhashes_locked(&w_blockhash_queue);
}
}
// ReplayStage will start computing the accounts delta hash when it
// detects the tick height has reached the boundary, so the system
// needs to guarantee all account updates for the slot have been
// committed before this tick height is incremented (like the blockhash
// sysvar above)
self.tick_height.fetch_add(1, Relaxed);
}
pub fn is_complete(&self) -> bool {
self.tick_height() == self.max_tick_height()
}
pub fn is_block_boundary(&self, tick_height: u64) -> bool {
tick_height % self.ticks_per_slot == 0
}
pub fn demote_sysvar_write_locks(&self) -> bool {
self.feature_set
.is_active(&feature_set::demote_sysvar_write_locks::id())
}
pub fn prepare_batch<'a, 'b>(
&'a self,
txs: impl Iterator<Item = &'b Transaction>,
) -> TransactionBatch<'a, 'b> {
let hashed_txs: Vec<HashedTransaction> = txs.map(HashedTransaction::from).collect();
let lock_results = self.rc.accounts.lock_accounts(
hashed_txs.as_transactions_iter(),
self.demote_sysvar_write_locks(),
);
TransactionBatch::new(lock_results, &self, Cow::Owned(hashed_txs))
}
pub fn prepare_hashed_batch<'a, 'b>(
&'a self,
hashed_txs: &'b [HashedTransaction],
) -> TransactionBatch<'a, 'b> {
let lock_results = self.rc.accounts.lock_accounts(
hashed_txs.as_transactions_iter(),
self.demote_sysvar_write_locks(),
);
TransactionBatch::new(lock_results, &self, Cow::Borrowed(hashed_txs))
}
pub fn prepare_simulation_batch<'a, 'b>(
&'a self,
txs: &'b [Transaction],
) -> TransactionBatch<'a, 'b> {
let lock_results: Vec<_> = txs
.iter()
.map(|tx| tx.sanitize().map_err(|e| e.into()))
.collect();
let hashed_txs = txs.iter().map(HashedTransaction::from).collect();
let mut batch = TransactionBatch::new(lock_results, &self, hashed_txs);
batch.needs_unlock = false;
batch
}
/// Run transactions against a frozen bank without committing the results
pub fn simulate_transaction(
&self,
transaction: Transaction,
) -> (Result<()>, TransactionLogMessages) {
assert!(self.is_frozen(), "simulation bank must be frozen");
let txs = &[transaction];
let batch = self.prepare_simulation_batch(txs);
let mut timings = ExecuteTimings::default();
let (
_loaded_accounts,
executed,
_inner_instructions,
log_messages,
_retryable_transactions,
_transaction_count,
_signature_count,
) = self.load_and_execute_transactions(
&batch,
// After simulation, transactions will need to be forwarded to the leader
// for processing. During forwarding, the transaction could expire if the
// delay is not accounted for.
MAX_PROCESSING_AGE - MAX_TRANSACTION_FORWARDING_DELAY,
false,
true,
&mut timings,
);
let transaction_result = executed[0].0.clone().map(|_| ());
let log_messages = log_messages
.get(0)
.map_or(vec![], |messages| messages.to_vec());
debug!("simulate_transaction: {:?}", timings);
(transaction_result, log_messages)
}
pub fn unlock_accounts(&self, batch: &mut TransactionBatch) {
if batch.needs_unlock {
batch.needs_unlock = false;
self.rc.accounts.unlock_accounts(
batch.transactions_iter(),
batch.lock_results(),
self.demote_sysvar_write_locks(),
)
}
}
pub fn remove_unrooted_slot(&self, slot: Slot) {
self.rc.accounts.accounts_db.remove_unrooted_slot(slot)
}
pub fn set_shrink_paths(&self, paths: Vec<PathBuf>) {
self.rc.accounts.accounts_db.set_shrink_paths(paths);
}
fn check_age<'a>(
&self,
txs: impl Iterator<Item = &'a Transaction>,
lock_results: Vec<Result<()>>,
max_age: usize,
error_counters: &mut ErrorCounters,
) -> Vec<TransactionCheckResult> {
let hash_queue = self.blockhash_queue.read().unwrap();
txs.zip(lock_results)
.map(|(tx, lock_res)| match lock_res {
Ok(()) => {
let message = tx.message();
let hash_age = hash_queue.check_hash_age(&message.recent_blockhash, max_age);
if hash_age == Some(true) {
(Ok(()), None)
} else if let Some((pubkey, acc)) = self.check_tx_durable_nonce(&tx) {
(Ok(()), Some(NonceRollbackPartial::new(pubkey, acc)))
} else if hash_age == Some(false) {
error_counters.blockhash_too_old += 1;
(Err(TransactionError::BlockhashNotFound), None)
} else {
error_counters.blockhash_not_found += 1;
(Err(TransactionError::BlockhashNotFound), None)
}
}
Err(e) => (Err(e), None),
})
.collect()
}
fn is_tx_already_processed(
&self,
hashed_tx: &HashedTransaction,
status_cache: &StatusCache<Result<()>>,
check_duplicates_by_hash_enabled: bool,
) -> bool {
let tx = hashed_tx.transaction();
let status_cache_key: Option<&[u8]> = if check_duplicates_by_hash_enabled {
Some(hashed_tx.message_hash.as_ref())
} else {
tx.signatures.get(0).map(|sig0| sig0.as_ref())
};
status_cache_key
.and_then(|key| {
status_cache.get_status(key, &tx.message().recent_blockhash, &self.ancestors)
})
.is_some()
}
fn check_status_cache(
&self,
hashed_txs: &[HashedTransaction],
lock_results: Vec<TransactionCheckResult>,
error_counters: &mut ErrorCounters,
) -> Vec<TransactionCheckResult> {
let rcache = self.src.status_cache.read().unwrap();
let check_duplicates_by_hash_enabled = self.check_duplicates_by_hash_enabled();
hashed_txs
.iter()
.zip(lock_results)
.map(|(hashed_tx, (lock_res, nonce_rollback))| {
if lock_res.is_ok()
&& self.is_tx_already_processed(
hashed_tx,
&rcache,
check_duplicates_by_hash_enabled,
)
{
error_counters.already_processed += 1;
return (Err(TransactionError::AlreadyProcessed), None);
}
(lock_res, nonce_rollback)
})
.collect()
}
fn filter_by_vote_transactions<'a>(
&self,
txs: impl Iterator<Item = &'a Transaction>,
lock_results: Vec<TransactionCheckResult>,
error_counters: &mut ErrorCounters,
) -> Vec<TransactionCheckResult> {
txs.zip(lock_results)
.map(|(tx, lock_res)| {
if lock_res.0.is_ok() {
if is_simple_vote_transaction(tx) {
return lock_res;
}
error_counters.not_allowed_during_cluster_maintenance += 1;
return (Err(TransactionError::ClusterMaintenance), lock_res.1);
}
lock_res
})
.collect()
}
pub fn check_hash_age(&self, hash: &Hash, max_age: usize) -> Option<bool> {
self.blockhash_queue
.read()
.unwrap()
.check_hash_age(hash, max_age)
}
pub fn check_tx_durable_nonce(&self, tx: &Transaction) -> Option<(Pubkey, AccountSharedData)> {
transaction::uses_durable_nonce(&tx)
.and_then(|nonce_ix| transaction::get_nonce_pubkey_from_instruction(&nonce_ix, &tx))
.and_then(|nonce_pubkey| {
self.get_account(&nonce_pubkey)
.map(|acc| (*nonce_pubkey, acc))
})
.filter(|(_pubkey, nonce_account)| {
nonce_account::verify_nonce_account(nonce_account, &tx.message().recent_blockhash)
})
}
// Determine if the bank is currently in an upgrade epoch, where only votes are permitted
fn upgrade_epoch(&self) -> bool {
match self.cluster_type() {
#[cfg(test)]
ClusterType::Development => self.epoch == 0xdead, // Value assumed by `test_upgrade_epoch()`
#[cfg(not(test))]
ClusterType::Development => false,
ClusterType::Devnet => false,
ClusterType::Testnet => false,
ClusterType::MainnetBeta => self.epoch == 61,
}
}
pub fn check_transactions(
&self,
hashed_txs: &[HashedTransaction],
lock_results: &[Result<()>],
max_age: usize,
mut error_counters: &mut ErrorCounters,
) -> Vec<TransactionCheckResult> {
let age_results = self.check_age(
hashed_txs.as_transactions_iter(),
lock_results.to_vec(),
max_age,
&mut error_counters,
);
let cache_results = self.check_status_cache(hashed_txs, age_results, &mut error_counters);
if self.upgrade_epoch() {
// Reject all non-vote transactions
self.filter_by_vote_transactions(
hashed_txs.as_transactions_iter(),
cache_results,
&mut error_counters,
)
} else {
cache_results
}
}
pub fn collect_balances(&self, batch: &TransactionBatch) -> TransactionBalances {
let mut balances: TransactionBalances = vec![];
for transaction in batch.transactions_iter() {
let mut transaction_balances: Vec<u64> = vec![];
for account_key in transaction.message.account_keys.iter() {
transaction_balances.push(self.get_balance(account_key));
}
balances.push(transaction_balances);
}
balances
}
#[allow(clippy::cognitive_complexity)]
fn update_error_counters(error_counters: &ErrorCounters) {
if 0 != error_counters.total {
inc_new_counter_info!(
"bank-process_transactions-error_count",
error_counters.total
);
}
if 0 != error_counters.account_not_found {
inc_new_counter_info!(
"bank-process_transactions-account_not_found",
error_counters.account_not_found
);
}
if 0 != error_counters.account_in_use {
inc_new_counter_info!(
"bank-process_transactions-account_in_use",
error_counters.account_in_use
);
}
if 0 != error_counters.account_loaded_twice {
inc_new_counter_info!(
"bank-process_transactions-account_loaded_twice",
error_counters.account_loaded_twice
);
}
if 0 != error_counters.blockhash_not_found {
inc_new_counter_info!(
"bank-process_transactions-error-blockhash_not_found",
error_counters.blockhash_not_found
);
}
if 0 != error_counters.blockhash_too_old {
inc_new_counter_info!(
"bank-process_transactions-error-blockhash_too_old",
error_counters.blockhash_too_old
);
}
if 0 != error_counters.invalid_account_index {
inc_new_counter_info!(
"bank-process_transactions-error-invalid_account_index",
error_counters.invalid_account_index
);
}
if 0 != error_counters.invalid_account_for_fee {
inc_new_counter_info!(
"bank-process_transactions-error-invalid_account_for_fee",
error_counters.invalid_account_for_fee
);
}
if 0 != error_counters.insufficient_funds {
inc_new_counter_info!(
"bank-process_transactions-error-insufficient_funds",
error_counters.insufficient_funds
);
}
if 0 != error_counters.instruction_error {
inc_new_counter_info!(
"bank-process_transactions-error-instruction_error",
error_counters.instruction_error
);
}
if 0 != error_counters.already_processed {
inc_new_counter_info!(
"bank-process_transactions-error-already_processed",
error_counters.already_processed
);
}
if 0 != error_counters.not_allowed_during_cluster_maintenance {
inc_new_counter_info!(
"bank-process_transactions-error-cluster-maintenance",
error_counters.not_allowed_during_cluster_maintenance
);
}
}
/// Converts Accounts into RefCell<AccountSharedData>, this involves moving
/// ownership by draining the source
fn accounts_to_refcells(
accounts: &mut TransactionAccounts,
account_deps: &mut TransactionAccountDeps,
loaders: &mut TransactionLoaders,
) -> (
TransactionAccountRefCells,
TransactionAccountDepRefCells,
TransactionLoaderRefCells,
) {
let account_refcells: Vec<_> = accounts
.drain(..)
.map(|account| Rc::new(RefCell::new(account)))
.collect();
let account_dep_refcells: Vec<_> = account_deps
.drain(..)
.map(|(pubkey, account_dep)| (pubkey, Rc::new(RefCell::new(account_dep))))
.collect();
let loader_refcells: Vec<Vec<_>> = loaders
.iter_mut()
.map(|v| {
v.drain(..)
.map(|(pubkey, account)| (pubkey, Rc::new(RefCell::new(account))))
.collect()
})
.collect();
(account_refcells, account_dep_refcells, loader_refcells)
}
/// Converts back from RefCell<AccountSharedData> to AccountSharedData, this involves moving
/// ownership by draining the sources
fn refcells_to_accounts(
accounts: &mut TransactionAccounts,
loaders: &mut TransactionLoaders,
mut account_refcells: TransactionAccountRefCells,
loader_refcells: TransactionLoaderRefCells,
) -> std::result::Result<(), TransactionError> {
for account_refcell in account_refcells.drain(..) {
accounts.push(
Rc::try_unwrap(account_refcell)
.map_err(|_| TransactionError::AccountBorrowOutstanding)?
.into_inner(),
)
}
for (ls, mut lrcs) in loaders.iter_mut().zip(loader_refcells) {
for (pubkey, lrc) in lrcs.drain(..) {
ls.push((
pubkey,
Rc::try_unwrap(lrc)
.map_err(|_| TransactionError::AccountBorrowOutstanding)?
.into_inner(),
))
}
}
Ok(())
}
fn compile_recorded_instructions(
inner_instructions: &mut Vec<Option<InnerInstructionsList>>,
instruction_recorders: Option<Vec<InstructionRecorder>>,
message: &Message,
) {
inner_instructions.push(instruction_recorders.map(|instruction_recorders| {
instruction_recorders
.into_iter()
.map(|r| r.compile_instructions(message))
.collect()
}));
}
/// Get any cached executors needed by the transaction
fn get_executors(
&self,
message: &Message,
loaders: &[Vec<(Pubkey, AccountSharedData)>],
) -> Rc<RefCell<Executors>> {
let mut num_executors = message.account_keys.len();
for instruction_loaders in loaders.iter() {
num_executors += instruction_loaders.len();
}
let mut executors = HashMap::with_capacity(num_executors);
let cow_cache = self.cached_executors.read().unwrap();
let cache = cow_cache.read().unwrap();
for key in message.account_keys.iter() {
if let Some(executor) = cache.get(key) {
executors.insert(*key, executor);
}
}
for instruction_loaders in loaders.iter() {
for (key, _) in instruction_loaders.iter() {
if let Some(executor) = cache.get(key) {
executors.insert(*key, executor);
}
}
}
Rc::new(RefCell::new(Executors {
executors,
is_dirty: false,
}))
}
/// Add executors back to the bank's cache if modified
fn update_executors(&self, executors: Rc<RefCell<Executors>>) {
let executors = executors.borrow();
if executors.is_dirty {
let mut cow_cache = self.cached_executors.write().unwrap();
let mut cache = cow_cache.write().unwrap();
for (key, executor) in executors.executors.iter() {
cache.put(key, (*executor).clone());
}
}
}
/// Remove an executor from the bank's cache
pub fn remove_executor(&self, pubkey: &Pubkey) {
let mut cow_cache = self.cached_executors.write().unwrap();
let mut cache = cow_cache.write().unwrap();
cache.remove(pubkey);
}
#[allow(clippy::type_complexity)]
pub fn load_and_execute_transactions(
&self,
batch: &TransactionBatch,
max_age: usize,
enable_cpi_recording: bool,
enable_log_recording: bool,
timings: &mut ExecuteTimings,
) -> (
Vec<TransactionLoadResult>,
Vec<TransactionExecutionResult>,
Vec<Option<InnerInstructionsList>>,
Vec<TransactionLogMessages>,
Vec<usize>,
u64,
u64,
) {
let hashed_txs = batch.hashed_transactions();
debug!("processing transactions: {}", hashed_txs.len());
inc_new_counter_info!("bank-process_transactions", hashed_txs.len());
let mut error_counters = ErrorCounters::default();
let retryable_txs: Vec<_> = batch
.lock_results()
.iter()
.enumerate()
.filter_map(|(index, res)| match res {
Err(TransactionError::AccountInUse) => {
error_counters.account_in_use += 1;
Some(index)
}
Err(_) => None,
Ok(_) => None,
})
.collect();
let mut check_time = Measure::start("check_transactions");
let check_results = self.check_transactions(
hashed_txs,
batch.lock_results(),
max_age,
&mut error_counters,
);
check_time.stop();
let mut load_time = Measure::start("accounts_load");
let mut loaded_accounts = self.rc.accounts.load_accounts(
&self.ancestors,
hashed_txs.as_transactions_iter(),
check_results,
&self.blockhash_queue.read().unwrap(),
&mut error_counters,
&self.rent_collector,
&self.feature_set,
);
load_time.stop();
let mut execution_time = Measure::start("execution_time");
let mut signature_count: u64 = 0;
let mut inner_instructions: Vec<Option<InnerInstructionsList>> =
Vec::with_capacity(hashed_txs.len());
let mut transaction_log_messages = Vec::with_capacity(hashed_txs.len());
let bpf_compute_budget = self
.bpf_compute_budget
.unwrap_or_else(BpfComputeBudget::new);
let executed: Vec<TransactionExecutionResult> = loaded_accounts
.iter_mut()
.zip(hashed_txs.as_transactions_iter())
.map(|(accs, tx)| match accs {
(Err(e), _nonce_rollback) => (Err(e.clone()), None),
(Ok(loaded_transaction), nonce_rollback) => {
signature_count += u64::from(tx.message().header.num_required_signatures);
let executors = self.get_executors(&tx.message, &loaded_transaction.loaders);
let (account_refcells, account_dep_refcells, loader_refcells) =
Self::accounts_to_refcells(
&mut loaded_transaction.accounts,
&mut loaded_transaction.account_deps,
&mut loaded_transaction.loaders,
);
let instruction_recorders = if enable_cpi_recording {
let ix_count = tx.message.instructions.len();
let mut recorders = Vec::with_capacity(ix_count);
recorders.resize_with(ix_count, InstructionRecorder::default);
Some(recorders)
} else {
None
};
let log_collector = if enable_log_recording {
Some(Rc::new(LogCollector::default()))
} else {
None
};
let mut process_result = self.message_processor.process_message(
tx.message(),
&loader_refcells,
&account_refcells,
&account_dep_refcells,
&self.rent_collector,
log_collector.clone(),
executors.clone(),
instruction_recorders.as_deref(),
self.feature_set.clone(),
bpf_compute_budget,
&mut timings.details,
self.rc.accounts.clone(),
&self.ancestors,
);
if enable_log_recording {
let log_messages: TransactionLogMessages =
Rc::try_unwrap(log_collector.unwrap_or_default())
.unwrap_or_default()
.into();
transaction_log_messages.push(log_messages);
}
Self::compile_recorded_instructions(
&mut inner_instructions,
instruction_recorders,
&tx.message,
);
if let Err(e) = Self::refcells_to_accounts(
&mut loaded_transaction.accounts,
&mut loaded_transaction.loaders,
account_refcells,
loader_refcells,
) {
warn!("Account lifetime mismanagement");
process_result = Err(e);
}
if process_result.is_ok() {
self.update_executors(executors);
}
let nonce_rollback =
if let Err(TransactionError::InstructionError(_, _)) = &process_result {
error_counters.instruction_error += 1;
nonce_rollback.clone()
} else if process_result.is_err() {
None
} else {
nonce_rollback.clone()
};
(process_result, nonce_rollback)
}
})
.collect();
execution_time.stop();
debug!(
"check: {}us load: {}us execute: {}us txs_len={}",
check_time.as_us(),
load_time.as_us(),
execution_time.as_us(),
hashed_txs.len(),
);
timings.check_us += check_time.as_us();
timings.load_us += load_time.as_us();
timings.execute_us += execution_time.as_us();
let mut tx_count: u64 = 0;
let err_count = &mut error_counters.total;
let transaction_log_collector_config =
self.transaction_log_collector_config.read().unwrap();
for (i, ((r, _nonce_rollback), hashed_tx)) in executed.iter().zip(hashed_txs).enumerate() {
let tx = hashed_tx.transaction();
if let Some(debug_keys) = &self.transaction_debug_keys {
for key in &tx.message.account_keys {
if debug_keys.contains(key) {
info!("slot: {} result: {:?} tx: {:?}", self.slot, r, tx);
break;
}
}
}
if Self::can_commit(r) // Skip log collection for unprocessed transactions
&& transaction_log_collector_config.filter != TransactionLogCollectorFilter::None
{
let mut transaction_log_collector = self.transaction_log_collector.write().unwrap();
let transaction_log_index = transaction_log_collector.logs.len();
let mut mentioned_address = false;
if !transaction_log_collector_config
.mentioned_addresses
.is_empty()
{
for key in &tx.message.account_keys {
if transaction_log_collector_config
.mentioned_addresses
.contains(key)
{
transaction_log_collector
.mentioned_address_map
.entry(*key)
.or_default()
.push(transaction_log_index);
mentioned_address = true;
}
}
}
let is_vote = is_simple_vote_transaction(tx);
let store = match transaction_log_collector_config.filter {
TransactionLogCollectorFilter::All => !is_vote || mentioned_address,
TransactionLogCollectorFilter::AllWithVotes => true,
TransactionLogCollectorFilter::None => false,
TransactionLogCollectorFilter::OnlyMentionedAddresses => mentioned_address,
};
if store {
transaction_log_collector.logs.push(TransactionLogInfo {
signature: tx.signatures[0],
result: r.clone(),
is_vote,
log_messages: transaction_log_messages.get(i).cloned().unwrap_or_default(),
});
}
}
if r.is_ok() {
tx_count += 1;
} else {
if *err_count == 0 {
debug!("tx error: {:?} {:?}", r, tx);
}
*err_count += 1;
}
}
if *err_count > 0 {
debug!(
"{} errors of {} txs",
*err_count,
*err_count as u64 + tx_count
);
}
Self::update_error_counters(&error_counters);
(
loaded_accounts,
executed,
inner_instructions,
transaction_log_messages,
retryable_txs,
tx_count,
signature_count,
)
}
fn filter_program_errors_and_collect_fee<'a>(
&self,
txs: impl Iterator<Item = &'a Transaction>,
executed: &[TransactionExecutionResult],
) -> Vec<Result<()>> {
let hash_queue = self.blockhash_queue.read().unwrap();
let mut fees = 0;
let fee_config = FeeConfig {
secp256k1_program_enabled: self.secp256k1_program_enabled(),
};
let results = txs
.zip(executed)
.map(|(tx, (res, nonce_rollback))| {
let (fee_calculator, is_durable_nonce) = nonce_rollback
.as_ref()
.map(|nonce_rollback| nonce_rollback.fee_calculator())
.map(|maybe_fee_calculator| (maybe_fee_calculator, true))
.unwrap_or_else(|| {
(
hash_queue
.get_fee_calculator(&tx.message().recent_blockhash)
.cloned(),
false,
)
});
let fee_calculator = fee_calculator.ok_or(TransactionError::BlockhashNotFound)?;
let fee = fee_calculator.calculate_fee_with_config(tx.message(), &fee_config);
let message = tx.message();
match *res {
Err(TransactionError::InstructionError(_, _)) => {
// credit the transaction fee even in case of InstructionError
// necessary to withdraw from account[0] here because previous
// work of doing so (in accounts.load()) is ignored by store_account()
//
// ...except nonce accounts, which will have their post-load,
// pre-execute account state stored
if !is_durable_nonce {
self.withdraw(&message.account_keys[0], fee)?;
}
fees += fee;
Ok(())
}
Ok(()) => {
fees += fee;
Ok(())
}
_ => res.clone(),
}
})
.collect();
self.collector_fees.fetch_add(fees, Relaxed);
results
}
pub fn commit_transactions(
&self,
hashed_txs: &[HashedTransaction],
loaded_accounts: &mut [TransactionLoadResult],
executed: &[TransactionExecutionResult],
tx_count: u64,
signature_count: u64,
timings: &mut ExecuteTimings,
) -> TransactionResults {
assert!(
!self.freeze_started(),
"commit_transactions() working on a bank that is already frozen or is undergoing freezing!"
);
self.increment_transaction_count(tx_count);
self.increment_signature_count(signature_count);
inc_new_counter_info!("bank-process_transactions-txs", tx_count as usize);
inc_new_counter_info!("bank-process_transactions-sigs", signature_count as usize);
if !hashed_txs.is_empty() {
let processed_tx_count = hashed_txs.len() as u64;
let failed_tx_count = processed_tx_count.saturating_sub(tx_count);
self.transaction_error_count
.fetch_add(failed_tx_count, Relaxed);
self.transaction_entries_count.fetch_add(1, Relaxed);
self.transactions_per_entry_max
.fetch_max(processed_tx_count, Relaxed);
}
if executed
.iter()
.any(|(res, _nonce_rollback)| Self::can_commit(res))
{
self.is_delta.store(true, Relaxed);
}
let mut write_time = Measure::start("write_time");
self.rc.accounts.store_cached(
self.slot(),
hashed_txs.as_transactions_iter(),
executed,
loaded_accounts,
&self.rent_collector,
&self.last_blockhash_with_fee_calculator(),
self.fix_recent_blockhashes_sysvar_delay(),
self.demote_sysvar_write_locks(),
);
self.collect_rent(executed, loaded_accounts);
let overwritten_vote_accounts = self.update_cached_accounts(
hashed_txs.as_transactions_iter(),
executed,
loaded_accounts,
);
// once committed there is no way to unroll
write_time.stop();
debug!(
"store: {}us txs_len={}",
write_time.as_us(),
hashed_txs.len()
);
timings.store_us += write_time.as_us();
self.update_transaction_statuses(hashed_txs, &executed);
let fee_collection_results =
self.filter_program_errors_and_collect_fee(hashed_txs.as_transactions_iter(), executed);
TransactionResults {
fee_collection_results,
execution_results: executed.to_vec(),
overwritten_vote_accounts,
}
}
// Distribute collected rent fees for this slot to staked validators (excluding stakers)
// according to stake.
//
// The nature of rent fee is the cost of doing business, every validator has to hold (or have
// access to) the same list of accounts, so we pay according to stake, which is a rough proxy for
// value to the network.
//
// Currently, rent distribution doesn't consider given validator's uptime at all (this might
// change). That's because rent should be rewarded for the storage resource utilization cost.
// It's treated differently from transaction fees, which is for the computing resource
// utilization cost.
//
// We can't use collector_id (which is rotated according to stake-weighted leader schedule)
// as an approximation to the ideal rent distribution to simplify and avoid this per-slot
// computation for the distribution (time: N log N, space: N acct. stores; N = # of
// validators).
// The reason is that rent fee doesn't need to be incentivized for throughput unlike transaction
// fees
//
// Ref: collect_fees
#[allow(clippy::needless_collect)]
fn distribute_rent_to_validators<I>(&self, vote_accounts: I, rent_to_be_distributed: u64)
where
I: IntoIterator<Item = (Pubkey, (u64, ArcVoteAccount))>,
{
let mut total_staked = 0;
// Collect the stake associated with each validator.
// Note that a validator may be present in this vector multiple times if it happens to have
// more than one staked vote account somehow
let mut validator_stakes = vote_accounts
.into_iter()
.filter_map(|(_vote_pubkey, (staked, account))| {
if staked == 0 {
None
} else {
total_staked += staked;
let node_pubkey = account.vote_state().as_ref().ok()?.node_pubkey;
Some((node_pubkey, staked))
}
})
.collect::<Vec<(Pubkey, u64)>>();
#[cfg(test)]
if validator_stakes.is_empty() {
// some tests bank.freezes() with bad staking state
self.capitalization
.fetch_sub(rent_to_be_distributed, Relaxed);
return;
}
#[cfg(not(test))]
assert!(!validator_stakes.is_empty());
// Sort first by stake and then by validator identity pubkey for determinism
validator_stakes.sort_by(|(pubkey1, staked1), (pubkey2, staked2)| {
match staked2.cmp(staked1) {
std::cmp::Ordering::Equal => pubkey2.cmp(pubkey1),
other => other,
}
});
let enforce_fix = self.no_overflow_rent_distribution_enabled();
let mut rent_distributed_in_initial_round = 0;
let validator_rent_shares = validator_stakes
.into_iter()
.map(|(pubkey, staked)| {
let rent_share = if !enforce_fix {
(((staked * rent_to_be_distributed) as f64) / (total_staked as f64)) as u64
} else {
(((staked as u128) * (rent_to_be_distributed as u128)) / (total_staked as u128))
.try_into()
.unwrap()
};
rent_distributed_in_initial_round += rent_share;
(pubkey, rent_share)
})
.collect::<Vec<(Pubkey, u64)>>();
// Leftover lamports after fraction calculation, will be paid to validators starting from highest stake
// holder
let mut leftover_lamports = rent_to_be_distributed - rent_distributed_in_initial_round;
let mut rewards = vec![];
validator_rent_shares
.into_iter()
.for_each(|(pubkey, rent_share)| {
let rent_to_be_paid = if leftover_lamports > 0 {
leftover_lamports -= 1;
rent_share + 1
} else {
rent_share
};
if !enforce_fix || rent_to_be_paid > 0 {
let mut account = self
.get_account_with_fixed_root(&pubkey)
.unwrap_or_default();
account.lamports += rent_to_be_paid;
self.store_account(&pubkey, &account);
rewards.push((
pubkey,
RewardInfo {
reward_type: RewardType::Rent,
lamports: rent_to_be_paid as i64,
post_balance: account.lamports,
},
));
}
});
self.rewards.write().unwrap().append(&mut rewards);
if enforce_fix {
assert_eq!(leftover_lamports, 0);
} else if leftover_lamports != 0 {
warn!(
"There was leftover from rent distribution: {}",
leftover_lamports
);
self.capitalization.fetch_sub(leftover_lamports, Relaxed);
}
}
fn distribute_rent(&self) {
let total_rent_collected = self.collected_rent.load(Relaxed);
let (burned_portion, rent_to_be_distributed) = self
.rent_collector
.rent
.calculate_burn(total_rent_collected);
debug!(
"distributed rent: {} (rounded from: {}, burned: {})",
rent_to_be_distributed, total_rent_collected, burned_portion
);
self.capitalization.fetch_sub(burned_portion, Relaxed);
if rent_to_be_distributed == 0 {
return;
}
self.distribute_rent_to_validators(self.vote_accounts(), rent_to_be_distributed);
}
fn collect_rent(
&self,
res: &[TransactionExecutionResult],
loaded_accounts: &[TransactionLoadResult],
) {
let mut collected_rent: u64 = 0;
for (i, (raccs, _nonce_rollback)) in loaded_accounts.iter().enumerate() {
let (res, _nonce_rollback) = &res[i];
if res.is_err() || raccs.is_err() {
continue;
}
let loaded_transaction = raccs.as_ref().unwrap();
collected_rent += loaded_transaction.rent;
}
self.collected_rent.fetch_add(collected_rent, Relaxed);
}
fn run_incinerator(&self) {
if let Some((account, _)) =
self.get_account_modified_since_parent_with_fixed_root(&incinerator::id())
{
self.capitalization.fetch_sub(account.lamports, Relaxed);
self.store_account(&incinerator::id(), &AccountSharedData::default());
}
}
fn collect_rent_eagerly(&self) {
if !self.enable_eager_rent_collection() {
return;
}
let mut measure = Measure::start("collect_rent_eagerly-ms");
for partition in self.rent_collection_partitions() {
self.collect_rent_in_partition(partition);
}
measure.stop();
inc_new_counter_info!("collect_rent_eagerly-ms", measure.as_ms() as usize);
}
#[cfg(test)]
fn restore_old_behavior_for_fragile_tests(&self) {
self.lazy_rent_collection.store(true, Relaxed);
self.no_stake_rewrite.store(true, Relaxed);
}
fn enable_eager_rent_collection(&self) -> bool {
if self.lazy_rent_collection.load(Relaxed) {
return false;
}
true
}
fn rent_collection_partitions(&self) -> Vec<Partition> {
if !self.use_fixed_collection_cycle() {
// This mode is for production/development/testing.
// In this mode, we iterate over the whole pubkey value range for each epochs
// including warm-up epochs.
// The only exception is the situation where normal epochs are relatively short
// (currently less than 2 day). In that case, we arrange a single collection
// cycle to be multiple of epochs so that a cycle could be greater than the 2 day.
self.variable_cycle_partitions()
} else {
// This mode is mainly for benchmarking only.
// In this mode, we always iterate over the whole pubkey value range with
// <slot_count_in_two_day> slots as a collection cycle, regardless warm-up or
// alignment between collection cycles and epochs.
// Thus, we can simulate stable processing load of eager rent collection,
// strictly proportional to the number of pubkeys since genesis.
self.fixed_cycle_partitions()
}
}
fn collect_rent_in_partition(&self, partition: Partition) {
let subrange = Self::pubkey_range_from_partition(partition);
let accounts = self
.rc
.accounts
.load_to_collect_rent_eagerly(&self.ancestors, subrange);
let account_count = accounts.len();
// parallelize?
let mut rent = 0;
for (pubkey, mut account) in accounts {
rent += self
.rent_collector
.collect_from_existing_account(&pubkey, &mut account);
// Store all of them unconditionally to purge old AppendVec,
// even if collected rent is 0 (= not updated).
self.store_account(&pubkey, &account);
}
self.collected_rent.fetch_add(rent, Relaxed);
datapoint_info!("collect_rent_eagerly", ("accounts", account_count, i64));
}
// Mostly, the pair (start_index & end_index) is equivalent to this range:
// start_index..=end_index. But it has some exceptional cases, including
// this important and valid one:
// 0..=0: the first partition in the new epoch when crossing epochs
fn pubkey_range_from_partition(
(start_index, end_index, partition_count): Partition,
) -> RangeInclusive<Pubkey> {
assert!(start_index <= end_index);
assert!(start_index < partition_count);
assert!(end_index < partition_count);
assert!(0 < partition_count);
type Prefix = u64;
const PREFIX_SIZE: usize = mem::size_of::<Prefix>();
const PREFIX_MAX: Prefix = Prefix::max_value();
let mut start_pubkey = [0x00u8; 32];
let mut end_pubkey = [0xffu8; 32];
if partition_count == 1 {
assert_eq!(start_index, 0);
assert_eq!(end_index, 0);
return Pubkey::new_from_array(start_pubkey)..=Pubkey::new_from_array(end_pubkey);
}
// not-overflowing way of `(Prefix::max_value() + 1) / partition_count`
let partition_width = (PREFIX_MAX - partition_count + 1) / partition_count + 1;
let mut start_key_prefix = if start_index == 0 && end_index == 0 {
0
} else if start_index + 1 == partition_count {
PREFIX_MAX
} else {
(start_index + 1) * partition_width
};
let mut end_key_prefix = if end_index + 1 == partition_count {
PREFIX_MAX
} else {
(end_index + 1) * partition_width - 1
};
if start_index != 0 && start_index == end_index {
// n..=n (n != 0): a noop pair across epochs without a gap under
// multi_epoch_cycle, just nullify it.
if end_key_prefix == PREFIX_MAX {
start_key_prefix = end_key_prefix;
start_pubkey = end_pubkey;
} else {
end_key_prefix = start_key_prefix;
end_pubkey = start_pubkey;
}
}
start_pubkey[0..PREFIX_SIZE].copy_from_slice(&start_key_prefix.to_be_bytes());
end_pubkey[0..PREFIX_SIZE].copy_from_slice(&end_key_prefix.to_be_bytes());
trace!(
"pubkey_range_from_partition: ({}-{})/{} [{}]: {}-{}",
start_index,
end_index,
partition_count,
(end_key_prefix - start_key_prefix),
start_pubkey.iter().map(|x| format!("{:02x}", x)).join(""),
end_pubkey.iter().map(|x| format!("{:02x}", x)).join(""),
);
// should be an inclusive range (a closed interval) like this:
// [0xgg00-0xhhff], [0xii00-0xjjff], ... (where 0xii00 == 0xhhff + 1)
Pubkey::new_from_array(start_pubkey)..=Pubkey::new_from_array(end_pubkey)
}
fn fixed_cycle_partitions(&self) -> Vec<Partition> {
let slot_count_in_two_day = self.slot_count_in_two_day();
let parent_cycle = self.parent_slot() / slot_count_in_two_day;
let current_cycle = self.slot() / slot_count_in_two_day;
let mut parent_cycle_index = self.parent_slot() % slot_count_in_two_day;
let current_cycle_index = self.slot() % slot_count_in_two_day;
let mut partitions = vec![];
if parent_cycle < current_cycle {
if current_cycle_index > 0 {
// generate and push gapped partitions because some slots are skipped
let parent_last_cycle_index = slot_count_in_two_day - 1;
// ... for parent cycle
partitions.push((
parent_cycle_index,
parent_last_cycle_index,
slot_count_in_two_day,
));
// ... for current cycle
partitions.push((0, 0, slot_count_in_two_day));
}
parent_cycle_index = 0;
}
partitions.push((
parent_cycle_index,
current_cycle_index,
slot_count_in_two_day,
));
partitions
}
fn variable_cycle_partitions(&self) -> Vec<Partition> {
let (current_epoch, current_slot_index) = self.get_epoch_and_slot_index(self.slot());
let (parent_epoch, mut parent_slot_index) =
self.get_epoch_and_slot_index(self.parent_slot());
let mut partitions = vec![];
if parent_epoch < current_epoch {
let slot_skipped = (self.slot() - self.parent_slot()) > 1;
if slot_skipped {
// Generate special partitions because there are skipped slots
// exactly at the epoch transition.
let parent_last_slot_index = self.get_slots_in_epoch(parent_epoch) - 1;
// ... for parent epoch
partitions.push(self.partition_from_slot_indexes_with_gapped_epochs(
parent_slot_index,
parent_last_slot_index,
parent_epoch,
));
if current_slot_index > 0 {
// ... for current epoch
partitions.push(self.partition_from_slot_indexes_with_gapped_epochs(
0,
0,
current_epoch,
));
}
}
parent_slot_index = 0;
}
partitions.push(self.partition_from_normal_slot_indexes(
parent_slot_index,
current_slot_index,
current_epoch,
));
partitions
}
fn do_partition_from_slot_indexes(
&self,
start_slot_index: SlotIndex,
end_slot_index: SlotIndex,
epoch: Epoch,
generated_for_gapped_epochs: bool,
) -> Partition {
let cycle_params = self.determine_collection_cycle_params(epoch);
let (_, _, in_multi_epoch_cycle, _, _, partition_count) = cycle_params;
// use common codepath for both very likely and very unlikely for the sake of minimized
// risk of any miscalculation instead of negligibly faster computation per slot for the
// likely case.
let mut start_partition_index =
Self::partition_index_from_slot_index(start_slot_index, cycle_params);
let mut end_partition_index =
Self::partition_index_from_slot_index(end_slot_index, cycle_params);
// Adjust partition index for some edge cases
let is_special_new_epoch = start_slot_index == 0 && end_slot_index != 1;
let in_middle_of_cycle = start_partition_index > 0;
if in_multi_epoch_cycle && is_special_new_epoch && in_middle_of_cycle {
// Adjust slot indexes so that the final partition ranges are continuous!
// This is need because the caller gives us off-by-one indexes when
// an epoch boundary is crossed.
// Usually there is no need for this adjustment because cycles are aligned
// with epochs. But for multi-epoch cycles, adjust the indexes if it
// happens in the middle of a cycle for both gapped and not-gapped cases:
//
// epoch (slot range)|slot idx.*1|raw part. idx.|adj. part. idx.|epoch boundary
// ------------------+-----------+--------------+---------------+--------------
// 3 (20..30) | [7..8] | 7.. 8 | 7.. 8
// | [8..9] | 8.. 9 | 8.. 9
// 4 (30..40) | [0..0] |<10>..10 | <9>..10 <--- not gapped
// | [0..1] | 10..11 | 10..12
// | [1..2] | 11..12 | 11..12
// | [2..9 *2| 12..19 | 12..19 <-+
// 5 (40..50) | 0..0 *2|<20>..<20> |<19>..<19> *3 <-+- gapped
// | 0..4] |<20>..24 |<19>..24 <-+
// | [4..5] | 24..25 | 24..25
// | [5..6] | 25..26 | 25..26
//
// NOTE: <..> means the adjusted slots
//
// *1: The range of parent_bank.slot() and current_bank.slot() is firstly
// split by the epoch boundaries and then the split ones are given to us.
// The original ranges are denoted as [...]
// *2: These are marked with generated_for_gapped_epochs = true.
// *3: This becomes no-op partition
start_partition_index -= 1;
if generated_for_gapped_epochs {
assert_eq!(start_slot_index, end_slot_index);
end_partition_index -= 1;
}
}
(start_partition_index, end_partition_index, partition_count)
}
fn partition_from_normal_slot_indexes(
&self,
start_slot_index: SlotIndex,
end_slot_index: SlotIndex,
epoch: Epoch,
) -> Partition {
self.do_partition_from_slot_indexes(start_slot_index, end_slot_index, epoch, false)
}
fn partition_from_slot_indexes_with_gapped_epochs(
&self,
start_slot_index: SlotIndex,
end_slot_index: SlotIndex,
epoch: Epoch,
) -> Partition {
self.do_partition_from_slot_indexes(start_slot_index, end_slot_index, epoch, true)
}
fn determine_collection_cycle_params(&self, epoch: Epoch) -> RentCollectionCycleParams {
let slot_count_per_epoch = self.get_slots_in_epoch(epoch);
if !self.use_multi_epoch_collection_cycle(epoch) {
(
epoch,
slot_count_per_epoch,
false,
0,
1,
slot_count_per_epoch,
)
} else {
let epoch_count_in_cycle = self.slot_count_in_two_day() / slot_count_per_epoch;
let partition_count = slot_count_per_epoch * epoch_count_in_cycle;
(
epoch,
slot_count_per_epoch,
true,
self.first_normal_epoch(),
epoch_count_in_cycle,
partition_count,
)
}
}
fn partition_index_from_slot_index(
slot_index_in_epoch: SlotIndex,
(
epoch,
slot_count_per_epoch,
_,
base_epoch,
epoch_count_per_cycle,
_,
): RentCollectionCycleParams,
) -> PartitionIndex {
let epoch_offset = epoch - base_epoch;
let epoch_index_in_cycle = epoch_offset % epoch_count_per_cycle;
slot_index_in_epoch + epoch_index_in_cycle * slot_count_per_epoch
}
// Given short epochs, it's too costly to collect rent eagerly
// within an epoch, so lower the frequency of it.
// These logic isn't strictly eager anymore and should only be used
// for development/performance purpose.
// Absolutely not under ClusterType::MainnetBeta!!!!
fn use_multi_epoch_collection_cycle(&self, epoch: Epoch) -> bool {
// Force normal behavior, disabling multi epoch collection cycle for manual local testing
#[cfg(not(test))]
if self.slot_count_per_normal_epoch() == solana_sdk::epoch_schedule::MINIMUM_SLOTS_PER_EPOCH
{
return false;
}
epoch >= self.first_normal_epoch()
&& self.slot_count_per_normal_epoch() < self.slot_count_in_two_day()
}
fn use_fixed_collection_cycle(&self) -> bool {
// Force normal behavior, disabling fixed collection cycle for manual local testing
#[cfg(not(test))]
if self.slot_count_per_normal_epoch() == solana_sdk::epoch_schedule::MINIMUM_SLOTS_PER_EPOCH
{
return false;
}
self.cluster_type() != ClusterType::MainnetBeta
&& self.slot_count_per_normal_epoch() < self.slot_count_in_two_day()
}
// This value is specially chosen to align with slots per epoch in mainnet-beta and testnet
// Also, assume 500GB account data set as the extreme, then for 2 day (=48 hours) to collect
// rent eagerly, we'll consume 5.7 MB/s IO bandwidth, bidirectionally.
fn slot_count_in_two_day(&self) -> SlotCount {
2 * DEFAULT_TICKS_PER_SECOND * SECONDS_PER_DAY / self.ticks_per_slot
}
fn slot_count_per_normal_epoch(&self) -> SlotCount {
self.get_slots_in_epoch(self.first_normal_epoch())
}
pub fn cluster_type(&self) -> ClusterType {
// unwrap is safe; self.cluster_type is ensured to be Some() always...
// we only using Option here for ABI compatibility...
self.cluster_type.unwrap()
}
/// Process a batch of transactions.
#[must_use]
pub fn load_execute_and_commit_transactions(
&self,
batch: &TransactionBatch,
max_age: usize,
collect_balances: bool,
enable_cpi_recording: bool,
enable_log_recording: bool,
timings: &mut ExecuteTimings,
) -> (
TransactionResults,
TransactionBalancesSet,
Vec<Option<InnerInstructionsList>>,
Vec<TransactionLogMessages>,
) {
let pre_balances = if collect_balances {
self.collect_balances(batch)
} else {
vec![]
};
let (
mut loaded_accounts,
executed,
inner_instructions,
transaction_logs,
_,
tx_count,
signature_count,
) = self.load_and_execute_transactions(
batch,
max_age,
enable_cpi_recording,
enable_log_recording,
timings,
);
let results = self.commit_transactions(
batch.hashed_transactions(),
&mut loaded_accounts,
&executed,
tx_count,
signature_count,
timings,
);
let post_balances = if collect_balances {
self.collect_balances(batch)
} else {
vec![]
};
(
results,
TransactionBalancesSet::new(pre_balances, post_balances),
inner_instructions,
transaction_logs,
)
}
/// Process a Transaction. This is used for unit tests and simply calls the vector
/// Bank::process_transactions method
pub fn process_transaction(&self, tx: &Transaction) -> Result<()> {
let batch = self.prepare_batch(std::iter::once(tx));
self.process_transaction_batch(&batch)[0].clone()?;
tx.signatures
.get(0)
.map_or(Ok(()), |sig| self.get_signature_status(sig).unwrap())
}
#[must_use]
pub fn process_transactions(&self, txs: &[Transaction]) -> Vec<Result<()>> {
let batch = self.prepare_batch(txs.iter());
self.process_transaction_batch(&batch)
}
#[must_use]
fn process_transaction_batch(&self, batch: &TransactionBatch) -> Vec<Result<()>> {
self.load_execute_and_commit_transactions(
batch,
MAX_PROCESSING_AGE,
false,
false,
false,
&mut ExecuteTimings::default(),
)
.0
.fee_collection_results
}
/// Create, sign, and process a Transaction from `keypair` to `to` of
/// `n` lamports where `blockhash` is the last Entry ID observed by the client.
pub fn transfer(&self, n: u64, keypair: &Keypair, to: &Pubkey) -> Result<Signature> {
let blockhash = self.last_blockhash();
let tx = system_transaction::transfer(keypair, to, n, blockhash);
let signature = tx.signatures[0];
self.process_transaction(&tx).map(|_| signature)
}
pub fn read_balance(account: &AccountSharedData) -> u64 {
account.lamports
}
/// Each program would need to be able to introspect its own state
/// this is hard-coded to the Budget language
pub fn get_balance(&self, pubkey: &Pubkey) -> u64 {
self.get_account(pubkey)
.map(|x| Self::read_balance(&x))
.unwrap_or(0)
}
/// Compute all the parents of the bank in order
pub fn parents(&self) -> Vec<Arc<Bank>> {
let mut parents = vec![];
let mut bank = self.parent();
while let Some(parent) = bank {
parents.push(parent.clone());
bank = parent.parent();
}
parents
}
/// Compute all the parents of the bank including this bank itself
pub fn parents_inclusive(self: Arc<Self>) -> Vec<Arc<Bank>> {
let mut parents = self.parents();
parents.insert(0, self);
parents
}
pub fn store_account(&self, pubkey: &Pubkey, account: &AccountSharedData) {
assert!(!self.freeze_started());
self.rc
.accounts
.store_slow_cached(self.slot(), pubkey, account);
if Stakes::is_stake(account) {
self.stakes.write().unwrap().store(
pubkey,
account,
self.stake_program_v2_enabled(),
self.check_init_vote_data_enabled(),
);
}
}
pub fn force_flush_accounts_cache(&self) {
self.rc
.accounts
.accounts_db
.flush_accounts_cache(true, Some(self.slot()))
}
pub fn flush_accounts_cache_if_needed(&self) {
self.rc
.accounts
.accounts_db
.flush_accounts_cache(false, Some(self.slot()))
}
pub fn expire_old_recycle_stores(&self) {
self.rc.accounts.accounts_db.expire_old_recycle_stores()
}
/// Technically this issues (or even burns!) new lamports,
/// so be extra careful for its usage
fn store_account_and_update_capitalization(
&self,
pubkey: &Pubkey,
new_account: &AccountSharedData,
) {
if let Some(old_account) = self.get_account_with_fixed_root(&pubkey) {
match new_account.lamports.cmp(&old_account.lamports) {
std::cmp::Ordering::Greater => {
self.capitalization
.fetch_add(new_account.lamports - old_account.lamports, Relaxed);
}
std::cmp::Ordering::Less => {
self.capitalization
.fetch_sub(old_account.lamports - new_account.lamports, Relaxed);
}
std::cmp::Ordering::Equal => {}
}
} else {
self.capitalization.fetch_add(new_account.lamports, Relaxed);
}
self.store_account(pubkey, new_account);
}
fn withdraw(&self, pubkey: &Pubkey, lamports: u64) -> Result<()> {
match self.get_account_with_fixed_root(pubkey) {
Some(mut account) => {
let min_balance = match get_system_account_kind(&account) {
Some(SystemAccountKind::Nonce) => self
.rent_collector
.rent
.minimum_balance(nonce::State::size()),
_ => 0,
};
lamports
.checked_add(min_balance)
.filter(|required_balance| *required_balance <= account.lamports())
.ok_or(TransactionError::InsufficientFundsForFee)?;
account
.checked_sub_lamports(lamports)
.map_err(|_| TransactionError::InsufficientFundsForFee)?;
self.store_account(pubkey, &account);
Ok(())
}
None => Err(TransactionError::AccountNotFound),
}
}
pub fn deposit(&self, pubkey: &Pubkey, lamports: u64) -> u64 {
// This doesn't collect rents intentionally.
// Rents should only be applied to actual TXes
let mut account = self.get_account_with_fixed_root(pubkey).unwrap_or_default();
account.lamports += lamports;
self.store_account(pubkey, &account);
account.lamports
}
pub fn accounts(&self) -> Arc<Accounts> {
self.rc.accounts.clone()
}
fn finish_init(
&mut self,
genesis_config: &GenesisConfig,
additional_builtins: Option<&Builtins>,
) {
self.rewards_pool_pubkeys =
Arc::new(genesis_config.rewards_pools.keys().cloned().collect());
let mut builtins = builtins::get();
if let Some(additional_builtins) = additional_builtins {
builtins
.genesis_builtins
.extend_from_slice(&additional_builtins.genesis_builtins);
builtins
.feature_builtins
.extend_from_slice(&additional_builtins.feature_builtins);
}
for builtin in builtins.genesis_builtins {
self.add_builtin(
&builtin.name,
builtin.id,
builtin.process_instruction_with_context,
);
}
self.feature_builtins = Arc::new(builtins.feature_builtins);
self.apply_feature_activations(true);
}
pub fn set_inflation(&self, inflation: Inflation) {
*self.inflation.write().unwrap() = inflation;
}
pub fn set_bpf_compute_budget(&mut self, bpf_compute_budget: Option<BpfComputeBudget>) {
self.bpf_compute_budget = bpf_compute_budget;
}
pub fn hard_forks(&self) -> Arc<RwLock<HardForks>> {
self.hard_forks.clone()
}
// Hi! leaky abstraction here....
// try to use get_account_with_fixed_root() if it's called ONLY from on-chain runtime account
// processing. That alternative fn provides more safety.
pub fn get_account(&self, pubkey: &Pubkey) -> Option<AccountSharedData> {
self.get_account_modified_slot(pubkey)
.map(|(acc, _slot)| acc)
}
// Hi! leaky abstraction here....
// use this over get_account() if it's called ONLY from on-chain runtime account
// processing (i.e. from in-band replay/banking stage; that ensures root is *fixed* while
// running).
// pro: safer assertion can be enabled inside AccountsDb
// con: panics!() if called from off-chain processing
pub fn get_account_with_fixed_root(&self, pubkey: &Pubkey) -> Option<AccountSharedData> {
self.load_slow_with_fixed_root(&self.ancestors, pubkey)
.map(|(acc, _slot)| acc)
}
pub fn get_account_modified_slot(&self, pubkey: &Pubkey) -> Option<(AccountSharedData, Slot)> {
self.load_slow(&self.ancestors, pubkey)
}
fn load_slow(
&self,
ancestors: &Ancestors,
pubkey: &Pubkey,
) -> Option<(AccountSharedData, Slot)> {
// get_account (= primary this fn caller) may be called from on-chain Bank code even if we
// try hard to use get_account_with_fixed_root for that purpose...
// so pass safer LoadHint:Unspecified here as a fallback
self.rc.accounts.load_without_fixed_root(ancestors, pubkey)
}
fn load_slow_with_fixed_root(
&self,
ancestors: &Ancestors,
pubkey: &Pubkey,
) -> Option<(AccountSharedData, Slot)> {
self.rc.accounts.load_with_fixed_root(ancestors, pubkey)
}
// Exclude self to really fetch the parent Bank's account hash and data.
//
// Being idempotent is needed to make the lazy initialization possible,
// especially for update_slot_hashes at the moment, which can be called
// multiple times with the same parent_slot in the case of forking.
//
// Generally, all of sysvar update granularity should be slot boundaries.
fn get_sysvar_account_with_fixed_root(&self, pubkey: &Pubkey) -> Option<AccountSharedData> {
let mut ancestors = self.ancestors.clone();
ancestors.remove(&self.slot());
self.rc
.accounts
.load_with_fixed_root(&ancestors, pubkey)
.map(|(acc, _slot)| acc)
}
pub fn get_program_accounts(&self, program_id: &Pubkey) -> Vec<(Pubkey, AccountSharedData)> {
self.rc
.accounts
.load_by_program(&self.ancestors, program_id)
}
pub fn get_filtered_program_accounts<F: Fn(&AccountSharedData) -> bool>(
&self,
program_id: &Pubkey,
filter: F,
) -> Vec<(Pubkey, AccountSharedData)> {
self.rc
.accounts
.load_by_program_with_filter(&self.ancestors, program_id, filter)
}
pub fn get_filtered_indexed_accounts<F: Fn(&AccountSharedData) -> bool>(
&self,
index_key: &IndexKey,
filter: F,
) -> Vec<(Pubkey, AccountSharedData)> {
self.rc
.accounts
.load_by_index_key_with_filter(&self.ancestors, index_key, filter)
}
pub fn get_all_accounts_with_modified_slots(&self) -> Vec<(Pubkey, AccountSharedData, Slot)> {
self.rc.accounts.load_all(&self.ancestors)
}
pub fn get_program_accounts_modified_since_parent(
&self,
program_id: &Pubkey,
) -> Vec<(Pubkey, AccountSharedData)> {
self.rc
.accounts
.load_by_program_slot(self.slot(), Some(program_id))
}
pub fn get_transaction_logs(
&self,
address: Option<&Pubkey>,
) -> Option<Vec<TransactionLogInfo>> {
let transaction_log_collector = self.transaction_log_collector.read().unwrap();
match address {
None => Some(transaction_log_collector.logs.clone()),
Some(address) => transaction_log_collector
.mentioned_address_map
.get(address)
.map(|log_indices| {
log_indices
.iter()
.map(|i| transaction_log_collector.logs[*i].clone())
.collect()
}),
}
}
pub fn get_all_accounts_modified_since_parent(&self) -> Vec<(Pubkey, AccountSharedData)> {
self.rc.accounts.load_by_program_slot(self.slot(), None)
}
// if you want get_account_modified_since_parent without fixed_root, please define so...
fn get_account_modified_since_parent_with_fixed_root(
&self,
pubkey: &Pubkey,
) -> Option<(AccountSharedData, Slot)> {
let just_self: Ancestors = vec![(self.slot(), 0)].into_iter().collect();
if let Some((account, slot)) = self.load_slow_with_fixed_root(&just_self, pubkey) {
if slot == self.slot() {
return Some((account, slot));
}
}
None
}
pub fn get_largest_accounts(
&self,
num: usize,
filter_by_address: &HashSet<Pubkey>,
filter: AccountAddressFilter,
) -> Vec<(Pubkey, u64)> {
self.rc
.accounts
.load_largest_accounts(&self.ancestors, num, filter_by_address, filter)
}
pub fn transaction_count(&self) -> u64 {
self.transaction_count.load(Relaxed)
}
pub fn transaction_error_count(&self) -> u64 {
self.transaction_error_count.load(Relaxed)
}
pub fn transaction_entries_count(&self) -> u64 {
self.transaction_entries_count.load(Relaxed)
}
pub fn transactions_per_entry_max(&self) -> u64 {
self.transactions_per_entry_max.load(Relaxed)
}
fn increment_transaction_count(&self, tx_count: u64) {
self.transaction_count.fetch_add(tx_count, Relaxed);
}
pub fn signature_count(&self) -> u64 {
self.signature_count.load(Relaxed)
}
fn increment_signature_count(&self, signature_count: u64) {
self.signature_count.fetch_add(signature_count, Relaxed);
}
pub fn get_signature_status_processed_since_parent(
&self,
signature: &Signature,
) -> Option<Result<()>> {
if let Some((slot, status)) = self.get_signature_status_slot(signature) {
if slot <= self.slot() {
return Some(status);
}
}
None
}
pub fn get_signature_status_with_blockhash(
&self,
signature: &Signature,
blockhash: &Hash,
) -> Option<Result<()>> {
let rcache = self.src.status_cache.read().unwrap();
rcache
.get_status(signature, blockhash, &self.ancestors)
.map(|v| v.1)
}
pub fn get_signature_status_slot(&self, signature: &Signature) -> Option<(Slot, Result<()>)> {
let rcache = self.src.status_cache.read().unwrap();
rcache.get_status_any_blockhash(signature, &self.ancestors)
}
pub fn get_signature_status(&self, signature: &Signature) -> Option<Result<()>> {
self.get_signature_status_slot(signature).map(|v| v.1)
}
pub fn has_signature(&self, signature: &Signature) -> bool {
self.get_signature_status_slot(signature).is_some()
}
/// Hash the `accounts` HashMap. This represents a validator's interpretation
/// of the delta of the ledger since the last vote and up to now
fn hash_internal_state(&self) -> Hash {
// If there are no accounts, return the hash of the previous state and the latest blockhash
let accounts_delta_hash = self.rc.accounts.bank_hash_info_at(self.slot());
let mut signature_count_buf = [0u8; 8];
LittleEndian::write_u64(&mut signature_count_buf[..], self.signature_count() as u64);
let mut hash = hashv(&[
self.parent_hash.as_ref(),
accounts_delta_hash.hash.as_ref(),
&signature_count_buf,
self.last_blockhash().as_ref(),
]);
if let Some(buf) = self
.hard_forks
.read()
.unwrap()
.get_hash_data(self.slot(), self.parent_slot())
{
info!("hard fork at bank {}", self.slot());
hash = extend_and_hash(&hash, &buf)
}
info!(
"bank frozen: {} hash: {} accounts_delta: {} signature_count: {} last_blockhash: {} capitalization: {}",
self.slot(),
hash,
accounts_delta_hash.hash,
self.signature_count(),
self.last_blockhash(),
self.capitalization(),
);
info!(
"accounts hash slot: {} stats: {:?}",
self.slot(),
accounts_delta_hash.stats,
);
hash
}
/// Recalculate the hash_internal_state from the account stores. Would be used to verify a
/// snapshot.
#[must_use]
fn verify_bank_hash(&self) -> bool {
self.rc.accounts.verify_bank_hash_and_lamports(
self.slot(),
&self.ancestors,
self.capitalization(),
)
}
pub fn get_snapshot_storages(&self) -> SnapshotStorages {
self.rc
.get_snapshot_storages(self.slot())
.into_iter()
.collect()
}
#[must_use]
fn verify_hash(&self) -> bool {
assert!(self.is_frozen());
let calculated_hash = self.hash_internal_state();
let expected_hash = self.hash();
if calculated_hash == expected_hash {
true
} else {
warn!(
"verify failed: slot: {}, {} (calculated) != {} (expected)",
self.slot(),
calculated_hash,
expected_hash
);
false
}
}
pub fn calculate_capitalization(&self) -> u64 {
self.rc.accounts.calculate_capitalization(&self.ancestors)
}
pub fn calculate_and_verify_capitalization(&self) -> bool {
let calculated = self.calculate_capitalization();
let expected = self.capitalization();
if calculated == expected {
true
} else {
warn!(
"Capitalization mismatch: calculated: {} != expected: {}",
calculated, expected
);
false
}
}
/// Forcibly overwrites current capitalization by actually recalculating accounts' balances.
/// This should only be used for developing purposes.
pub fn set_capitalization(&self) -> u64 {
let old = self.capitalization();
self.capitalization
.store(self.calculate_capitalization(), Relaxed);
old
}
pub fn get_accounts_hash(&self) -> Hash {
self.rc.accounts.accounts_db.get_accounts_hash(self.slot)
}
pub fn get_thread_pool(&self) -> &ThreadPool {
&self.rc.accounts.accounts_db.thread_pool_clean
}
pub fn update_accounts_hash_with_index_option(
&self,
use_index: bool,
debug_verify: bool,
) -> Hash {
let (hash, total_lamports) = self
.rc
.accounts
.accounts_db
.update_accounts_hash_with_index_option(
use_index,
debug_verify,
self.slot(),
&self.ancestors,
Some(self.capitalization()),
);
assert_eq!(total_lamports, self.capitalization());
hash
}
pub fn update_accounts_hash(&self) -> Hash {
self.update_accounts_hash_with_index_option(true, false)
}
/// A snapshot bank should be purged of 0 lamport accounts which are not part of the hash
/// calculation and could shield other real accounts.
pub fn verify_snapshot_bank(&self) -> bool {
if self.slot() > 0 {
self.clean_accounts(true);
self.shrink_all_slots();
}
// Order and short-circuiting is significant; verify_hash requires a valid bank hash
self.verify_bank_hash() && self.verify_hash()
}
/// Return the number of hashes per tick
pub fn hashes_per_tick(&self) -> &Option<u64> {
&self.hashes_per_tick
}
/// Return the number of ticks per slot
pub fn ticks_per_slot(&self) -> u64 {
self.ticks_per_slot
}
/// Return the number of slots per year
pub fn slots_per_year(&self) -> f64 {
self.slots_per_year
}
/// Return the number of ticks since genesis.
pub fn tick_height(&self) -> u64 {
self.tick_height.load(Relaxed)
}
/// Return the inflation parameters of the Bank
pub fn inflation(&self) -> Inflation {
*self.inflation.read().unwrap()
}
/// Return the total capitalization of the Bank
pub fn capitalization(&self) -> u64 {
self.capitalization.load(Relaxed)
}
/// Return this bank's max_tick_height
pub fn max_tick_height(&self) -> u64 {
self.max_tick_height
}
/// Return the block_height of this bank
pub fn block_height(&self) -> u64 {
self.block_height
}
/// Return the number of slots per epoch for the given epoch
pub fn get_slots_in_epoch(&self, epoch: Epoch) -> u64 {
self.epoch_schedule.get_slots_in_epoch(epoch)
}
/// returns the epoch for which this bank's leader_schedule_slot_offset and slot would
/// need to cache leader_schedule
pub fn get_leader_schedule_epoch(&self, slot: Slot) -> Epoch {
self.epoch_schedule.get_leader_schedule_epoch(slot)
}
/// a bank-level cache of vote accounts
fn update_cached_accounts<'a>(
&self,
txs: impl Iterator<Item = &'a Transaction>,
res: &[TransactionExecutionResult],
loaded: &[TransactionLoadResult],
) -> Vec<OverwrittenVoteAccount> {
let mut overwritten_vote_accounts = vec![];
for (i, ((raccs, _load_nonce_rollback), tx)) in loaded.iter().zip(txs).enumerate() {
let (res, _res_nonce_rollback) = &res[i];
if res.is_err() || raccs.is_err() {
continue;
}
let message = &tx.message();
let loaded_transaction = raccs.as_ref().unwrap();
for (pubkey, account) in message
.account_keys
.iter()
.zip(loaded_transaction.accounts.iter())
.filter(|(_key, account)| (Stakes::is_stake(account)))
{
if Stakes::is_stake(account) {
if let Some(old_vote_account) = self.stakes.write().unwrap().store(
pubkey,
account,
self.stake_program_v2_enabled(),
self.check_init_vote_data_enabled(),
) {
// TODO: one of the indices is redundant.
overwritten_vote_accounts.push(OverwrittenVoteAccount {
account: old_vote_account,
transaction_index: i,
transaction_result_index: i,
});
}
}
}
}
overwritten_vote_accounts
}
/// current stake delegations for this bank
pub fn cloned_stake_delegations(&self) -> HashMap<Pubkey, Delegation> {
self.stakes.read().unwrap().stake_delegations().clone()
}
pub fn staked_nodes(&self) -> HashMap<Pubkey, u64> {
self.stakes.read().unwrap().staked_nodes()
}
/// current vote accounts for this bank along with the stake
/// attributed to each account
/// Note: This clones the entire vote-accounts hashmap. For a single
/// account lookup use get_vote_account instead.
pub fn vote_accounts(&self) -> Vec<(Pubkey, (u64 /*stake*/, ArcVoteAccount))> {
self.stakes
.read()
.unwrap()
.vote_accounts()
.iter()
.map(|(k, v)| (*k, v.clone()))
.collect()
}
/// Vote account for the given vote account pubkey along with the stake.
pub fn get_vote_account(
&self,
vote_account: &Pubkey,
) -> Option<(u64 /*stake*/, ArcVoteAccount)> {
self.stakes
.read()
.unwrap()
.vote_accounts()
.get(vote_account)
.cloned()
}
/// Get the EpochStakes for a given epoch
pub fn epoch_stakes(&self, epoch: Epoch) -> Option<&EpochStakes> {
self.epoch_stakes.get(&epoch)
}
pub fn epoch_stakes_map(&self) -> &HashMap<Epoch, EpochStakes> {
&self.epoch_stakes
}
pub fn epoch_staked_nodes(&self, epoch: Epoch) -> Option<HashMap<Pubkey, u64>> {
Some(self.epoch_stakes.get(&epoch)?.stakes().staked_nodes())
}
/// vote accounts for the specific epoch along with the stake
/// attributed to each account
pub fn epoch_vote_accounts(
&self,
epoch: Epoch,
) -> Option<&HashMap<Pubkey, (u64, ArcVoteAccount)>> {
self.epoch_stakes
.get(&epoch)
.map(|epoch_stakes| Stakes::vote_accounts(epoch_stakes.stakes()))
}
/// Get the fixed authorized voter for the given vote account for the
/// current epoch
pub fn epoch_authorized_voter(&self, vote_account: &Pubkey) -> Option<&Pubkey> {
self.epoch_stakes
.get(&self.epoch)
.expect("Epoch stakes for bank's own epoch must exist")
.epoch_authorized_voters()
.get(vote_account)
}
/// Get the fixed set of vote accounts for the given node id for the
/// current epoch
pub fn epoch_vote_accounts_for_node_id(&self, node_id: &Pubkey) -> Option<&NodeVoteAccounts> {
self.epoch_stakes
.get(&self.epoch)
.expect("Epoch stakes for bank's own epoch must exist")
.node_id_to_vote_accounts()
.get(node_id)
}
/// Get the fixed total stake of all vote accounts for current epoch
pub fn total_epoch_stake(&self) -> u64 {
self.epoch_stakes
.get(&self.epoch)
.expect("Epoch stakes for bank's own epoch must exist")
.total_stake()
}
/// Get the fixed stake of the given vote account for the current epoch
pub fn epoch_vote_account_stake(&self, vote_account: &Pubkey) -> u64 {
*self
.epoch_vote_accounts(self.epoch())
.expect("Bank epoch vote accounts must contain entry for the bank's own epoch")
.get(vote_account)
.map(|(stake, _)| stake)
.unwrap_or(&0)
}
/// given a slot, return the epoch and offset into the epoch this slot falls
/// e.g. with a fixed number for slots_per_epoch, the calculation is simply:
///
/// ( slot/slots_per_epoch, slot % slots_per_epoch )
///
pub fn get_epoch_and_slot_index(&self, slot: Slot) -> (Epoch, SlotIndex) {
self.epoch_schedule.get_epoch_and_slot_index(slot)
}
pub fn get_epoch_info(&self) -> EpochInfo {
let absolute_slot = self.slot();
let block_height = self.block_height();
let (epoch, slot_index) = self.get_epoch_and_slot_index(absolute_slot);
let slots_in_epoch = self.get_slots_in_epoch(epoch);
let transaction_count = Some(self.transaction_count());
EpochInfo {
epoch,
slot_index,
slots_in_epoch,
absolute_slot,
block_height,
transaction_count,
}
}
pub fn is_empty(&self) -> bool {
!self.is_delta.load(Relaxed)
}
/// Add an instruction processor to intercept instructions before the dynamic loader.
pub fn add_builtin(
&mut self,
name: &str,
program_id: Pubkey,
process_instruction_with_context: ProcessInstructionWithContext,
) {
debug!("Adding program {} under {:?}", name, program_id);
self.add_native_program(name, &program_id, false);
self.message_processor
.add_program(program_id, process_instruction_with_context);
}
/// Replace a builtin instruction processor if it already exists
pub fn replace_builtin(
&mut self,
name: &str,
program_id: Pubkey,
process_instruction_with_context: ProcessInstructionWithContext,
) {
debug!("Replacing program {} under {:?}", name, program_id);
self.add_native_program(name, &program_id, true);
self.message_processor
.add_program(program_id, process_instruction_with_context);
}
pub fn clean_accounts(&self, skip_last: bool) {
let max_clean_slot = if skip_last {
// Don't clean the slot we're snapshotting because it may have zero-lamport
// accounts that were included in the bank delta hash when the bank was frozen,
// and if we clean them here, any newly created snapshot's hash for this bank
// may not match the frozen hash.
Some(self.slot().saturating_sub(1))
} else {
None
};
self.rc.accounts.accounts_db.clean_accounts(max_clean_slot);
}
pub fn shrink_all_slots(&self) {
self.rc.accounts.accounts_db.shrink_all_slots();
}
pub fn print_accounts_stats(&self) {
self.rc.accounts.accounts_db.print_accounts_stats("");
}
pub fn process_stale_slot_with_budget(
&self,
mut consumed_budget: usize,
budget_recovery_delta: usize,
) -> usize {
if consumed_budget == 0 {
let shrunken_account_count = self.rc.accounts.accounts_db.process_stale_slot_v1();
if shrunken_account_count > 0 {
datapoint_info!(
"stale_slot_shrink",
("accounts", shrunken_account_count, i64)
);
consumed_budget += shrunken_account_count;
}
}
consumed_budget.saturating_sub(budget_recovery_delta)
}
pub fn shrink_candidate_slots(&self) -> usize {
self.rc.accounts.accounts_db.shrink_candidate_slots()
}
pub fn secp256k1_program_enabled(&self) -> bool {
self.feature_set
.is_active(&feature_set::secp256k1_program_enabled::id())
}
pub fn no_overflow_rent_distribution_enabled(&self) -> bool {
self.feature_set
.is_active(&feature_set::no_overflow_rent_distribution::id())
}
pub fn stake_program_v2_enabled(&self) -> bool {
self.feature_set
.is_active(&feature_set::stake_program_v2::id())
}
pub fn check_init_vote_data_enabled(&self) -> bool {
self.feature_set
.is_active(&feature_set::check_init_vote_data::id())
}
pub fn check_duplicates_by_hash_enabled(&self) -> bool {
self.feature_set
.is_active(&feature_set::check_duplicates_by_hash::id())
}
// Check if the wallclock time from bank creation to now has exceeded the allotted
// time for transaction processing
pub fn should_bank_still_be_processing_txs(
bank_creation_time: &Instant,
max_tx_ingestion_nanos: u128,
) -> bool {
// Do this check outside of the poh lock, hence not a method on PohRecorder
bank_creation_time.elapsed().as_nanos() <= max_tx_ingestion_nanos
}
pub fn deactivate_feature(&mut self, id: &Pubkey) {
let mut feature_set = Arc::make_mut(&mut self.feature_set).clone();
feature_set.active.remove(&id);
feature_set.inactive.insert(*id);
self.feature_set = Arc::new(feature_set);
}
pub fn activate_feature(&mut self, id: &Pubkey) {
let mut feature_set = Arc::make_mut(&mut self.feature_set).clone();
feature_set.inactive.remove(id);
feature_set.active.insert(*id, 0);
self.feature_set = Arc::new(feature_set);
}
// This is called from snapshot restore AND for each epoch boundary
// The entire code path herein must be idempotent
fn apply_feature_activations(&mut self, init_finish_or_warp: bool) {
let new_feature_activations = self.compute_active_feature_set(!init_finish_or_warp);
if new_feature_activations.contains(&feature_set::pico_inflation::id()) {
*self.inflation.write().unwrap() = Inflation::pico();
self.fee_rate_governor.burn_percent = 50; // 50% fee burn
self.rent_collector.rent.burn_percent = 50; // 50% rent burn
}
if !new_feature_activations.is_disjoint(&self.feature_set.full_inflation_features_enabled())
{
*self.inflation.write().unwrap() = Inflation::full();
self.fee_rate_governor.burn_percent = 50; // 50% fee burn
self.rent_collector.rent.burn_percent = 50; // 50% rent burn
}
if new_feature_activations.contains(&feature_set::spl_token_v2_self_transfer_fix::id()) {
self.apply_spl_token_v2_self_transfer_fix();
}
// Remove me after a while around v1.6
if !self.no_stake_rewrite.load(Relaxed)
&& new_feature_activations.contains(&feature_set::rewrite_stake::id())
{
// to avoid any potential risk of wrongly rewriting accounts in the future,
// only do this once, taking small risk of unknown
// bugs which again creates bad stake accounts..
self.rewrite_stakes();
}
self.ensure_feature_builtins(init_finish_or_warp, &new_feature_activations);
self.reconfigure_token2_native_mint();
self.ensure_no_storage_rewards_pool();
}
// Compute the active feature set based on the current bank state, and return the set of newly activated features
fn compute_active_feature_set(&mut self, allow_new_activations: bool) -> HashSet<Pubkey> {
let mut active = self.feature_set.active.clone();
let mut inactive = HashSet::new();
let mut newly_activated = HashSet::new();
let slot = self.slot();
for feature_id in &self.feature_set.inactive {
let mut activated = None;
if let Some(mut account) = self.get_account_with_fixed_root(feature_id) {
if let Some(mut feature) = feature::from_account(&account) {
match feature.activated_at {
None => {
if allow_new_activations {
// Feature has been requested, activate it now
feature.activated_at = Some(slot);
if feature::to_account(&feature, &mut account).is_some() {
self.store_account(feature_id, &account);
}
newly_activated.insert(*feature_id);
activated = Some(slot);
info!("Feature {} activated at slot {}", feature_id, slot);
}
}
Some(activation_slot) => {
if slot >= activation_slot {
// Feature is already active
activated = Some(activation_slot);
}
}
}
}
}
if let Some(slot) = activated {
active.insert(*feature_id, slot);
} else {
inactive.insert(*feature_id);
}
}
self.feature_set = Arc::new(FeatureSet { active, inactive });
newly_activated
}
fn ensure_feature_builtins(
&mut self,
init_or_warp: bool,
new_feature_activations: &HashSet<Pubkey>,
) {
let feature_builtins = self.feature_builtins.clone();
for (builtin, feature, activation_type) in feature_builtins.iter() {
let should_populate = init_or_warp && self.feature_set.is_active(&feature)
|| !init_or_warp && new_feature_activations.contains(&feature);
if should_populate {
match activation_type {
ActivationType::NewProgram => self.add_builtin(
&builtin.name,
builtin.id,
builtin.process_instruction_with_context,
),
ActivationType::NewVersion => self.replace_builtin(
&builtin.name,
builtin.id,
builtin.process_instruction_with_context,
),
}
}
}
}
fn apply_spl_token_v2_self_transfer_fix(&mut self) {
if let Some(old_account) = self.get_account_with_fixed_root(&inline_spl_token_v2_0::id()) {
if let Some(new_account) =
self.get_account_with_fixed_root(&inline_spl_token_v2_0::new_token_program::id())
{
datapoint_info!(
"bank-apply_spl_token_v2_self_transfer_fix",
("slot", self.slot, i64),
);
// Burn lamports in the old token account
self.capitalization.fetch_sub(old_account.lamports, Relaxed);
// Transfer new token account to old token account
self.store_account(&inline_spl_token_v2_0::id(), &new_account);
// Clear new token account
self.store_account(
&inline_spl_token_v2_0::new_token_program::id(),
&AccountSharedData::default(),
);
self.remove_executor(&inline_spl_token_v2_0::id());
}
}
}
fn reconfigure_token2_native_mint(&mut self) {
let reconfigure_token2_native_mint = match self.cluster_type() {
ClusterType::Development => true,
ClusterType::Devnet => true,
ClusterType::Testnet => self.epoch() == 93,
ClusterType::MainnetBeta => self.epoch() == 75,
};
if reconfigure_token2_native_mint {
let mut native_mint_account = solana_sdk::account::AccountSharedData::from(Account {
owner: inline_spl_token_v2_0::id(),
data: inline_spl_token_v2_0::native_mint::ACCOUNT_DATA.to_vec(),
lamports: sol_to_lamports(1.),
executable: false,
rent_epoch: self.epoch() + 1,
});
// As a workaround for
// https://github.com/solana-labs/solana-program-library/issues/374, ensure that the
// spl-token 2 native mint account is owned by the spl-token 2 program.
let store = if let Some(existing_native_mint_account) =
self.get_account_with_fixed_root(&inline_spl_token_v2_0::native_mint::id())
{
if existing_native_mint_account.owner() == &solana_sdk::system_program::id() {
native_mint_account.lamports = existing_native_mint_account.lamports;
true
} else {
false
}
} else {
self.capitalization
.fetch_add(native_mint_account.lamports, Relaxed);
true
};
if store {
self.store_account(
&inline_spl_token_v2_0::native_mint::id(),
&native_mint_account,
);
}
}
}
fn ensure_no_storage_rewards_pool(&mut self) {
let purge_window_epoch = match self.cluster_type() {
ClusterType::Development => false,
// never do this for devnet; we're pristine here. :)
ClusterType::Devnet => false,
// schedule to remove at testnet/tds
ClusterType::Testnet => self.epoch() == 93,
// never do this for stable; we're pristine here. :)
ClusterType::MainnetBeta => false,
};
if purge_window_epoch {
for reward_pubkey in self.rewards_pool_pubkeys.iter() {
if let Some(mut reward_account) = self.get_account_with_fixed_root(&reward_pubkey) {
if reward_account.lamports == u64::MAX {
reward_account.set_lamports(0);
self.store_account(&reward_pubkey, &reward_account);
// Adjust capitalization.... it has been wrapping, reducing the real capitalization by 1-lamport
self.capitalization.fetch_add(1, Relaxed);
info!(
"purged rewards pool accont: {}, new capitalization: {}",
reward_pubkey,
self.capitalization()
);
}
};
}
}
}
fn fix_recent_blockhashes_sysvar_delay(&self) -> bool {
match self.cluster_type() {
ClusterType::Development | ClusterType::Devnet | ClusterType::Testnet => true,
ClusterType::MainnetBeta => self
.feature_set
.is_active(&feature_set::consistent_recent_blockhashes_sysvar::id()),
}
}
}
impl Drop for Bank {
fn drop(&mut self) {
if !self.skip_drop.load(Relaxed) {
if let Some(drop_callback) = self.drop_callback.read().unwrap().0.as_ref() {
drop_callback.callback(self);
} else {
// Default case
// 1. Tests
// 2. At startup when replaying blockstore and there's no
// AccountsBackgroundService to perform cleanups yet.
self.rc.accounts.purge_slot(self.slot());
}
}
}
}
pub fn goto_end_of_slot(bank: &mut Bank) {
let mut tick_hash = bank.last_blockhash();
loop {
tick_hash = hashv(&[&tick_hash.as_ref(), &[42]]);
bank.register_tick(&tick_hash);
if tick_hash == bank.last_blockhash() {
bank.freeze();
return;
}
}
}
fn is_simple_vote_transaction(transaction: &Transaction) -> bool {
if transaction.message.instructions.len() == 1 {
let instruction = &transaction.message.instructions[0];
let program_pubkey =
transaction.message.account_keys[instruction.program_id_index as usize];
if program_pubkey == solana_vote_program::id() {
if let Ok(vote_instruction) = limited_deserialize::<VoteInstruction>(&instruction.data)
{
return matches!(
vote_instruction,
VoteInstruction::Vote(_) | VoteInstruction::VoteSwitch(_, _)
);
}
}
}
false
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::{
accounts_db::SHRINK_RATIO,
accounts_index::{AccountMap, Ancestors, ITER_BATCH_SIZE},
genesis_utils::{
activate_all_features, bootstrap_validator_stake_lamports,
create_genesis_config_with_leader, create_genesis_config_with_vote_accounts,
GenesisConfigInfo, ValidatorVoteKeypairs,
},
native_loader::NativeLoaderError,
status_cache::MAX_CACHE_ENTRIES,
};
use crossbeam_channel::bounded;
use solana_sdk::{
account::Account,
account_utils::StateMut,
clock::{DEFAULT_SLOTS_PER_EPOCH, DEFAULT_TICKS_PER_SLOT},
epoch_schedule::MINIMUM_SLOTS_PER_EPOCH,
feature::Feature,
genesis_config::create_genesis_config,
instruction::{AccountMeta, CompiledInstruction, Instruction, InstructionError},
message::{Message, MessageHeader},
nonce,
poh_config::PohConfig,
process_instruction::InvokeContext,
rent::Rent,
signature::{keypair_from_seed, Keypair, Signer},
system_instruction::{self, SystemError},
system_program,
sysvar::{fees::Fees, rewards::Rewards},
timing::duration_as_s,
};
use solana_stake_program::{
stake_instruction,
stake_state::{self, Authorized, Delegation, Lockup, Stake},
};
use solana_vote_program::{
vote_instruction,
vote_state::{
self, BlockTimestamp, Vote, VoteInit, VoteState, VoteStateVersions, MAX_LOCKOUT_HISTORY,
},
};
use std::{result, thread::Builder, time::Duration};
#[test]
fn test_nonce_rollback_info() {
let nonce_authority = keypair_from_seed(&[0; 32]).unwrap();
let nonce_address = nonce_authority.pubkey();
let fee_calculator = FeeCalculator::new(42);
let state =
nonce::state::Versions::new_current(nonce::State::Initialized(nonce::state::Data {
authority: Pubkey::default(),
blockhash: Hash::new_unique(),
fee_calculator: fee_calculator.clone(),
}));
let nonce_account = AccountSharedData::new_data(43, &state, &system_program::id()).unwrap();
// NonceRollbackPartial create + NonceRollbackInfo impl
let partial = NonceRollbackPartial::new(nonce_address, nonce_account.clone());
assert_eq!(*partial.nonce_address(), nonce_address);
assert_eq!(*partial.nonce_account(), nonce_account);
assert_eq!(partial.fee_calculator(), Some(fee_calculator.clone()));
assert_eq!(partial.fee_account(), None);
let from = keypair_from_seed(&[1; 32]).unwrap();
let from_address = from.pubkey();
let to_address = Pubkey::new_unique();
let instructions = vec![
system_instruction::advance_nonce_account(&nonce_address, &nonce_authority.pubkey()),
system_instruction::transfer(&from_address, &to_address, 42),
];
let message = Message::new(&instructions, Some(&from_address));
let from_account = AccountSharedData::new(44, 0, &Pubkey::default());
let to_account = AccountSharedData::new(45, 0, &Pubkey::default());
let recent_blockhashes_sysvar_account = AccountSharedData::new(4, 0, &Pubkey::default());
let accounts = [
from_account.clone(),
nonce_account.clone(),
to_account.clone(),
recent_blockhashes_sysvar_account.clone(),
];
// NonceRollbackFull create + NonceRollbackInfo impl
let full = NonceRollbackFull::from_partial(partial.clone(), &message, &accounts).unwrap();
assert_eq!(*full.nonce_address(), nonce_address);
assert_eq!(*full.nonce_account(), nonce_account);
assert_eq!(full.fee_calculator(), Some(fee_calculator));
assert_eq!(full.fee_account(), Some(&from_account));
let message = Message::new(&instructions, Some(&nonce_address));
let accounts = [
nonce_account,
from_account,
to_account,
recent_blockhashes_sysvar_account,
];
// Nonce account is fee-payer
let full = NonceRollbackFull::from_partial(partial.clone(), &message, &accounts).unwrap();
assert_eq!(full.fee_account(), None);
// NonceRollbackFull create, fee-payer not in account_keys fails
assert_eq!(
NonceRollbackFull::from_partial(partial, &message, &[]).unwrap_err(),
TransactionError::AccountNotFound,
);
}
#[test]
fn test_bank_unix_timestamp_from_genesis() {
let (genesis_config, _mint_keypair) = create_genesis_config(1);
let mut bank = Arc::new(Bank::new(&genesis_config));
assert_eq!(
genesis_config.creation_time,
bank.unix_timestamp_from_genesis()
);
let slots_per_sec = 1.0
/ (duration_as_s(&genesis_config.poh_config.target_tick_duration)
* genesis_config.ticks_per_slot as f32);
for _i in 0..slots_per_sec as usize + 1 {
bank = Arc::new(new_from_parent(&bank));
}
assert!(bank.unix_timestamp_from_genesis() - genesis_config.creation_time >= 1);
}
#[test]
#[allow(clippy::float_cmp)]
fn test_bank_new() {
let dummy_leader_pubkey = solana_sdk::pubkey::new_rand();
let dummy_leader_stake_lamports = bootstrap_validator_stake_lamports();
let mint_lamports = 10_000;
let GenesisConfigInfo {
mut genesis_config,
mint_keypair,
voting_keypair,
..
} = create_genesis_config_with_leader(
mint_lamports,
&dummy_leader_pubkey,
dummy_leader_stake_lamports,
);
genesis_config.rent = Rent {
lamports_per_byte_year: 5,
exemption_threshold: 1.2,
burn_percent: 5,
};
let bank = Bank::new(&genesis_config);
assert_eq!(bank.get_balance(&mint_keypair.pubkey()), mint_lamports);
assert_eq!(
bank.get_balance(&voting_keypair.pubkey()),
dummy_leader_stake_lamports /* 1 token goes to the vote account associated with dummy_leader_lamports */
);
let rent_account = bank.get_account(&sysvar::rent::id()).unwrap();
let rent = from_account::<sysvar::rent::Rent, _>(&rent_account).unwrap();
assert_eq!(rent.burn_percent, 5);
assert_eq!(rent.exemption_threshold, 1.2);
assert_eq!(rent.lamports_per_byte_year, 5);
}
#[test]
fn test_bank_block_height() {
let (genesis_config, _mint_keypair) = create_genesis_config(1);
let bank0 = Arc::new(Bank::new(&genesis_config));
assert_eq!(bank0.block_height(), 0);
let bank1 = Arc::new(new_from_parent(&bank0));
assert_eq!(bank1.block_height(), 1);
}
#[test]
fn test_bank_update_epoch_stakes() {
impl Bank {
fn epoch_stake_keys(&self) -> Vec<Epoch> {
let mut keys: Vec<Epoch> = self.epoch_stakes.keys().copied().collect();
keys.sort_unstable();
keys
}
fn epoch_stake_key_info(&self) -> (Epoch, Epoch, usize) {
let mut keys: Vec<Epoch> = self.epoch_stakes.keys().copied().collect();
keys.sort_unstable();
(*keys.first().unwrap(), *keys.last().unwrap(), keys.len())
}
}
let (genesis_config, _mint_keypair) = create_genesis_config(100_000);
let mut bank = Bank::new(&genesis_config);
let initial_epochs = bank.epoch_stake_keys();
assert_eq!(initial_epochs, vec![0, 1]);
for existing_epoch in &initial_epochs {
bank.update_epoch_stakes(*existing_epoch);
assert_eq!(bank.epoch_stake_keys(), initial_epochs);
}
for epoch in (initial_epochs.len() as Epoch)..MAX_LEADER_SCHEDULE_STAKES {
bank.update_epoch_stakes(epoch);
assert_eq!(bank.epoch_stakes.len() as Epoch, epoch + 1);
}
assert_eq!(
bank.epoch_stake_key_info(),
(
0,
MAX_LEADER_SCHEDULE_STAKES - 1,
MAX_LEADER_SCHEDULE_STAKES as usize
)
);
bank.update_epoch_stakes(MAX_LEADER_SCHEDULE_STAKES);
assert_eq!(
bank.epoch_stake_key_info(),
(
0,
MAX_LEADER_SCHEDULE_STAKES,
MAX_LEADER_SCHEDULE_STAKES as usize + 1
)
);
bank.update_epoch_stakes(MAX_LEADER_SCHEDULE_STAKES + 1);
assert_eq!(
bank.epoch_stake_key_info(),
(
1,
MAX_LEADER_SCHEDULE_STAKES + 1,
MAX_LEADER_SCHEDULE_STAKES as usize + 1
)
);
}
#[test]
fn test_bank_capitalization() {
let bank0 = Arc::new(Bank::new(&GenesisConfig {
accounts: (0..42)
.map(|_| {
(
solana_sdk::pubkey::new_rand(),
Account::new(42, 0, &Pubkey::default()),
)
})
.collect(),
cluster_type: ClusterType::MainnetBeta,
..GenesisConfig::default()
}));
let sysvar_and_native_proram_delta0 = 10;
assert_eq!(
bank0.capitalization(),
42 * 42 + sysvar_and_native_proram_delta0
);
let bank1 = Bank::new_from_parent(&bank0, &Pubkey::default(), 1);
let sysvar_and_native_proram_delta1 = 2;
assert_eq!(
bank1.capitalization(),
42 * 42 + sysvar_and_native_proram_delta0 + sysvar_and_native_proram_delta1,
);
}
#[test]
fn test_credit_debit_rent_no_side_effect_on_hash() {
solana_logger::setup();
let (mut genesis_config, _mint_keypair) = create_genesis_config(10);
let keypair1: Keypair = Keypair::new();
let keypair2: Keypair = Keypair::new();
let keypair3: Keypair = Keypair::new();
let keypair4: Keypair = Keypair::new();
// Transaction between these two keypairs will fail
let keypair5: Keypair = Keypair::new();
let keypair6: Keypair = Keypair::new();
genesis_config.rent = Rent {
lamports_per_byte_year: 1,
exemption_threshold: 21.0,
burn_percent: 10,
};
let root_bank = Arc::new(Bank::new(&genesis_config));
let bank = Bank::new_from_parent(
&root_bank,
&Pubkey::default(),
years_as_slots(
2.0,
&genesis_config.poh_config.target_tick_duration,
genesis_config.ticks_per_slot,
) as u64,
);
let root_bank_2 = Arc::new(Bank::new(&genesis_config));
let bank_with_success_txs = Bank::new_from_parent(
&root_bank_2,
&Pubkey::default(),
years_as_slots(
2.0,
&genesis_config.poh_config.target_tick_duration,
genesis_config.ticks_per_slot,
) as u64,
);
assert_eq!(bank.last_blockhash(), genesis_config.hash());
// Initialize credit-debit and credit only accounts
let account1 = AccountSharedData::new(264, 0, &Pubkey::default());
let account2 = AccountSharedData::new(264, 1, &Pubkey::default());
let account3 = AccountSharedData::new(264, 0, &Pubkey::default());
let account4 = AccountSharedData::new(264, 1, &Pubkey::default());
let account5 = AccountSharedData::new(10, 0, &Pubkey::default());
let account6 = AccountSharedData::new(10, 1, &Pubkey::default());
bank.store_account(&keypair1.pubkey(), &account1);
bank.store_account(&keypair2.pubkey(), &account2);
bank.store_account(&keypair3.pubkey(), &account3);
bank.store_account(&keypair4.pubkey(), &account4);
bank.store_account(&keypair5.pubkey(), &account5);
bank.store_account(&keypair6.pubkey(), &account6);
bank_with_success_txs.store_account(&keypair1.pubkey(), &account1);
bank_with_success_txs.store_account(&keypair2.pubkey(), &account2);
bank_with_success_txs.store_account(&keypair3.pubkey(), &account3);
bank_with_success_txs.store_account(&keypair4.pubkey(), &account4);
bank_with_success_txs.store_account(&keypair5.pubkey(), &account5);
bank_with_success_txs.store_account(&keypair6.pubkey(), &account6);
// Make native instruction loader rent exempt
let system_program_id = system_program::id();
let mut system_program_account = bank.get_account(&system_program_id).unwrap();
system_program_account.lamports =
bank.get_minimum_balance_for_rent_exemption(system_program_account.data().len());
bank.store_account(&system_program_id, &system_program_account);
bank_with_success_txs.store_account(&system_program_id, &system_program_account);
let t1 =
system_transaction::transfer(&keypair1, &keypair2.pubkey(), 1, genesis_config.hash());
let t2 =
system_transaction::transfer(&keypair3, &keypair4.pubkey(), 1, genesis_config.hash());
let t3 =
system_transaction::transfer(&keypair5, &keypair6.pubkey(), 1, genesis_config.hash());
let res = bank.process_transactions(&[t1.clone(), t2.clone(), t3]);
assert_eq!(res.len(), 3);
assert_eq!(res[0], Ok(()));
assert_eq!(res[1], Ok(()));
assert_eq!(res[2], Err(TransactionError::AccountNotFound));
bank.freeze();
let rwlockguard_bank_hash = bank.hash.read().unwrap();
let bank_hash = rwlockguard_bank_hash.as_ref();
let res = bank_with_success_txs.process_transactions(&[t2, t1]);
assert_eq!(res.len(), 2);
assert_eq!(res[0], Ok(()));
assert_eq!(res[1], Ok(()));
bank_with_success_txs.freeze();
let rwlockguard_bank_with_success_txs_hash = bank_with_success_txs.hash.read().unwrap();
let bank_with_success_txs_hash = rwlockguard_bank_with_success_txs_hash.as_ref();
assert_eq!(bank_with_success_txs_hash, bank_hash);
}
#[derive(Serialize, Deserialize)]
enum MockInstruction {
Deduction,
}
fn mock_process_instruction(
_program_id: &Pubkey,
data: &[u8],
invoke_context: &mut dyn InvokeContext,
) -> result::Result<(), InstructionError> {
let keyed_accounts = invoke_context.get_keyed_accounts()?;
if let Ok(instruction) = bincode::deserialize(data) {
match instruction {
MockInstruction::Deduction => {
keyed_accounts[1]
.account
.borrow_mut()
.checked_add_lamports(1)?;
keyed_accounts[2].account.borrow_mut().lamports -= 1;
Ok(())
}
}
} else {
Err(InstructionError::InvalidInstructionData)
}
}
fn create_mock_transaction(
payer: &Keypair,
keypair1: &Keypair,
keypair2: &Keypair,
read_only_keypair: &Keypair,
mock_program_id: Pubkey,
recent_blockhash: Hash,
) -> Transaction {
let account_metas = vec![
AccountMeta::new(payer.pubkey(), true),
AccountMeta::new(keypair1.pubkey(), true),
AccountMeta::new(keypair2.pubkey(), true),
AccountMeta::new_readonly(read_only_keypair.pubkey(), false),
];
let deduct_instruction = Instruction::new_with_bincode(
mock_program_id,
&MockInstruction::Deduction,
account_metas,
);
Transaction::new_signed_with_payer(
&[deduct_instruction],
Some(&payer.pubkey()),
&[payer, keypair1, keypair2],
recent_blockhash,
)
}
fn store_accounts_for_rent_test(
bank: &Bank,
keypairs: &mut Vec<Keypair>,
mock_program_id: Pubkey,
generic_rent_due_for_system_account: u64,
) {
let mut account_pairs: Vec<(Pubkey, AccountSharedData)> =
Vec::with_capacity(keypairs.len() - 1);
account_pairs.push((
keypairs[0].pubkey(),
AccountSharedData::new(
generic_rent_due_for_system_account + 2,
0,
&Pubkey::default(),
),
));
account_pairs.push((
keypairs[1].pubkey(),
AccountSharedData::new(
generic_rent_due_for_system_account + 2,
0,
&Pubkey::default(),
),
));
account_pairs.push((
keypairs[2].pubkey(),
AccountSharedData::new(
generic_rent_due_for_system_account + 2,
0,
&Pubkey::default(),
),
));
account_pairs.push((
keypairs[3].pubkey(),
AccountSharedData::new(
generic_rent_due_for_system_account + 2,
0,
&Pubkey::default(),
),
));
account_pairs.push((
keypairs[4].pubkey(),
AccountSharedData::new(10, 0, &Pubkey::default()),
));
account_pairs.push((
keypairs[5].pubkey(),
AccountSharedData::new(10, 0, &Pubkey::default()),
));
account_pairs.push((
keypairs[6].pubkey(),
AccountSharedData::new(
(2 * generic_rent_due_for_system_account) + 24,
0,
&Pubkey::default(),
),
));
account_pairs.push((
keypairs[8].pubkey(),
AccountSharedData::new(
generic_rent_due_for_system_account + 2 + 929,
0,
&Pubkey::default(),
),
));
account_pairs.push((
keypairs[9].pubkey(),
AccountSharedData::new(10, 0, &Pubkey::default()),
));
// Feeding to MockProgram to test read only rent behaviour
account_pairs.push((
keypairs[10].pubkey(),
AccountSharedData::new(
generic_rent_due_for_system_account + 3,
0,
&Pubkey::default(),
),
));
account_pairs.push((
keypairs[11].pubkey(),
AccountSharedData::new(generic_rent_due_for_system_account + 3, 0, &mock_program_id),
));
account_pairs.push((
keypairs[12].pubkey(),
AccountSharedData::new(generic_rent_due_for_system_account + 3, 0, &mock_program_id),
));
account_pairs.push((
keypairs[13].pubkey(),
AccountSharedData::new(14, 22, &mock_program_id),
));
for account_pair in account_pairs.iter() {
bank.store_account(&account_pair.0, &account_pair.1);
}
}
fn create_child_bank_for_rent_test(
root_bank: &Arc<Bank>,
genesis_config: &GenesisConfig,
mock_program_id: Pubkey,
) -> Bank {
let mut bank = Bank::new_from_parent(
root_bank,
&Pubkey::default(),
years_as_slots(
2.0,
&genesis_config.poh_config.target_tick_duration,
genesis_config.ticks_per_slot,
) as u64,
);
bank.rent_collector.slots_per_year = 421_812.0;
bank.add_builtin("mock_program", mock_program_id, mock_process_instruction);
bank
}
fn assert_capitalization_diff(bank: &Bank, updater: impl Fn(), asserter: impl Fn(u64, u64)) {
let old = bank.capitalization();
updater();
let new = bank.capitalization();
asserter(old, new);
assert_eq!(bank.capitalization(), bank.calculate_capitalization());
}
#[test]
fn test_store_account_and_update_capitalization_missing() {
let (genesis_config, _mint_keypair) = create_genesis_config(0);
let bank = Bank::new(&genesis_config);
let pubkey = solana_sdk::pubkey::new_rand();
let some_lamports = 400;
let account = AccountSharedData::new(some_lamports, 0, &system_program::id());
assert_capitalization_diff(
&bank,
|| bank.store_account_and_update_capitalization(&pubkey, &account),
|old, new| assert_eq!(old + some_lamports, new),
);
assert_eq!(account, bank.get_account(&pubkey).unwrap());
}
#[test]
fn test_store_account_and_update_capitalization_increased() {
let old_lamports = 400;
let (genesis_config, mint_keypair) = create_genesis_config(old_lamports);
let bank = Bank::new(&genesis_config);
let pubkey = mint_keypair.pubkey();
let new_lamports = 500;
let account = AccountSharedData::new(new_lamports, 0, &system_program::id());
assert_capitalization_diff(
&bank,
|| bank.store_account_and_update_capitalization(&pubkey, &account),
|old, new| assert_eq!(old + 100, new),
);
assert_eq!(account, bank.get_account(&pubkey).unwrap());
}
#[test]
fn test_store_account_and_update_capitalization_decreased() {
let old_lamports = 400;
let (genesis_config, mint_keypair) = create_genesis_config(old_lamports);
let bank = Bank::new(&genesis_config);
let pubkey = mint_keypair.pubkey();
let new_lamports = 100;
let account = AccountSharedData::new(new_lamports, 0, &system_program::id());
assert_capitalization_diff(
&bank,
|| bank.store_account_and_update_capitalization(&pubkey, &account),
|old, new| assert_eq!(old - 300, new),
);
assert_eq!(account, bank.get_account(&pubkey).unwrap());
}
#[test]
fn test_store_account_and_update_capitalization_unchanged() {
let lamports = 400;
let (genesis_config, mint_keypair) = create_genesis_config(lamports);
let bank = Bank::new(&genesis_config);
let pubkey = mint_keypair.pubkey();
let account = AccountSharedData::new(lamports, 1, &system_program::id());
assert_capitalization_diff(
&bank,
|| bank.store_account_and_update_capitalization(&pubkey, &account),
|old, new| assert_eq!(old, new),
);
assert_eq!(account, bank.get_account(&pubkey).unwrap());
}
#[test]
fn test_rent_distribution() {
solana_logger::setup();
let bootstrap_validator_pubkey = solana_sdk::pubkey::new_rand();
let bootstrap_validator_stake_lamports = 30;
let mut genesis_config = create_genesis_config_with_leader(
10,
&bootstrap_validator_pubkey,
bootstrap_validator_stake_lamports,
)
.genesis_config;
genesis_config.epoch_schedule = EpochSchedule::custom(
MINIMUM_SLOTS_PER_EPOCH,
genesis_config.epoch_schedule.leader_schedule_slot_offset,
false,
);
genesis_config.rent = Rent {
lamports_per_byte_year: 1,
exemption_threshold: 2.0,
burn_percent: 10,
};
let rent = Rent::free();
let validator_1_pubkey = solana_sdk::pubkey::new_rand();
let validator_1_stake_lamports = 20;
let validator_1_staking_keypair = Keypair::new();
let validator_1_voting_keypair = Keypair::new();
let validator_1_vote_account = vote_state::create_account(
&validator_1_voting_keypair.pubkey(),
&validator_1_pubkey,
0,
validator_1_stake_lamports,
);
let validator_1_stake_account = stake_state::create_account(
&validator_1_staking_keypair.pubkey(),
&validator_1_voting_keypair.pubkey(),
&validator_1_vote_account,
&rent,
validator_1_stake_lamports,
);
genesis_config.accounts.insert(
validator_1_pubkey,
Account::new(42, 0, &system_program::id()),
);
genesis_config.accounts.insert(
validator_1_staking_keypair.pubkey(),
Account::from(validator_1_stake_account),
);
genesis_config.accounts.insert(
validator_1_voting_keypair.pubkey(),
Account::from(validator_1_vote_account),
);
let validator_2_pubkey = solana_sdk::pubkey::new_rand();
let validator_2_stake_lamports = 20;
let validator_2_staking_keypair = Keypair::new();
let validator_2_voting_keypair = Keypair::new();
let validator_2_vote_account = vote_state::create_account(
&validator_2_voting_keypair.pubkey(),
&validator_2_pubkey,
0,
validator_2_stake_lamports,
);
let validator_2_stake_account = stake_state::create_account(
&validator_2_staking_keypair.pubkey(),
&validator_2_voting_keypair.pubkey(),
&validator_2_vote_account,
&rent,
validator_2_stake_lamports,
);
genesis_config.accounts.insert(
validator_2_pubkey,
Account::new(42, 0, &system_program::id()),
);
genesis_config.accounts.insert(
validator_2_staking_keypair.pubkey(),
Account::from(validator_2_stake_account),
);
genesis_config.accounts.insert(
validator_2_voting_keypair.pubkey(),
Account::from(validator_2_vote_account),
);
let validator_3_pubkey = solana_sdk::pubkey::new_rand();
let validator_3_stake_lamports = 30;
let validator_3_staking_keypair = Keypair::new();
let validator_3_voting_keypair = Keypair::new();
let validator_3_vote_account = vote_state::create_account(
&validator_3_voting_keypair.pubkey(),
&validator_3_pubkey,
0,
validator_3_stake_lamports,
);
let validator_3_stake_account = stake_state::create_account(
&validator_3_staking_keypair.pubkey(),
&validator_3_voting_keypair.pubkey(),
&validator_3_vote_account,
&rent,
validator_3_stake_lamports,
);
genesis_config.accounts.insert(
validator_3_pubkey,
Account::new(42, 0, &system_program::id()),
);
genesis_config.accounts.insert(
validator_3_staking_keypair.pubkey(),
Account::from(validator_3_stake_account),
);
genesis_config.accounts.insert(
validator_3_voting_keypair.pubkey(),
Account::from(validator_3_vote_account),
);
genesis_config.rent = Rent {
lamports_per_byte_year: 1,
exemption_threshold: 10.0,
burn_percent: 10,
};
let mut bank = Bank::new(&genesis_config);
// Enable rent collection
bank.rent_collector.epoch = 5;
bank.rent_collector.slots_per_year = 192.0;
let payer = Keypair::new();
let payer_account = AccountSharedData::new(400, 0, &system_program::id());
bank.store_account_and_update_capitalization(&payer.pubkey(), &payer_account);
let payee = Keypair::new();
let payee_account = AccountSharedData::new(70, 1, &system_program::id());
bank.store_account_and_update_capitalization(&payee.pubkey(), &payee_account);
let bootstrap_validator_initial_balance = bank.get_balance(&bootstrap_validator_pubkey);
let tx = system_transaction::transfer(&payer, &payee.pubkey(), 180, genesis_config.hash());
let result = bank.process_transaction(&tx);
assert_eq!(result, Ok(()));
let mut total_rent_deducted = 0;
// 400 - 128(Rent) - 180(Transfer)
assert_eq!(bank.get_balance(&payer.pubkey()), 92);
total_rent_deducted += 128;
// 70 - 70(Rent) + 180(Transfer) - 21(Rent)
assert_eq!(bank.get_balance(&payee.pubkey()), 159);
total_rent_deducted += 70 + 21;
let previous_capitalization = bank.capitalization.load(Relaxed);
bank.freeze();
assert_eq!(bank.collected_rent.load(Relaxed), total_rent_deducted);
let burned_portion =
total_rent_deducted * u64::from(bank.rent_collector.rent.burn_percent) / 100;
let rent_to_be_distributed = total_rent_deducted - burned_portion;
let bootstrap_validator_portion =
((bootstrap_validator_stake_lamports * rent_to_be_distributed) as f64 / 100.0) as u64
+ 1; // Leftover lamport
assert_eq!(
bank.get_balance(&bootstrap_validator_pubkey),
bootstrap_validator_portion + bootstrap_validator_initial_balance
);
// Since, validator 1 and validator 2 has equal smallest stake, it comes down to comparison
// between their pubkey.
let tweak_1 = if validator_1_pubkey > validator_2_pubkey {
1
} else {
0
};
let validator_1_portion =
((validator_1_stake_lamports * rent_to_be_distributed) as f64 / 100.0) as u64 + tweak_1;
assert_eq!(
bank.get_balance(&validator_1_pubkey),
validator_1_portion + 42 - tweak_1,
);
// Since, validator 1 and validator 2 has equal smallest stake, it comes down to comparison
// between their pubkey.
let tweak_2 = if validator_2_pubkey > validator_1_pubkey {
1
} else {
0
};
let validator_2_portion =
((validator_2_stake_lamports * rent_to_be_distributed) as f64 / 100.0) as u64 + tweak_2;
assert_eq!(
bank.get_balance(&validator_2_pubkey),
validator_2_portion + 42 - tweak_2,
);
let validator_3_portion =
((validator_3_stake_lamports * rent_to_be_distributed) as f64 / 100.0) as u64 + 1;
assert_eq!(
bank.get_balance(&validator_3_pubkey),
validator_3_portion + 42
);
let current_capitalization = bank.capitalization.load(Relaxed);
let sysvar_and_native_proram_delta = 1;
assert_eq!(
previous_capitalization - current_capitalization + sysvar_and_native_proram_delta,
burned_portion
);
assert!(bank.calculate_and_verify_capitalization());
assert_eq!(
rent_to_be_distributed,
bank.rewards
.read()
.unwrap()
.iter()
.map(|(address, reward)| {
assert_eq!(reward.reward_type, RewardType::Rent);
if *address == validator_2_pubkey {
assert_eq!(reward.post_balance, validator_2_portion + 42 - tweak_2);
} else if *address == validator_3_pubkey {
assert_eq!(reward.post_balance, validator_3_portion + 42);
}
reward.lamports as u64
})
.sum::<u64>()
);
}
#[test]
fn test_distribute_rent_to_validators_overflow() {
solana_logger::setup();
// These values are taken from the real cluster (testnet)
const RENT_TO_BE_DISTRIBUTED: u64 = 120_525;
const VALIDATOR_STAKE: u64 = 374_999_998_287_840;
let validator_pubkey = solana_sdk::pubkey::new_rand();
let mut genesis_config =
create_genesis_config_with_leader(10, &validator_pubkey, VALIDATOR_STAKE)
.genesis_config;
let bank = Bank::new(&genesis_config);
let old_validator_lamports = bank.get_balance(&validator_pubkey);
bank.distribute_rent_to_validators(bank.vote_accounts(), RENT_TO_BE_DISTRIBUTED);
let new_validator_lamports = bank.get_balance(&validator_pubkey);
assert_eq!(
new_validator_lamports,
old_validator_lamports + RENT_TO_BE_DISTRIBUTED
);
genesis_config
.accounts
.remove(&feature_set::no_overflow_rent_distribution::id())
.unwrap();
let bank = std::panic::AssertUnwindSafe(Bank::new(&genesis_config));
let old_validator_lamports = bank.get_balance(&validator_pubkey);
let new_validator_lamports = std::panic::catch_unwind(|| {
bank.distribute_rent_to_validators(bank.vote_accounts(), RENT_TO_BE_DISTRIBUTED);
bank.get_balance(&validator_pubkey)
});
if let Ok(new_validator_lamports) = new_validator_lamports {
info!("asserting overflowing incorrect rent distribution");
assert_ne!(
new_validator_lamports,
old_validator_lamports + RENT_TO_BE_DISTRIBUTED
);
} else {
info!("NOT-asserting overflowing incorrect rent distribution");
}
}
#[test]
fn test_rent_exempt_executable_account() {
let (mut genesis_config, mint_keypair) = create_genesis_config(100_000);
genesis_config.rent = Rent {
lamports_per_byte_year: 1,
exemption_threshold: 1000.0,
burn_percent: 10,
};
let root_bank = Arc::new(Bank::new(&genesis_config));
let bank = create_child_bank_for_rent_test(
&root_bank,
&genesis_config,
solana_sdk::pubkey::new_rand(),
);
let account_pubkey = solana_sdk::pubkey::new_rand();
let account_balance = 1;
let mut account =
AccountSharedData::new(account_balance, 0, &solana_sdk::pubkey::new_rand());
account.executable = true;
bank.store_account(&account_pubkey, &account);
let transfer_lamports = 1;
let tx = system_transaction::transfer(
&mint_keypair,
&account_pubkey,
transfer_lamports,
genesis_config.hash(),
);
assert_eq!(
bank.process_transaction(&tx),
Err(TransactionError::InstructionError(
0,
InstructionError::ExecutableLamportChange
))
);
assert_eq!(bank.get_balance(&account_pubkey), account_balance);
}
#[test]
#[allow(clippy::cognitive_complexity)]
fn test_rent_complex() {
solana_logger::setup();
let mock_program_id = Pubkey::new(&[2u8; 32]);
let (mut genesis_config, _mint_keypair) = create_genesis_config(10);
let mut keypairs: Vec<Keypair> = Vec::with_capacity(14);
for _i in 0..14 {
keypairs.push(Keypair::new());
}
genesis_config.rent = Rent {
lamports_per_byte_year: 1,
exemption_threshold: 1000.0,
burn_percent: 10,
};
let root_bank = Bank::new(&genesis_config);
// until we completely transition to the eager rent collection,
// we must ensure lazy rent collection doens't get broken!
root_bank.restore_old_behavior_for_fragile_tests();
let root_bank = Arc::new(root_bank);
let bank = create_child_bank_for_rent_test(&root_bank, &genesis_config, mock_program_id);
assert_eq!(bank.last_blockhash(), genesis_config.hash());
let slots_elapsed: u64 = (0..=bank.epoch)
.map(|epoch| {
bank.rent_collector
.epoch_schedule
.get_slots_in_epoch(epoch + 1)
})
.sum();
let (generic_rent_due_for_system_account, _) = bank.rent_collector.rent.due(
bank.get_minimum_balance_for_rent_exemption(0) - 1,
0,
slots_elapsed as f64 / bank.rent_collector.slots_per_year,
);
store_accounts_for_rent_test(
&bank,
&mut keypairs,
mock_program_id,
generic_rent_due_for_system_account,
);
let magic_rent_number = 131; // yuck, derive this value programmatically one day
let t1 = system_transaction::transfer(
&keypairs[0],
&keypairs[1].pubkey(),
1,
genesis_config.hash(),
);
let t2 = system_transaction::transfer(
&keypairs[2],
&keypairs[3].pubkey(),
1,
genesis_config.hash(),
);
let t3 = system_transaction::transfer(
&keypairs[4],
&keypairs[5].pubkey(),
1,
genesis_config.hash(),
);
let t4 = system_transaction::transfer(
&keypairs[6],
&keypairs[7].pubkey(),
generic_rent_due_for_system_account + 1,
genesis_config.hash(),
);
let t5 = system_transaction::transfer(
&keypairs[8],
&keypairs[9].pubkey(),
929,
genesis_config.hash(),
);
let t6 = create_mock_transaction(
&keypairs[10],
&keypairs[11],
&keypairs[12],
&keypairs[13],
mock_program_id,
genesis_config.hash(),
);
let res = bank.process_transactions(&[t6, t5, t1, t2, t3, t4]);
assert_eq!(res.len(), 6);
assert_eq!(res[0], Ok(()));
assert_eq!(res[1], Ok(()));
assert_eq!(res[2], Ok(()));
assert_eq!(res[3], Ok(()));
assert_eq!(res[4], Err(TransactionError::AccountNotFound));
assert_eq!(res[5], Ok(()));
bank.freeze();
let mut rent_collected = 0;
// 48992 - generic_rent_due_for_system_account(Rent) - 1(transfer)
assert_eq!(bank.get_balance(&keypairs[0].pubkey()), 1);
rent_collected += generic_rent_due_for_system_account;
// 48992 - generic_rent_due_for_system_account(Rent) + 1(transfer)
assert_eq!(bank.get_balance(&keypairs[1].pubkey()), 3);
rent_collected += generic_rent_due_for_system_account;
// 48992 - generic_rent_due_for_system_account(Rent) - 1(transfer)
assert_eq!(bank.get_balance(&keypairs[2].pubkey()), 1);
rent_collected += generic_rent_due_for_system_account;
// 48992 - generic_rent_due_for_system_account(Rent) + 1(transfer)
assert_eq!(bank.get_balance(&keypairs[3].pubkey()), 3);
rent_collected += generic_rent_due_for_system_account;
// No rent deducted
assert_eq!(bank.get_balance(&keypairs[4].pubkey()), 10);
assert_eq!(bank.get_balance(&keypairs[5].pubkey()), 10);
// 98004 - generic_rent_due_for_system_account(Rent) - 48991(transfer)
assert_eq!(bank.get_balance(&keypairs[6].pubkey()), 23);
rent_collected += generic_rent_due_for_system_account;
// 0 + 48990(transfer) - magic_rent_number(Rent)
assert_eq!(
bank.get_balance(&keypairs[7].pubkey()),
generic_rent_due_for_system_account + 1 - magic_rent_number
);
// Epoch should be updated
// Rent deducted on store side
let account8 = bank.get_account(&keypairs[7].pubkey()).unwrap();
// Epoch should be set correctly.
assert_eq!(account8.rent_epoch(), bank.epoch + 1);
rent_collected += magic_rent_number;
// 49921 - generic_rent_due_for_system_account(Rent) - 929(Transfer)
assert_eq!(bank.get_balance(&keypairs[8].pubkey()), 2);
rent_collected += generic_rent_due_for_system_account;
let account10 = bank.get_account(&keypairs[9].pubkey()).unwrap();
// Account was overwritten at load time, since it didn't have sufficient balance to pay rent
// Then, at store time we deducted `magic_rent_number` rent for the current epoch, once it has balance
assert_eq!(account10.rent_epoch(), bank.epoch + 1);
// account data is blank now
assert_eq!(account10.data().len(), 0);
// 10 - 10(Rent) + 929(Transfer) - magic_rent_number(Rent)
assert_eq!(account10.lamports, 929 - magic_rent_number);
rent_collected += magic_rent_number + 10;
// 48993 - generic_rent_due_for_system_account(Rent)
assert_eq!(bank.get_balance(&keypairs[10].pubkey()), 3);
rent_collected += generic_rent_due_for_system_account;
// 48993 - generic_rent_due_for_system_account(Rent) + 1(Addition by program)
assert_eq!(bank.get_balance(&keypairs[11].pubkey()), 4);
rent_collected += generic_rent_due_for_system_account;
// 48993 - generic_rent_due_for_system_account(Rent) - 1(Deduction by program)
assert_eq!(bank.get_balance(&keypairs[12].pubkey()), 2);
rent_collected += generic_rent_due_for_system_account;
// No rent for read-only account
assert_eq!(bank.get_balance(&keypairs[13].pubkey()), 14);
// Bank's collected rent should be sum of rent collected from all accounts
assert_eq!(bank.collected_rent.load(Relaxed), rent_collected);
}
#[test]
fn test_rent_eager_across_epoch_without_gap() {
let (genesis_config, _mint_keypair) = create_genesis_config(1);
let mut bank = Arc::new(Bank::new(&genesis_config));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 32)]);
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 1, 32)]);
for _ in 2..32 {
bank = Arc::new(new_from_parent(&bank));
}
assert_eq!(bank.rent_collection_partitions(), vec![(30, 31, 32)]);
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 64)]);
}
#[test]
fn test_rent_eager_across_epoch_with_full_gap() {
let (mut genesis_config, _mint_keypair) = create_genesis_config(1);
activate_all_features(&mut genesis_config);
let mut bank = Arc::new(Bank::new(&genesis_config));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 32)]);
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 1, 32)]);
for _ in 2..15 {
bank = Arc::new(new_from_parent(&bank));
}
assert_eq!(bank.rent_collection_partitions(), vec![(13, 14, 32)]);
bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 49));
assert_eq!(
bank.rent_collection_partitions(),
vec![(14, 31, 32), (0, 0, 64), (0, 17, 64)]
);
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.rent_collection_partitions(), vec![(17, 18, 64)]);
}
#[test]
fn test_rent_eager_across_epoch_with_half_gap() {
let (mut genesis_config, _mint_keypair) = create_genesis_config(1);
activate_all_features(&mut genesis_config);
let mut bank = Arc::new(Bank::new(&genesis_config));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 32)]);
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 1, 32)]);
for _ in 2..15 {
bank = Arc::new(new_from_parent(&bank));
}
assert_eq!(bank.rent_collection_partitions(), vec![(13, 14, 32)]);
bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 32));
assert_eq!(
bank.rent_collection_partitions(),
vec![(14, 31, 32), (0, 0, 64)]
);
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 1, 64)]);
}
#[test]
#[allow(clippy::cognitive_complexity)]
fn test_rent_eager_across_epoch_without_gap_under_multi_epoch_cycle() {
let leader_pubkey = solana_sdk::pubkey::new_rand();
let leader_lamports = 3;
let mut genesis_config =
create_genesis_config_with_leader(5, &leader_pubkey, leader_lamports).genesis_config;
genesis_config.cluster_type = ClusterType::MainnetBeta;
const SLOTS_PER_EPOCH: u64 = MINIMUM_SLOTS_PER_EPOCH as u64;
const LEADER_SCHEDULE_SLOT_OFFSET: u64 = SLOTS_PER_EPOCH * 3 - 3;
genesis_config.epoch_schedule =
EpochSchedule::custom(SLOTS_PER_EPOCH, LEADER_SCHEDULE_SLOT_OFFSET, false);
let mut bank = Arc::new(Bank::new(&genesis_config));
assert_eq!(DEFAULT_SLOTS_PER_EPOCH, 432_000);
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (0, 0));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 432_000)]);
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (0, 1));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 1, 432_000)]);
for _ in 2..32 {
bank = Arc::new(new_from_parent(&bank));
}
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (0, 31));
assert_eq!(bank.rent_collection_partitions(), vec![(30, 31, 432_000)]);
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (1, 0));
assert_eq!(bank.rent_collection_partitions(), vec![(31, 32, 432_000)]);
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (1, 1));
assert_eq!(bank.rent_collection_partitions(), vec![(32, 33, 432_000)]);
bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 1000));
bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 1001));
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (31, 9));
assert_eq!(
bank.rent_collection_partitions(),
vec![(1000, 1001, 432_000)]
);
bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 431_998));
bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 431_999));
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (13499, 31));
assert_eq!(
bank.rent_collection_partitions(),
vec![(431_998, 431_999, 432_000)]
);
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (13500, 0));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 432_000)]);
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (13500, 1));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 1, 432_000)]);
}
#[test]
fn test_rent_eager_across_epoch_with_gap_under_multi_epoch_cycle() {
let leader_pubkey = solana_sdk::pubkey::new_rand();
let leader_lamports = 3;
let mut genesis_config =
create_genesis_config_with_leader(5, &leader_pubkey, leader_lamports).genesis_config;
genesis_config.cluster_type = ClusterType::MainnetBeta;
const SLOTS_PER_EPOCH: u64 = MINIMUM_SLOTS_PER_EPOCH as u64;
const LEADER_SCHEDULE_SLOT_OFFSET: u64 = SLOTS_PER_EPOCH * 3 - 3;
genesis_config.epoch_schedule =
EpochSchedule::custom(SLOTS_PER_EPOCH, LEADER_SCHEDULE_SLOT_OFFSET, false);
let mut bank = Arc::new(Bank::new(&genesis_config));
assert_eq!(DEFAULT_SLOTS_PER_EPOCH, 432_000);
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (0, 0));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 432_000)]);
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (0, 1));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 1, 432_000)]);
for _ in 2..19 {
bank = Arc::new(new_from_parent(&bank));
}
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (0, 18));
assert_eq!(bank.rent_collection_partitions(), vec![(17, 18, 432_000)]);
bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 44));
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (1, 12));
assert_eq!(
bank.rent_collection_partitions(),
vec![(18, 31, 432_000), (31, 31, 432_000), (31, 44, 432_000)]
);
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (1, 13));
assert_eq!(bank.rent_collection_partitions(), vec![(44, 45, 432_000)]);
bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 431_993));
bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 432_011));
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (13500, 11));
assert_eq!(
bank.rent_collection_partitions(),
vec![
(431_993, 431_999, 432_000),
(0, 0, 432_000),
(0, 11, 432_000)
]
);
}
#[test]
fn test_rent_eager_with_warmup_epochs_under_multi_epoch_cycle() {
let leader_pubkey = solana_sdk::pubkey::new_rand();
let leader_lamports = 3;
let mut genesis_config =
create_genesis_config_with_leader(5, &leader_pubkey, leader_lamports).genesis_config;
genesis_config.cluster_type = ClusterType::MainnetBeta;
const SLOTS_PER_EPOCH: u64 = MINIMUM_SLOTS_PER_EPOCH as u64 * 8;
const LEADER_SCHEDULE_SLOT_OFFSET: u64 = SLOTS_PER_EPOCH * 3 - 3;
genesis_config.epoch_schedule =
EpochSchedule::custom(SLOTS_PER_EPOCH, LEADER_SCHEDULE_SLOT_OFFSET, true);
let mut bank = Arc::new(Bank::new(&genesis_config));
assert_eq!(DEFAULT_SLOTS_PER_EPOCH, 432_000);
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32);
assert_eq!(bank.first_normal_epoch(), 3);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (0, 0));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 32)]);
bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 222));
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 128);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (2, 127));
assert_eq!(bank.rent_collection_partitions(), vec![(126, 127, 128)]);
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 256);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (3, 0));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 431_872)]);
assert_eq!(431_872 % bank.get_slots_in_epoch(bank.epoch()), 0);
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 256);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (3, 1));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 1, 431_872)]);
bank = Arc::new(Bank::new_from_parent(
&bank,
&Pubkey::default(),
431_872 + 223 - 1,
));
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 256);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (1689, 255));
assert_eq!(
bank.rent_collection_partitions(),
vec![(431_870, 431_871, 431_872)]
);
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 256);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (1690, 0));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 431_872)]);
}
#[test]
fn test_rent_eager_under_fixed_cycle_for_development() {
solana_logger::setup();
let leader_pubkey = solana_sdk::pubkey::new_rand();
let leader_lamports = 3;
let mut genesis_config =
create_genesis_config_with_leader(5, &leader_pubkey, leader_lamports).genesis_config;
const SLOTS_PER_EPOCH: u64 = MINIMUM_SLOTS_PER_EPOCH as u64 * 8;
const LEADER_SCHEDULE_SLOT_OFFSET: u64 = SLOTS_PER_EPOCH * 3 - 3;
genesis_config.epoch_schedule =
EpochSchedule::custom(SLOTS_PER_EPOCH, LEADER_SCHEDULE_SLOT_OFFSET, true);
let mut bank = Arc::new(Bank::new(&genesis_config));
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32);
assert_eq!(bank.first_normal_epoch(), 3);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (0, 0));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 432_000)]);
bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 222));
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 128);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (2, 127));
assert_eq!(bank.rent_collection_partitions(), vec![(222, 223, 432_000)]);
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 256);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (3, 0));
assert_eq!(bank.rent_collection_partitions(), vec![(223, 224, 432_000)]);
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 256);
assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (3, 1));
assert_eq!(bank.rent_collection_partitions(), vec![(224, 225, 432_000)]);
bank = Arc::new(Bank::new_from_parent(
&bank,
&Pubkey::default(),
432_000 - 2,
));
bank = Arc::new(new_from_parent(&bank));
assert_eq!(
bank.rent_collection_partitions(),
vec![(431_998, 431_999, 432_000)]
);
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 432_000)]);
bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.rent_collection_partitions(), vec![(0, 1, 432_000)]);
bank = Arc::new(Bank::new_from_parent(
&bank,
&Pubkey::default(),
864_000 - 20,
));
bank = Arc::new(Bank::new_from_parent(
&bank,
&Pubkey::default(),
864_000 + 39,
));
assert_eq!(
bank.rent_collection_partitions(),
vec![
(431_980, 431_999, 432_000),
(0, 0, 432_000),
(0, 39, 432_000)
]
);
}
#[test]
fn test_rent_eager_pubkey_range_minimal() {
let range = Bank::pubkey_range_from_partition((0, 0, 1));
assert_eq!(
range,
Pubkey::new_from_array([0x00; 32])..=Pubkey::new_from_array([0xff; 32])
);
}
#[test]
fn test_rent_eager_pubkey_range_maximum() {
let max = !0;
let range = Bank::pubkey_range_from_partition((0, 0, max));
assert_eq!(
range,
Pubkey::new_from_array([0x00; 32])
..=Pubkey::new_from_array([
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
])
);
let range = Bank::pubkey_range_from_partition((0, 1, max));
assert_eq!(
range,
Pubkey::new_from_array([
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
])
..=Pubkey::new_from_array([
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
])
);
let range = Bank::pubkey_range_from_partition((max - 3, max - 2, max));
assert_eq!(
range,
Pubkey::new_from_array([
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
])
..=Pubkey::new_from_array([
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
])
);
let range = Bank::pubkey_range_from_partition((max - 2, max - 1, max));
assert_eq!(
range,
Pubkey::new_from_array([
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
])
..=Pubkey::new_from_array([
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
])
);
fn should_cause_overflow(partition_count: u64) -> bool {
// Check `partition_width = (u64::max_value() + 1) / partition_count` is exact and
// does not have a remainder.
// This way, `partition_width * partition_count == (u64::max_value() + 1)`,
// so the test actually tests for overflow
(u64::max_value() - partition_count + 1) % partition_count == 0
}
let max_exact = 64;
// Make sure `max_exact` divides evenly when calculating `calculate_partition_width`
assert!(should_cause_overflow(max_exact));
// Make sure `max_inexact` doesn't divide evenly when calculating `calculate_partition_width`
let max_inexact = 10;
assert!(!should_cause_overflow(max_inexact));
for max in &[max_exact, max_inexact] {
let range = Bank::pubkey_range_from_partition((max - 1, max - 1, *max));
assert_eq!(
range,
Pubkey::new_from_array([
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
])
..=Pubkey::new_from_array([
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
])
);
}
}
fn map_to_test_bad_range() -> AccountMap<Pubkey, i8> {
let mut map: AccountMap<Pubkey, i8> = AccountMap::new();
// when empty, AccountMap (= std::collections::BTreeMap) doesn't sanitize given range...
map.insert(solana_sdk::pubkey::new_rand(), 1);
map
}
#[test]
#[should_panic(expected = "range start is greater than range end in BTreeMap")]
fn test_rent_eager_bad_range() {
let test_map = map_to_test_bad_range();
test_map.range(
Pubkey::new_from_array([
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01,
])
..=Pubkey::new_from_array([
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
]),
);
}
#[test]
fn test_rent_eager_pubkey_range_noop_range() {
let test_map = map_to_test_bad_range();
let range = Bank::pubkey_range_from_partition((0, 0, 3));
assert_eq!(
range,
Pubkey::new_from_array([
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
])
..=Pubkey::new_from_array([
0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x54, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
])
);
test_map.range(range);
let range = Bank::pubkey_range_from_partition((1, 1, 3));
assert_eq!(
range,
Pubkey::new_from_array([
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
])
..=Pubkey::new_from_array([
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00
])
);
test_map.range(range);
let range = Bank::pubkey_range_from_partition((2, 2, 3));
assert_eq!(
range,
Pubkey::new_from_array([
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff
])
..=Pubkey::new_from_array([
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
])
);
test_map.range(range);
}
#[test]
fn test_rent_eager_pubkey_range_dividable() {
let test_map = map_to_test_bad_range();
let range = Bank::pubkey_range_from_partition((0, 0, 2));
assert_eq!(
range,
Pubkey::new_from_array([
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
])
..=Pubkey::new_from_array([
0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
])
);
test_map.range(range);
let range = Bank::pubkey_range_from_partition((0, 1, 2));
assert_eq!(
range,
Pubkey::new_from_array([
0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
])
..=Pubkey::new_from_array([
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
])
);
test_map.range(range);
}
#[test]
fn test_rent_eager_pubkey_range_not_dividable() {
solana_logger::setup();
let test_map = map_to_test_bad_range();
let range = Bank::pubkey_range_from_partition((0, 0, 3));
assert_eq!(
range,
Pubkey::new_from_array([
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
])
..=Pubkey::new_from_array([
0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x54, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
])
);
test_map.range(range);
let range = Bank::pubkey_range_from_partition((0, 1, 3));
assert_eq!(
range,
Pubkey::new_from_array([
0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
])
..=Pubkey::new_from_array([
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xa9, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
])
);
test_map.range(range);
let range = Bank::pubkey_range_from_partition((1, 2, 3));
assert_eq!(
range,
Pubkey::new_from_array([
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
])
..=Pubkey::new_from_array([
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
])
);
test_map.range(range);
}
#[test]
fn test_rent_eager_pubkey_range_gap() {
solana_logger::setup();
let test_map = map_to_test_bad_range();
let range = Bank::pubkey_range_from_partition((120, 1023, 12345));
assert_eq!(
range,
Pubkey::new_from_array([
0x02, 0x82, 0x5a, 0x89, 0xd1, 0xac, 0x58, 0x9c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
])
..=Pubkey::new_from_array([
0x15, 0x3c, 0x1d, 0xf1, 0xc6, 0x39, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
])
);
test_map.range(range);
}
impl Bank {
fn slots_by_pubkey(&self, pubkey: &Pubkey, ancestors: &Ancestors) -> Vec<Slot> {
let (locked_entry, _) = self
.rc
.accounts
.accounts_db
.accounts_index
.get(&pubkey, Some(&ancestors), None)
.unwrap();
locked_entry
.slot_list()
.iter()
.map(|(slot, _)| *slot)
.collect::<Vec<Slot>>()
}
}
#[test]
fn test_rent_eager_collect_rent_in_partition() {
solana_logger::setup();
let (mut genesis_config, _mint_keypair) = create_genesis_config(1);
activate_all_features(&mut genesis_config);
let zero_lamport_pubkey = solana_sdk::pubkey::new_rand();
let rent_due_pubkey = solana_sdk::pubkey::new_rand();
let rent_exempt_pubkey = solana_sdk::pubkey::new_rand();
let mut bank = Arc::new(Bank::new(&genesis_config));
let zero_lamports = 0;
let little_lamports = 1234;
let large_lamports = 123_456_789;
let rent_collected = 22;
bank.store_account(
&zero_lamport_pubkey,
&AccountSharedData::new(zero_lamports, 0, &Pubkey::default()),
);
bank.store_account(
&rent_due_pubkey,
&AccountSharedData::new(little_lamports, 0, &Pubkey::default()),
);
bank.store_account(
&rent_exempt_pubkey,
&AccountSharedData::new(large_lamports, 0, &Pubkey::default()),
);
let genesis_slot = 0;
let some_slot = 1000;
let ancestors = vec![(some_slot, 0), (0, 1)].into_iter().collect();
bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), some_slot));
assert_eq!(bank.collected_rent.load(Relaxed), 0);
assert_eq!(
bank.get_account(&rent_due_pubkey).unwrap().lamports,
little_lamports
);
assert_eq!(bank.get_account(&rent_due_pubkey).unwrap().rent_epoch(), 0);
assert_eq!(
bank.slots_by_pubkey(&rent_due_pubkey, &ancestors),
vec![genesis_slot]
);
assert_eq!(
bank.slots_by_pubkey(&rent_exempt_pubkey, &ancestors),
vec![genesis_slot]
);
assert_eq!(
bank.slots_by_pubkey(&zero_lamport_pubkey, &ancestors),
vec![genesis_slot]
);
bank.collect_rent_in_partition((0, 0, 1)); // all range
// unrelated 1-lamport account exists
assert_eq!(bank.collected_rent.load(Relaxed), rent_collected + 1);
assert_eq!(
bank.get_account(&rent_due_pubkey).unwrap().lamports,
little_lamports - rent_collected
);
assert_eq!(bank.get_account(&rent_due_pubkey).unwrap().rent_epoch(), 6);
assert_eq!(
bank.get_account(&rent_exempt_pubkey).unwrap().lamports,
large_lamports
);
assert_eq!(
bank.get_account(&rent_exempt_pubkey).unwrap().rent_epoch(),
5
);
assert_eq!(
bank.slots_by_pubkey(&rent_due_pubkey, &ancestors),
vec![genesis_slot, some_slot]
);
assert_eq!(
bank.slots_by_pubkey(&rent_exempt_pubkey, &ancestors),
vec![genesis_slot, some_slot]
);
assert_eq!(
bank.slots_by_pubkey(&zero_lamport_pubkey, &ancestors),
vec![genesis_slot]
);
}
#[test]
fn test_rent_eager_collect_rent_zero_lamport_deterministic() {
solana_logger::setup();
let (genesis_config, _mint_keypair) = create_genesis_config(1);
let zero_lamport_pubkey = solana_sdk::pubkey::new_rand();
let genesis_bank1 = Arc::new(Bank::new(&genesis_config));
let genesis_bank2 = Arc::new(Bank::new(&genesis_config));
let bank1_with_zero = Arc::new(new_from_parent(&genesis_bank1));
let bank1_without_zero = Arc::new(new_from_parent(&genesis_bank2));
let zero_lamports = 0;
let account = AccountSharedData::new(zero_lamports, 0, &Pubkey::default());
bank1_with_zero.store_account(&zero_lamport_pubkey, &account);
bank1_without_zero.store_account(&zero_lamport_pubkey, &account);
bank1_without_zero
.rc
.accounts
.accounts_db
.accounts_index
.add_root(genesis_bank1.slot() + 1, false);
bank1_without_zero
.rc
.accounts
.accounts_db
.accounts_index
.purge_roots(&zero_lamport_pubkey);
let some_slot = 1000;
let bank2_with_zero = Arc::new(Bank::new_from_parent(
&bank1_with_zero,
&Pubkey::default(),
some_slot,
));
let bank2_without_zero = Arc::new(Bank::new_from_parent(
&bank1_without_zero,
&Pubkey::default(),
some_slot,
));
let hash1_with_zero = bank1_with_zero.hash();
let hash1_without_zero = bank1_without_zero.hash();
assert_eq!(hash1_with_zero, hash1_without_zero);
assert_ne!(hash1_with_zero, Hash::default());
bank2_with_zero.collect_rent_in_partition((0, 0, 1)); // all
bank2_without_zero.collect_rent_in_partition((0, 0, 1)); // all
bank2_with_zero.freeze();
let hash2_with_zero = bank2_with_zero.hash();
bank2_without_zero.freeze();
let hash2_without_zero = bank2_without_zero.hash();
assert_eq!(hash2_with_zero, hash2_without_zero);
assert_ne!(hash2_with_zero, Hash::default());
}
#[test]
fn test_bank_update_vote_stake_rewards() {
solana_logger::setup();
// create a bank that ticks really slowly...
let bank0 = Arc::new(Bank::new(&GenesisConfig {
accounts: (0..42)
.map(|_| {
(
solana_sdk::pubkey::new_rand(),
Account::new(1_000_000_000, 0, &Pubkey::default()),
)
})
.collect(),
// set it up so the first epoch is a full year long
poh_config: PohConfig {
target_tick_duration: Duration::from_secs(
SECONDS_PER_YEAR as u64
/ MINIMUM_SLOTS_PER_EPOCH as u64
/ DEFAULT_TICKS_PER_SLOT,
),
hashes_per_tick: None,
target_tick_count: None,
},
cluster_type: ClusterType::MainnetBeta,
..GenesisConfig::default()
}));
// enable lazy rent collection because this test depends on rent-due accounts
// not being eagerly-collected for exact rewards calculation
bank0.restore_old_behavior_for_fragile_tests();
let sysvar_and_native_proram_delta0 = 10;
assert_eq!(
bank0.capitalization(),
42 * 1_000_000_000 + sysvar_and_native_proram_delta0
);
assert!(bank0.rewards.read().unwrap().is_empty());
let ((vote_id, mut vote_account), (stake_id, stake_account)) =
crate::stakes::tests::create_staked_node_accounts(1_0000);
// set up accounts
bank0.store_account_and_update_capitalization(&stake_id, &stake_account);
// generate some rewards
let mut vote_state = Some(VoteState::from(&vote_account).unwrap());
for i in 0..MAX_LOCKOUT_HISTORY + 42 {
if let Some(v) = vote_state.as_mut() {
v.process_slot_vote_unchecked(i as u64)
}
let versioned = VoteStateVersions::Current(Box::new(vote_state.take().unwrap()));
VoteState::to(&versioned, &mut vote_account).unwrap();
bank0.store_account_and_update_capitalization(&vote_id, &vote_account);
match versioned {
VoteStateVersions::Current(v) => {
vote_state = Some(*v);
}
_ => panic!("Has to be of type Current"),
};
}
bank0.store_account_and_update_capitalization(&vote_id, &vote_account);
let validator_points: u128 = bank0
.stake_delegation_accounts(&mut null_tracer())
.iter()
.flat_map(|(_vote_pubkey, (stake_group, vote_account))| {
stake_group
.iter()
.map(move |(_stake_pubkey, stake_account)| (stake_account, vote_account))
})
.map(|(stake_account, vote_account)| {
stake_state::calculate_points(&stake_account, &vote_account, None, true)
.unwrap_or(0)
})
.sum();
// put a child bank in epoch 1, which calls update_rewards()...
let bank1 = Bank::new_from_parent(
&bank0,
&Pubkey::default(),
bank0.get_slots_in_epoch(bank0.epoch()) + 1,
);
// verify that there's inflation
assert_ne!(bank1.capitalization(), bank0.capitalization());
// verify the inflation is represented in validator_points *
let sysvar_and_native_proram_delta1 = 2;
let paid_rewards =
bank1.capitalization() - bank0.capitalization() - sysvar_and_native_proram_delta1;
let rewards = bank1
.get_account(&sysvar::rewards::id())
.map(|account| from_account::<Rewards, _>(&account).unwrap())
.unwrap();
// verify the stake and vote accounts are the right size
assert!(
((bank1.get_balance(&stake_id) - stake_account.lamports + bank1.get_balance(&vote_id)
- vote_account.lamports) as f64
- rewards.validator_point_value * validator_points as f64)
.abs()
< 1.0
);
// verify the rewards are the right size
let allocated_rewards = rewards.validator_point_value * validator_points as f64;
assert!((allocated_rewards - paid_rewards as f64).abs() < 1.0); // rounding, truncating
// verify validator rewards show up in bank1.rewards vector
assert_eq!(
*bank1.rewards.read().unwrap(),
vec![(
stake_id,
RewardInfo {
reward_type: RewardType::Staking,
lamports: (rewards.validator_point_value * validator_points as f64) as i64,
post_balance: bank1.get_balance(&stake_id),
}
)]
);
bank1.freeze();
assert!(bank1.calculate_and_verify_capitalization());
}
fn do_test_bank_update_rewards_determinism() -> u64 {
// create a bank that ticks really slowly...
let bank = Arc::new(Bank::new(&GenesisConfig {
accounts: (0..42)
.map(|_| {
(
solana_sdk::pubkey::new_rand(),
Account::new(1_000_000_000, 0, &Pubkey::default()),
)
})
.collect(),
// set it up so the first epoch is a full year long
poh_config: PohConfig {
target_tick_duration: Duration::from_secs(
SECONDS_PER_YEAR as u64
/ MINIMUM_SLOTS_PER_EPOCH as u64
/ DEFAULT_TICKS_PER_SLOT,
),
hashes_per_tick: None,
target_tick_count: None,
},
cluster_type: ClusterType::MainnetBeta,
..GenesisConfig::default()
}));
// enable lazy rent collection because this test depends on rent-due accounts
// not being eagerly-collected for exact rewards calculation
bank.restore_old_behavior_for_fragile_tests();
let sysvar_and_native_proram_delta = 10;
assert_eq!(
bank.capitalization(),
42 * 1_000_000_000 + sysvar_and_native_proram_delta
);
assert!(bank.rewards.read().unwrap().is_empty());
let vote_id = solana_sdk::pubkey::new_rand();
let mut vote_account =
vote_state::create_account(&vote_id, &solana_sdk::pubkey::new_rand(), 50, 100);
let (stake_id1, stake_account1) = crate::stakes::tests::create_stake_account(123, &vote_id);
let (stake_id2, stake_account2) = crate::stakes::tests::create_stake_account(456, &vote_id);
// set up accounts
bank.store_account_and_update_capitalization(&stake_id1, &stake_account1);
bank.store_account_and_update_capitalization(&stake_id2, &stake_account2);
// generate some rewards
let mut vote_state = Some(VoteState::from(&vote_account).unwrap());
for i in 0..MAX_LOCKOUT_HISTORY + 42 {
if let Some(v) = vote_state.as_mut() {
v.process_slot_vote_unchecked(i as u64)
}
let versioned = VoteStateVersions::Current(Box::new(vote_state.take().unwrap()));
VoteState::to(&versioned, &mut vote_account).unwrap();
bank.store_account_and_update_capitalization(&vote_id, &vote_account);
match versioned {
VoteStateVersions::Current(v) => {
vote_state = Some(*v);
}
_ => panic!("Has to be of type Current"),
};
}
bank.store_account_and_update_capitalization(&vote_id, &vote_account);
// put a child bank in epoch 1, which calls update_rewards()...
let bank1 = Bank::new_from_parent(
&bank,
&Pubkey::default(),
bank.get_slots_in_epoch(bank.epoch()) + 1,
);
// verify that there's inflation
assert_ne!(bank1.capitalization(), bank.capitalization());
bank1.freeze();
assert!(bank1.calculate_and_verify_capitalization());
// verify voting and staking rewards are recorded
let rewards = bank1.rewards.read().unwrap();
rewards
.iter()
.find(|(_address, reward)| reward.reward_type == RewardType::Voting)
.unwrap();
rewards
.iter()
.find(|(_address, reward)| reward.reward_type == RewardType::Staking)
.unwrap();
bank1.capitalization()
}
#[test]
fn test_bank_update_rewards_determinism() {
solana_logger::setup();
// The same reward should be distributed given same credits
let expected_capitalization = do_test_bank_update_rewards_determinism();
// Repeat somewhat large number of iterations to expose possible different behavior
// depending on the randomly-seeded HashMap ordering
for _ in 0..30 {
let actual_capitalization = do_test_bank_update_rewards_determinism();
assert_eq!(actual_capitalization, expected_capitalization);
}
}
// Test that purging 0 lamports accounts works.
#[test]
fn test_purge_empty_accounts() {
solana_logger::setup();
let (genesis_config, mint_keypair) = create_genesis_config(500_000);
let parent = Arc::new(Bank::new(&genesis_config));
let mut bank = parent;
for _ in 0..10 {
let blockhash = bank.last_blockhash();
let pubkey = solana_sdk::pubkey::new_rand();
let tx = system_transaction::transfer(&mint_keypair, &pubkey, 0, blockhash);
bank.process_transaction(&tx).unwrap();
bank.freeze();
bank.squash();
bank = Arc::new(new_from_parent(&bank));
}
bank.freeze();
bank.squash();
bank.force_flush_accounts_cache();
let hash = bank.update_accounts_hash();
bank.clean_accounts(false);
assert_eq!(bank.update_accounts_hash(), hash);
let bank0 = Arc::new(new_from_parent(&bank));
let blockhash = bank.last_blockhash();
let keypair = Keypair::new();
let tx = system_transaction::transfer(&mint_keypair, &keypair.pubkey(), 10, blockhash);
bank0.process_transaction(&tx).unwrap();
let bank1 = Arc::new(new_from_parent(&bank0));
let pubkey = solana_sdk::pubkey::new_rand();
let blockhash = bank.last_blockhash();
let tx = system_transaction::transfer(&keypair, &pubkey, 10, blockhash);
bank1.process_transaction(&tx).unwrap();
assert_eq!(bank0.get_account(&keypair.pubkey()).unwrap().lamports, 10);
assert_eq!(bank1.get_account(&keypair.pubkey()), None);
info!("bank0 purge");
let hash = bank0.update_accounts_hash();
bank0.clean_accounts(false);
assert_eq!(bank0.update_accounts_hash(), hash);
assert_eq!(bank0.get_account(&keypair.pubkey()).unwrap().lamports, 10);
assert_eq!(bank1.get_account(&keypair.pubkey()), None);
info!("bank1 purge");
bank1.clean_accounts(false);
assert_eq!(bank0.get_account(&keypair.pubkey()).unwrap().lamports, 10);
assert_eq!(bank1.get_account(&keypair.pubkey()), None);
assert!(bank0.verify_bank_hash());
// Squash and then verify hash_internal value
bank0.freeze();
bank0.squash();
assert!(bank0.verify_bank_hash());
bank1.freeze();
bank1.squash();
bank1.update_accounts_hash();
assert!(bank1.verify_bank_hash());
// keypair should have 0 tokens on both forks
assert_eq!(bank0.get_account(&keypair.pubkey()), None);
assert_eq!(bank1.get_account(&keypair.pubkey()), None);
bank1.force_flush_accounts_cache();
bank1.clean_accounts(false);
assert!(bank1.verify_bank_hash());
}
#[test]
fn test_two_payments_to_one_party() {
let (genesis_config, mint_keypair) = create_genesis_config(10_000);
let pubkey = solana_sdk::pubkey::new_rand();
let bank = Bank::new(&genesis_config);
assert_eq!(bank.last_blockhash(), genesis_config.hash());
bank.transfer(1_000, &mint_keypair, &pubkey).unwrap();
assert_eq!(bank.get_balance(&pubkey), 1_000);
bank.transfer(500, &mint_keypair, &pubkey).unwrap();
assert_eq!(bank.get_balance(&pubkey), 1_500);
assert_eq!(bank.transaction_count(), 2);
}
#[test]
fn test_one_source_two_tx_one_batch() {
let (genesis_config, mint_keypair) = create_genesis_config(1);
let key1 = solana_sdk::pubkey::new_rand();
let key2 = solana_sdk::pubkey::new_rand();
let bank = Bank::new(&genesis_config);
assert_eq!(bank.last_blockhash(), genesis_config.hash());
let t1 = system_transaction::transfer(&mint_keypair, &key1, 1, genesis_config.hash());
let t2 = system_transaction::transfer(&mint_keypair, &key2, 1, genesis_config.hash());
let res = bank.process_transactions(&[t1.clone(), t2.clone()]);
assert_eq!(res.len(), 2);
assert_eq!(res[0], Ok(()));
assert_eq!(res[1], Err(TransactionError::AccountInUse));
assert_eq!(bank.get_balance(&mint_keypair.pubkey()), 0);
assert_eq!(bank.get_balance(&key1), 1);
assert_eq!(bank.get_balance(&key2), 0);
assert_eq!(bank.get_signature_status(&t1.signatures[0]), Some(Ok(())));
// TODO: Transactions that fail to pay a fee could be dropped silently.
// Non-instruction errors don't get logged in the signature cache
assert_eq!(bank.get_signature_status(&t2.signatures[0]), None);
}
#[test]
fn test_one_tx_two_out_atomic_fail() {
let (genesis_config, mint_keypair) = create_genesis_config(1);
let key1 = solana_sdk::pubkey::new_rand();
let key2 = solana_sdk::pubkey::new_rand();
let bank = Bank::new(&genesis_config);
let instructions =
system_instruction::transfer_many(&mint_keypair.pubkey(), &[(key1, 1), (key2, 1)]);
let message = Message::new(&instructions, Some(&mint_keypair.pubkey()));
let tx = Transaction::new(&[&mint_keypair], message, genesis_config.hash());
assert_eq!(
bank.process_transaction(&tx).unwrap_err(),
TransactionError::InstructionError(1, SystemError::ResultWithNegativeLamports.into())
);
assert_eq!(bank.get_balance(&mint_keypair.pubkey()), 1);
assert_eq!(bank.get_balance(&key1), 0);
assert_eq!(bank.get_balance(&key2), 0);
}
#[test]
fn test_one_tx_two_out_atomic_pass() {
let (genesis_config, mint_keypair) = create_genesis_config(2);
let key1 = solana_sdk::pubkey::new_rand();
let key2 = solana_sdk::pubkey::new_rand();
let bank = Bank::new(&genesis_config);
let instructions =
system_instruction::transfer_many(&mint_keypair.pubkey(), &[(key1, 1), (key2, 1)]);
let message = Message::new(&instructions, Some(&mint_keypair.pubkey()));
let tx = Transaction::new(&[&mint_keypair], message, genesis_config.hash());
bank.process_transaction(&tx).unwrap();
assert_eq!(bank.get_balance(&mint_keypair.pubkey()), 0);
assert_eq!(bank.get_balance(&key1), 1);
assert_eq!(bank.get_balance(&key2), 1);
}
// This test demonstrates that fees are paid even when a program fails.
#[test]
fn test_detect_failed_duplicate_transactions() {
let (mut genesis_config, mint_keypair) = create_genesis_config(2);
genesis_config.fee_rate_governor = FeeRateGovernor::new(1, 0);
let bank = Bank::new(&genesis_config);
let dest = Keypair::new();
// source with 0 program context
let tx =
system_transaction::transfer(&mint_keypair, &dest.pubkey(), 2, genesis_config.hash());
let signature = tx.signatures[0];
assert!(!bank.has_signature(&signature));
assert_eq!(
bank.process_transaction(&tx),
Err(TransactionError::InstructionError(
0,
SystemError::ResultWithNegativeLamports.into(),
))
);
// The lamports didn't move, but the from address paid the transaction fee.
assert_eq!(bank.get_balance(&dest.pubkey()), 0);
// This should be the original balance minus the transaction fee.
assert_eq!(bank.get_balance(&mint_keypair.pubkey()), 1);
}
#[test]
fn test_account_not_found() {
solana_logger::setup();
let (genesis_config, mint_keypair) = create_genesis_config(0);
let bank = Bank::new(&genesis_config);
let keypair = Keypair::new();
assert_eq!(
bank.transfer(1, &keypair, &mint_keypair.pubkey()),
Err(TransactionError::AccountNotFound)
);
assert_eq!(bank.transaction_count(), 0);
}
#[test]
fn test_insufficient_funds() {
let (genesis_config, mint_keypair) = create_genesis_config(11_000);
let bank = Bank::new(&genesis_config);
let pubkey = solana_sdk::pubkey::new_rand();
bank.transfer(1_000, &mint_keypair, &pubkey).unwrap();
assert_eq!(bank.transaction_count(), 1);
assert_eq!(bank.get_balance(&pubkey), 1_000);
assert_eq!(
bank.transfer(10_001, &mint_keypair, &pubkey),
Err(TransactionError::InstructionError(
0,
SystemError::ResultWithNegativeLamports.into(),
))
);
assert_eq!(bank.transaction_count(), 1);
let mint_pubkey = mint_keypair.pubkey();
assert_eq!(bank.get_balance(&mint_pubkey), 10_000);
assert_eq!(bank.get_balance(&pubkey), 1_000);
}
#[test]
fn test_transfer_to_newb() {
solana_logger::setup();
let (genesis_config, mint_keypair) = create_genesis_config(10_000);
let bank = Bank::new(&genesis_config);
let pubkey = solana_sdk::pubkey::new_rand();
bank.transfer(500, &mint_keypair, &pubkey).unwrap();
assert_eq!(bank.get_balance(&pubkey), 500);
}
#[test]
fn test_transfer_to_sysvar() {
solana_logger::setup();
let (genesis_config, mint_keypair) = create_genesis_config(10_000);
let bank = Arc::new(Bank::new(&genesis_config));
let normal_pubkey = solana_sdk::pubkey::new_rand();
let sysvar_pubkey = sysvar::clock::id();
assert_eq!(bank.get_balance(&normal_pubkey), 0);
assert_eq!(bank.get_balance(&sysvar_pubkey), 1);
bank.transfer(500, &mint_keypair, &normal_pubkey).unwrap();
bank.transfer(500, &mint_keypair, &sysvar_pubkey).unwrap();
assert_eq!(bank.get_balance(&normal_pubkey), 500);
assert_eq!(bank.get_balance(&sysvar_pubkey), 501);
let bank = Arc::new(new_from_parent(&bank));
assert_eq!(bank.get_balance(&normal_pubkey), 500);
assert_eq!(bank.get_balance(&sysvar_pubkey), 501);
}
#[test]
fn test_bank_deposit() {
let (genesis_config, _mint_keypair) = create_genesis_config(100);
let bank = Bank::new(&genesis_config);
// Test new account
let key = Keypair::new();
let new_balance = bank.deposit(&key.pubkey(), 10);
assert_eq!(new_balance, 10);
assert_eq!(bank.get_balance(&key.pubkey()), 10);
// Existing account
let new_balance = bank.deposit(&key.pubkey(), 3);
assert_eq!(new_balance, 13);
assert_eq!(bank.get_balance(&key.pubkey()), 13);
}
#[test]
fn test_bank_withdraw() {
let (genesis_config, _mint_keypair) = create_genesis_config(100);
let bank = Bank::new(&genesis_config);
// Test no account
let key = Keypair::new();
assert_eq!(
bank.withdraw(&key.pubkey(), 10),
Err(TransactionError::AccountNotFound)
);
bank.deposit(&key.pubkey(), 3);
assert_eq!(bank.get_balance(&key.pubkey()), 3);
// Low balance
assert_eq!(
bank.withdraw(&key.pubkey(), 10),
Err(TransactionError::InsufficientFundsForFee)
);
// Enough balance
assert_eq!(bank.withdraw(&key.pubkey(), 2), Ok(()));
assert_eq!(bank.get_balance(&key.pubkey()), 1);
}
#[test]
fn test_bank_withdraw_from_nonce_account() {
let (mut genesis_config, _mint_keypair) = create_genesis_config(100_000);
genesis_config.rent.lamports_per_byte_year = 42;
let bank = Bank::new(&genesis_config);
let min_balance = bank.get_minimum_balance_for_rent_exemption(nonce::State::size());
let nonce = Keypair::new();
let nonce_account = AccountSharedData::new_data(
min_balance + 42,
&nonce::state::Versions::new_current(nonce::State::Initialized(
nonce::state::Data::default(),
)),
&system_program::id(),
)
.unwrap();
bank.store_account(&nonce.pubkey(), &nonce_account);
assert_eq!(bank.get_balance(&nonce.pubkey()), min_balance + 42);
// Resulting in non-zero, but sub-min_balance balance fails
assert_eq!(
bank.withdraw(&nonce.pubkey(), min_balance / 2),
Err(TransactionError::InsufficientFundsForFee)
);
assert_eq!(bank.get_balance(&nonce.pubkey()), min_balance + 42);
// Resulting in exactly rent-exempt balance succeeds
bank.withdraw(&nonce.pubkey(), 42).unwrap();
assert_eq!(bank.get_balance(&nonce.pubkey()), min_balance);
// Account closure fails
assert_eq!(
bank.withdraw(&nonce.pubkey(), min_balance),
Err(TransactionError::InsufficientFundsForFee),
);
}
#[test]
fn test_bank_tx_fee() {
solana_logger::setup();
let arbitrary_transfer_amount = 42;
let mint = arbitrary_transfer_amount * 100;
let leader = solana_sdk::pubkey::new_rand();
let GenesisConfigInfo {
mut genesis_config,
mint_keypair,
..
} = create_genesis_config_with_leader(mint, &leader, 3);
genesis_config.fee_rate_governor = FeeRateGovernor::new(4, 0); // something divisible by 2
let expected_fee_paid = genesis_config
.fee_rate_governor
.create_fee_calculator()
.lamports_per_signature;
let (expected_fee_collected, expected_fee_burned) =
genesis_config.fee_rate_governor.burn(expected_fee_paid);
let mut bank = Bank::new(&genesis_config);
let capitalization = bank.capitalization();
let key = Keypair::new();
let tx = system_transaction::transfer(
&mint_keypair,
&key.pubkey(),
arbitrary_transfer_amount,
bank.last_blockhash(),
);
let initial_balance = bank.get_balance(&leader);
assert_eq!(bank.process_transaction(&tx), Ok(()));
assert_eq!(bank.get_balance(&key.pubkey()), arbitrary_transfer_amount);
assert_eq!(
bank.get_balance(&mint_keypair.pubkey()),
mint - arbitrary_transfer_amount - expected_fee_paid
);
assert_eq!(bank.get_balance(&leader), initial_balance);
goto_end_of_slot(&mut bank);
assert_eq!(bank.signature_count(), 1);
assert_eq!(
bank.get_balance(&leader),
initial_balance + expected_fee_collected
); // Leader collects fee after the bank is frozen
// verify capitalization
let sysvar_and_native_proram_delta = 1;
assert_eq!(
capitalization - expected_fee_burned + sysvar_and_native_proram_delta,
bank.capitalization()
);
assert_eq!(
*bank.rewards.read().unwrap(),
vec![(
leader,
RewardInfo {
reward_type: RewardType::Fee,
lamports: expected_fee_collected as i64,
post_balance: initial_balance + expected_fee_collected,
}
)]
);
// Verify that an InstructionError collects fees, too
let mut bank = Bank::new_from_parent(&Arc::new(bank), &leader, 1);
let mut tx =
system_transaction::transfer(&mint_keypair, &key.pubkey(), 1, bank.last_blockhash());
// Create a bogus instruction to system_program to cause an instruction error
tx.message.instructions[0].data[0] = 40;
bank.process_transaction(&tx)
.expect_err("instruction error");
assert_eq!(bank.get_balance(&key.pubkey()), arbitrary_transfer_amount); // no change
assert_eq!(
bank.get_balance(&mint_keypair.pubkey()),
mint - arbitrary_transfer_amount - 2 * expected_fee_paid
); // mint_keypair still pays a fee
goto_end_of_slot(&mut bank);
assert_eq!(bank.signature_count(), 1);
// Profit! 2 transaction signatures processed at 3 lamports each
assert_eq!(
bank.get_balance(&leader),
initial_balance + 2 * expected_fee_collected
);
assert_eq!(
*bank.rewards.read().unwrap(),
vec![(
leader,
RewardInfo {
reward_type: RewardType::Fee,
lamports: expected_fee_collected as i64,
post_balance: initial_balance + 2 * expected_fee_collected,
}
)]
);
}
#[test]
fn test_bank_blockhash_fee_schedule() {
//solana_logger::setup();
let leader = solana_sdk::pubkey::new_rand();
let GenesisConfigInfo {
mut genesis_config,
mint_keypair,
..
} = create_genesis_config_with_leader(1_000_000, &leader, 3);
genesis_config
.fee_rate_governor
.target_lamports_per_signature = 1000;
genesis_config.fee_rate_governor.target_signatures_per_slot = 1;
let mut bank = Bank::new(&genesis_config);
goto_end_of_slot(&mut bank);
let (cheap_blockhash, cheap_fee_calculator) = bank.last_blockhash_with_fee_calculator();
assert_eq!(cheap_fee_calculator.lamports_per_signature, 0);
let mut bank = Bank::new_from_parent(&Arc::new(bank), &leader, 1);
goto_end_of_slot(&mut bank);
let (expensive_blockhash, expensive_fee_calculator) =
bank.last_blockhash_with_fee_calculator();
assert!(
cheap_fee_calculator.lamports_per_signature
< expensive_fee_calculator.lamports_per_signature
);
let bank = Bank::new_from_parent(&Arc::new(bank), &leader, 2);
// Send a transfer using cheap_blockhash
let key = Keypair::new();
let initial_mint_balance = bank.get_balance(&mint_keypair.pubkey());
let tx = system_transaction::transfer(&mint_keypair, &key.pubkey(), 1, cheap_blockhash);
assert_eq!(bank.process_transaction(&tx), Ok(()));
assert_eq!(bank.get_balance(&key.pubkey()), 1);
assert_eq!(
bank.get_balance(&mint_keypair.pubkey()),
initial_mint_balance - 1 - cheap_fee_calculator.lamports_per_signature
);
// Send a transfer using expensive_blockhash
let key = Keypair::new();
let initial_mint_balance = bank.get_balance(&mint_keypair.pubkey());
let tx = system_transaction::transfer(&mint_keypair, &key.pubkey(), 1, expensive_blockhash);
assert_eq!(bank.process_transaction(&tx), Ok(()));
assert_eq!(bank.get_balance(&key.pubkey()), 1);
assert_eq!(
bank.get_balance(&mint_keypair.pubkey()),
initial_mint_balance - 1 - expensive_fee_calculator.lamports_per_signature
);
}
#[test]
fn test_filter_program_errors_and_collect_fee() {
let leader = solana_sdk::pubkey::new_rand();
let GenesisConfigInfo {
mut genesis_config,
mint_keypair,
..
} = create_genesis_config_with_leader(100, &leader, 3);
genesis_config.fee_rate_governor = FeeRateGovernor::new(2, 0);
let bank = Bank::new(&genesis_config);
let key = Keypair::new();
let tx1 =
system_transaction::transfer(&mint_keypair, &key.pubkey(), 2, genesis_config.hash());
let tx2 =
system_transaction::transfer(&mint_keypair, &key.pubkey(), 5, genesis_config.hash());
let results = vec![
(Ok(()), None),
(
Err(TransactionError::InstructionError(
1,
SystemError::ResultWithNegativeLamports.into(),
)),
None,
),
];
let initial_balance = bank.get_balance(&leader);
let results = bank.filter_program_errors_and_collect_fee([tx1, tx2].iter(), &results);
bank.freeze();
assert_eq!(
bank.get_balance(&leader),
initial_balance
+ bank
.fee_rate_governor
.burn(bank.fee_calculator.lamports_per_signature * 2)
.0
);
assert_eq!(results[0], Ok(()));
assert_eq!(results[1], Ok(()));
}
#[test]
fn test_debits_before_credits() {
let (genesis_config, mint_keypair) = create_genesis_config(2);
let bank = Bank::new(&genesis_config);
let keypair = Keypair::new();
let tx0 = system_transaction::transfer(
&mint_keypair,
&keypair.pubkey(),
2,
genesis_config.hash(),
);
let tx1 = system_transaction::transfer(
&keypair,
&mint_keypair.pubkey(),
1,
genesis_config.hash(),
);
let txs = vec![tx0, tx1];
let results = bank.process_transactions(&txs);
assert!(results[1].is_err());
// Assert bad transactions aren't counted.
assert_eq!(bank.transaction_count(), 1);
}
#[test]
fn test_readonly_accounts() {
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config_with_leader(500, &solana_sdk::pubkey::new_rand(), 0);
let bank = Bank::new(&genesis_config);
let vote_pubkey0 = solana_sdk::pubkey::new_rand();
let vote_pubkey1 = solana_sdk::pubkey::new_rand();
let vote_pubkey2 = solana_sdk::pubkey::new_rand();
let authorized_voter = Keypair::new();
let payer0 = Keypair::new();
let payer1 = Keypair::new();
// Create vote accounts
let vote_account0 =
vote_state::create_account(&vote_pubkey0, &authorized_voter.pubkey(), 0, 100);
let vote_account1 =
vote_state::create_account(&vote_pubkey1, &authorized_voter.pubkey(), 0, 100);
let vote_account2 =
vote_state::create_account(&vote_pubkey2, &authorized_voter.pubkey(), 0, 100);
bank.store_account(&vote_pubkey0, &vote_account0);
bank.store_account(&vote_pubkey1, &vote_account1);
bank.store_account(&vote_pubkey2, &vote_account2);
// Fund payers
bank.transfer(10, &mint_keypair, &payer0.pubkey()).unwrap();
bank.transfer(10, &mint_keypair, &payer1.pubkey()).unwrap();
bank.transfer(1, &mint_keypair, &authorized_voter.pubkey())
.unwrap();
let vote = Vote::new(vec![1], Hash::default());
let ix0 = vote_instruction::vote(&vote_pubkey0, &authorized_voter.pubkey(), vote.clone());
let tx0 = Transaction::new_signed_with_payer(
&[ix0],
Some(&payer0.pubkey()),
&[&payer0, &authorized_voter],
bank.last_blockhash(),
);
let ix1 = vote_instruction::vote(&vote_pubkey1, &authorized_voter.pubkey(), vote.clone());
let tx1 = Transaction::new_signed_with_payer(
&[ix1],
Some(&payer1.pubkey()),
&[&payer1, &authorized_voter],
bank.last_blockhash(),
);
let txs = vec![tx0, tx1];
let results = bank.process_transactions(&txs);
// If multiple transactions attempt to read the same account, they should succeed.
// Vote authorized_voter and sysvar accounts are given read-only handling
assert_eq!(results[0], Ok(()));
assert_eq!(results[1], Ok(()));
let ix0 = vote_instruction::vote(&vote_pubkey2, &authorized_voter.pubkey(), vote);
let tx0 = Transaction::new_signed_with_payer(
&[ix0],
Some(&payer0.pubkey()),
&[&payer0, &authorized_voter],
bank.last_blockhash(),
);
let tx1 = system_transaction::transfer(
&authorized_voter,
&solana_sdk::pubkey::new_rand(),
1,
bank.last_blockhash(),
);
let txs = vec![tx0, tx1];
let results = bank.process_transactions(&txs);
// However, an account may not be locked as read-only and writable at the same time.
assert_eq!(results[0], Ok(()));
assert_eq!(results[1], Err(TransactionError::AccountInUse));
}
#[test]
fn test_interleaving_locks() {
let (genesis_config, mint_keypair) = create_genesis_config(3);
let bank = Bank::new(&genesis_config);
let alice = Keypair::new();
let bob = Keypair::new();
let tx1 =
system_transaction::transfer(&mint_keypair, &alice.pubkey(), 1, genesis_config.hash());
let pay_alice = vec![tx1];
let lock_result = bank.prepare_batch(pay_alice.iter());
let results_alice = bank
.load_execute_and_commit_transactions(
&lock_result,
MAX_PROCESSING_AGE,
false,
false,
false,
&mut ExecuteTimings::default(),
)
.0
.fee_collection_results;
assert_eq!(results_alice[0], Ok(()));
// try executing an interleaved transfer twice
assert_eq!(
bank.transfer(1, &mint_keypair, &bob.pubkey()),
Err(TransactionError::AccountInUse)
);
// the second time should fail as well
// this verifies that `unlock_accounts` doesn't unlock `AccountInUse` accounts
assert_eq!(
bank.transfer(1, &mint_keypair, &bob.pubkey()),
Err(TransactionError::AccountInUse)
);
drop(lock_result);
assert!(bank.transfer(2, &mint_keypair, &bob.pubkey()).is_ok());
}
#[test]
fn test_readonly_relaxed_locks() {
let (genesis_config, _) = create_genesis_config(3);
let bank = Bank::new(&genesis_config);
let key0 = Keypair::new();
let key1 = Keypair::new();
let key2 = Keypair::new();
let key3 = solana_sdk::pubkey::new_rand();
let message = Message {
header: MessageHeader {
num_required_signatures: 1,
num_readonly_signed_accounts: 0,
num_readonly_unsigned_accounts: 1,
},
account_keys: vec![key0.pubkey(), key3],
recent_blockhash: Hash::default(),
instructions: vec![],
};
let tx = Transaction::new(&[&key0], message, genesis_config.hash());
let txs = vec![tx];
let batch0 = bank.prepare_batch(txs.iter());
assert!(batch0.lock_results()[0].is_ok());
// Try locking accounts, locking a previously read-only account as writable
// should fail
let message = Message {
header: MessageHeader {
num_required_signatures: 1,
num_readonly_signed_accounts: 0,
num_readonly_unsigned_accounts: 0,
},
account_keys: vec![key1.pubkey(), key3],
recent_blockhash: Hash::default(),
instructions: vec![],
};
let tx = Transaction::new(&[&key1], message, genesis_config.hash());
let txs = vec![tx];
let batch1 = bank.prepare_batch(txs.iter());
assert!(batch1.lock_results()[0].is_err());
// Try locking a previously read-only account a 2nd time; should succeed
let message = Message {
header: MessageHeader {
num_required_signatures: 1,
num_readonly_signed_accounts: 0,
num_readonly_unsigned_accounts: 1,
},
account_keys: vec![key2.pubkey(), key3],
recent_blockhash: Hash::default(),
instructions: vec![],
};
let tx = Transaction::new(&[&key2], message, genesis_config.hash());
let txs = vec![tx];
let batch2 = bank.prepare_batch(txs.iter());
assert!(batch2.lock_results()[0].is_ok());
}
#[test]
fn test_bank_invalid_account_index() {
let (genesis_config, mint_keypair) = create_genesis_config(1);
let keypair = Keypair::new();
let bank = Bank::new(&genesis_config);
let tx = system_transaction::transfer(
&mint_keypair,
&keypair.pubkey(),
1,
genesis_config.hash(),
);
let mut tx_invalid_program_index = tx.clone();
tx_invalid_program_index.message.instructions[0].program_id_index = 42;
assert_eq!(
bank.process_transaction(&tx_invalid_program_index),
Err(TransactionError::SanitizeFailure)
);
let mut tx_invalid_account_index = tx;
tx_invalid_account_index.message.instructions[0].accounts[0] = 42;
assert_eq!(
bank.process_transaction(&tx_invalid_account_index),
Err(TransactionError::SanitizeFailure)
);
}
#[test]
fn test_bank_pay_to_self() {
let (genesis_config, mint_keypair) = create_genesis_config(1);
let key1 = Keypair::new();
let bank = Bank::new(&genesis_config);
bank.transfer(1, &mint_keypair, &key1.pubkey()).unwrap();
assert_eq!(bank.get_balance(&key1.pubkey()), 1);
let tx = system_transaction::transfer(&key1, &key1.pubkey(), 1, genesis_config.hash());
let _res = bank.process_transaction(&tx);
assert_eq!(bank.get_balance(&key1.pubkey()), 1);
bank.get_signature_status(&tx.signatures[0])
.unwrap()
.unwrap();
}
fn new_from_parent(parent: &Arc<Bank>) -> Bank {
Bank::new_from_parent(parent, &Pubkey::default(), parent.slot() + 1)
}
/// Verify that the parent's vector is computed correctly
#[test]
fn test_bank_parents() {
let (genesis_config, _) = create_genesis_config(1);
let parent = Arc::new(Bank::new(&genesis_config));
let bank = new_from_parent(&parent);
assert!(Arc::ptr_eq(&bank.parents()[0], &parent));
}
/// Verifies that transactions are dropped if they have already been processed
#[test]
fn test_tx_already_processed() {
let (genesis_config, mint_keypair) = create_genesis_config(2);
let mut bank = Bank::new(&genesis_config);
assert!(!bank.check_duplicates_by_hash_enabled());
let key1 = Keypair::new();
let mut tx =
system_transaction::transfer(&mint_keypair, &key1.pubkey(), 1, genesis_config.hash());
// First process `tx` so that the status cache is updated
assert_eq!(bank.process_transaction(&tx), Ok(()));
// Ensure that signature check works
assert_eq!(
bank.process_transaction(&tx),
Err(TransactionError::AlreadyProcessed)
);
// Clear transaction signature
tx.signatures[0] = Signature::default();
// Enable duplicate check by message hash
bank.feature_set = Arc::new(FeatureSet::all_enabled());
// Ensure that message hash check works
assert_eq!(
bank.process_transaction(&tx),
Err(TransactionError::AlreadyProcessed)
);
}
/// Verifies that last ids and status cache are correctly referenced from parent
#[test]
fn test_bank_parent_already_processed() {
let (genesis_config, mint_keypair) = create_genesis_config(2);
let key1 = Keypair::new();
let parent = Arc::new(Bank::new(&genesis_config));
let tx =
system_transaction::transfer(&mint_keypair, &key1.pubkey(), 1, genesis_config.hash());
assert_eq!(parent.process_transaction(&tx), Ok(()));
let bank = new_from_parent(&parent);
assert_eq!(
bank.process_transaction(&tx),
Err(TransactionError::AlreadyProcessed)
);
}
/// Verifies that last ids and accounts are correctly referenced from parent
#[test]
fn test_bank_parent_account_spend() {
let (genesis_config, mint_keypair) = create_genesis_config(2);
let key1 = Keypair::new();
let key2 = Keypair::new();
let parent = Arc::new(Bank::new(&genesis_config));
let tx =
system_transaction::transfer(&mint_keypair, &key1.pubkey(), 1, genesis_config.hash());
assert_eq!(parent.process_transaction(&tx), Ok(()));
let bank = new_from_parent(&parent);
let tx = system_transaction::transfer(&key1, &key2.pubkey(), 1, genesis_config.hash());
assert_eq!(bank.process_transaction(&tx), Ok(()));
assert_eq!(parent.get_signature_status(&tx.signatures[0]), None);
}
#[test]
fn test_bank_hash_internal_state() {
let (genesis_config, mint_keypair) = create_genesis_config(2_000);
let bank0 = Bank::new(&genesis_config);
let bank1 = Bank::new(&genesis_config);
let initial_state = bank0.hash_internal_state();
assert_eq!(bank1.hash_internal_state(), initial_state);
let pubkey = solana_sdk::pubkey::new_rand();
bank0.transfer(1_000, &mint_keypair, &pubkey).unwrap();
assert_ne!(bank0.hash_internal_state(), initial_state);
bank1.transfer(1_000, &mint_keypair, &pubkey).unwrap();
assert_eq!(bank0.hash_internal_state(), bank1.hash_internal_state());
// Checkpointing should always result in a new state
let bank2 = new_from_parent(&Arc::new(bank1));
assert_ne!(bank0.hash_internal_state(), bank2.hash_internal_state());
let pubkey2 = solana_sdk::pubkey::new_rand();
info!("transfer 2 {}", pubkey2);
bank2.transfer(10, &mint_keypair, &pubkey2).unwrap();
bank2.update_accounts_hash();
assert!(bank2.verify_bank_hash());
}
#[test]
fn test_bank_hash_internal_state_verify() {
solana_logger::setup();
let (genesis_config, mint_keypair) = create_genesis_config(2_000);
let bank0 = Bank::new(&genesis_config);
let pubkey = solana_sdk::pubkey::new_rand();
info!("transfer 0 {} mint: {}", pubkey, mint_keypair.pubkey());
bank0.transfer(1_000, &mint_keypair, &pubkey).unwrap();
let bank0_state = bank0.hash_internal_state();
let bank0 = Arc::new(bank0);
// Checkpointing should result in a new state while freezing the parent
let bank2 = Bank::new_from_parent(&bank0, &solana_sdk::pubkey::new_rand(), 1);
assert_ne!(bank0_state, bank2.hash_internal_state());
// Checkpointing should modify the checkpoint's state when freezed
assert_ne!(bank0_state, bank0.hash_internal_state());
// Checkpointing should never modify the checkpoint's state once frozen
let bank0_state = bank0.hash_internal_state();
bank2.update_accounts_hash();
assert!(bank2.verify_bank_hash());
let bank3 = Bank::new_from_parent(&bank0, &solana_sdk::pubkey::new_rand(), 2);
assert_eq!(bank0_state, bank0.hash_internal_state());
assert!(bank2.verify_bank_hash());
bank3.update_accounts_hash();
assert!(bank3.verify_bank_hash());
let pubkey2 = solana_sdk::pubkey::new_rand();
info!("transfer 2 {}", pubkey2);
bank2.transfer(10, &mint_keypair, &pubkey2).unwrap();
bank2.update_accounts_hash();
assert!(bank2.verify_bank_hash());
assert!(bank3.verify_bank_hash());
}
#[test]
#[should_panic(expected = "assertion failed: self.is_frozen()")]
fn test_verify_hash_unfrozen() {
let (genesis_config, _mint_keypair) = create_genesis_config(2_000);
let bank = Bank::new(&genesis_config);
assert!(bank.verify_hash());
}
#[test]
fn test_verify_snapshot_bank() {
solana_logger::setup();
let pubkey = solana_sdk::pubkey::new_rand();
let (genesis_config, mint_keypair) = create_genesis_config(2_000);
let bank = Bank::new(&genesis_config);
bank.transfer(1_000, &mint_keypair, &pubkey).unwrap();
bank.freeze();
bank.update_accounts_hash();
assert!(bank.verify_snapshot_bank());
// tamper the bank after freeze!
bank.increment_signature_count(1);
assert!(!bank.verify_snapshot_bank());
}
// Test that two bank forks with the same accounts should not hash to the same value.
#[test]
fn test_bank_hash_internal_state_same_account_different_fork() {
solana_logger::setup();
let (genesis_config, mint_keypair) = create_genesis_config(2_000);
let bank0 = Arc::new(Bank::new(&genesis_config));
let initial_state = bank0.hash_internal_state();
let bank1 = Bank::new_from_parent(&bank0, &Pubkey::default(), 1);
assert_ne!(bank1.hash_internal_state(), initial_state);
info!("transfer bank1");
let pubkey = solana_sdk::pubkey::new_rand();
bank1.transfer(1_000, &mint_keypair, &pubkey).unwrap();
assert_ne!(bank1.hash_internal_state(), initial_state);
info!("transfer bank2");
// bank2 should not hash the same as bank1
let bank2 = Bank::new_from_parent(&bank0, &Pubkey::default(), 2);
bank2.transfer(1_000, &mint_keypair, &pubkey).unwrap();
assert_ne!(bank2.hash_internal_state(), initial_state);
assert_ne!(bank1.hash_internal_state(), bank2.hash_internal_state());
}
#[test]
fn test_hash_internal_state_genesis() {
let bank0 = Bank::new(&create_genesis_config(10).0);
let bank1 = Bank::new(&create_genesis_config(20).0);
assert_ne!(bank0.hash_internal_state(), bank1.hash_internal_state());
}
// See that the order of two transfers does not affect the result
// of hash_internal_state
#[test]
fn test_hash_internal_state_order() {
let (genesis_config, mint_keypair) = create_genesis_config(100);
let bank0 = Bank::new(&genesis_config);
let bank1 = Bank::new(&genesis_config);
assert_eq!(bank0.hash_internal_state(), bank1.hash_internal_state());
let key0 = solana_sdk::pubkey::new_rand();
let key1 = solana_sdk::pubkey::new_rand();
bank0.transfer(10, &mint_keypair, &key0).unwrap();
bank0.transfer(20, &mint_keypair, &key1).unwrap();
bank1.transfer(20, &mint_keypair, &key1).unwrap();
bank1.transfer(10, &mint_keypair, &key0).unwrap();
assert_eq!(bank0.hash_internal_state(), bank1.hash_internal_state());
}
#[test]
fn test_hash_internal_state_error() {
solana_logger::setup();
let (genesis_config, mint_keypair) = create_genesis_config(100);
let bank = Bank::new(&genesis_config);
let key0 = solana_sdk::pubkey::new_rand();
bank.transfer(10, &mint_keypair, &key0).unwrap();
let orig = bank.hash_internal_state();
// Transfer will error but still take a fee
assert!(bank.transfer(1000, &mint_keypair, &key0).is_err());
assert_ne!(orig, bank.hash_internal_state());
let orig = bank.hash_internal_state();
let empty_keypair = Keypair::new();
assert!(bank.transfer(1000, &empty_keypair, &key0).is_err());
assert_eq!(orig, bank.hash_internal_state());
}
#[test]
fn test_bank_hash_internal_state_squash() {
let collector_id = Pubkey::default();
let bank0 = Arc::new(Bank::new(&create_genesis_config(10).0));
let hash0 = bank0.hash_internal_state();
// save hash0 because new_from_parent
// updates sysvar entries
let bank1 = Bank::new_from_parent(&bank0, &collector_id, 1);
// no delta in bank1, hashes should always update
assert_ne!(hash0, bank1.hash_internal_state());
// remove parent
bank1.squash();
assert!(bank1.parents().is_empty());
}
/// Verifies that last ids and accounts are correctly referenced from parent
#[test]
fn test_bank_squash() {
solana_logger::setup();
let (genesis_config, mint_keypair) = create_genesis_config(2);
let key1 = Keypair::new();
let key2 = Keypair::new();
let parent = Arc::new(Bank::new(&genesis_config));
let tx_transfer_mint_to_1 =
system_transaction::transfer(&mint_keypair, &key1.pubkey(), 1, genesis_config.hash());
trace!("parent process tx ");
assert_eq!(parent.process_transaction(&tx_transfer_mint_to_1), Ok(()));
trace!("done parent process tx ");
assert_eq!(parent.transaction_count(), 1);
assert_eq!(
parent.get_signature_status(&tx_transfer_mint_to_1.signatures[0]),
Some(Ok(()))
);
trace!("new from parent");
let bank = new_from_parent(&parent);
trace!("done new from parent");
assert_eq!(
bank.get_signature_status(&tx_transfer_mint_to_1.signatures[0]),
Some(Ok(()))
);
assert_eq!(bank.transaction_count(), parent.transaction_count());
let tx_transfer_1_to_2 =
system_transaction::transfer(&key1, &key2.pubkey(), 1, genesis_config.hash());
assert_eq!(bank.process_transaction(&tx_transfer_1_to_2), Ok(()));
assert_eq!(bank.transaction_count(), 2);
assert_eq!(parent.transaction_count(), 1);
assert_eq!(
parent.get_signature_status(&tx_transfer_1_to_2.signatures[0]),
None
);
for _ in 0..3 {
// first time these should match what happened above, assert that parents are ok
assert_eq!(bank.get_balance(&key1.pubkey()), 0);
assert_eq!(bank.get_account(&key1.pubkey()), None);
assert_eq!(bank.get_balance(&key2.pubkey()), 1);
trace!("start");
assert_eq!(
bank.get_signature_status(&tx_transfer_mint_to_1.signatures[0]),
Some(Ok(()))
);
assert_eq!(
bank.get_signature_status(&tx_transfer_1_to_2.signatures[0]),
Some(Ok(()))
);
// works iteration 0, no-ops on iteration 1 and 2
trace!("SQUASH");
bank.squash();
assert_eq!(parent.transaction_count(), 1);
assert_eq!(bank.transaction_count(), 2);
}
}
#[test]
fn test_bank_get_account_in_parent_after_squash() {
let (genesis_config, mint_keypair) = create_genesis_config(500);
let parent = Arc::new(Bank::new(&genesis_config));
let key1 = Keypair::new();
parent.transfer(1, &mint_keypair, &key1.pubkey()).unwrap();
assert_eq!(parent.get_balance(&key1.pubkey()), 1);
let bank = new_from_parent(&parent);
bank.squash();
assert_eq!(parent.get_balance(&key1.pubkey()), 1);
}
#[test]
fn test_bank_get_account_in_parent_after_squash2() {
solana_logger::setup();
let (genesis_config, mint_keypair) = create_genesis_config(500);
let bank0 = Arc::new(Bank::new(&genesis_config));
let key1 = Keypair::new();
bank0.transfer(1, &mint_keypair, &key1.pubkey()).unwrap();
assert_eq!(bank0.get_balance(&key1.pubkey()), 1);
let bank1 = Arc::new(Bank::new_from_parent(&bank0, &Pubkey::default(), 1));
bank1.transfer(3, &mint_keypair, &key1.pubkey()).unwrap();
let bank2 = Arc::new(Bank::new_from_parent(&bank0, &Pubkey::default(), 2));
bank2.transfer(2, &mint_keypair, &key1.pubkey()).unwrap();
let bank3 = Arc::new(Bank::new_from_parent(&bank1, &Pubkey::default(), 3));
bank1.squash();
// This picks up the values from 1 which is the highest root:
// TODO: if we need to access rooted banks older than this,
// need to fix the lookup.
assert_eq!(bank0.get_balance(&key1.pubkey()), 4);
assert_eq!(bank3.get_balance(&key1.pubkey()), 4);
assert_eq!(bank2.get_balance(&key1.pubkey()), 3);
bank3.squash();
assert_eq!(bank1.get_balance(&key1.pubkey()), 4);
let bank4 = Arc::new(Bank::new_from_parent(&bank3, &Pubkey::default(), 4));
bank4.transfer(4, &mint_keypair, &key1.pubkey()).unwrap();
assert_eq!(bank4.get_balance(&key1.pubkey()), 8);
assert_eq!(bank3.get_balance(&key1.pubkey()), 4);
bank4.squash();
let bank5 = Arc::new(Bank::new_from_parent(&bank4, &Pubkey::default(), 5));
bank5.squash();
let bank6 = Arc::new(Bank::new_from_parent(&bank5, &Pubkey::default(), 6));
bank6.squash();
// This picks up the values from 4 which is the highest root:
// TODO: if we need to access rooted banks older than this,
// need to fix the lookup.
assert_eq!(bank3.get_balance(&key1.pubkey()), 8);
assert_eq!(bank2.get_balance(&key1.pubkey()), 8);
assert_eq!(bank4.get_balance(&key1.pubkey()), 8);
}
#[test]
fn test_bank_get_account_modified_since_parent_with_fixed_root() {
let pubkey = solana_sdk::pubkey::new_rand();
let (genesis_config, mint_keypair) = create_genesis_config(500);
let bank1 = Arc::new(Bank::new(&genesis_config));
bank1.transfer(1, &mint_keypair, &pubkey).unwrap();
let result = bank1.get_account_modified_since_parent_with_fixed_root(&pubkey);
assert!(result.is_some());
let (account, slot) = result.unwrap();
assert_eq!(account.lamports, 1);
assert_eq!(slot, 0);
let bank2 = Arc::new(Bank::new_from_parent(&bank1, &Pubkey::default(), 1));
assert!(bank2
.get_account_modified_since_parent_with_fixed_root(&pubkey)
.is_none());
bank2.transfer(100, &mint_keypair, &pubkey).unwrap();
let result = bank1.get_account_modified_since_parent_with_fixed_root(&pubkey);
assert!(result.is_some());
let (account, slot) = result.unwrap();
assert_eq!(account.lamports, 1);
assert_eq!(slot, 0);
let result = bank2.get_account_modified_since_parent_with_fixed_root(&pubkey);
assert!(result.is_some());
let (account, slot) = result.unwrap();
assert_eq!(account.lamports, 101);
assert_eq!(slot, 1);
bank1.squash();
let bank3 = Bank::new_from_parent(&bank2, &Pubkey::default(), 3);
assert_eq!(
None,
bank3.get_account_modified_since_parent_with_fixed_root(&pubkey)
);
}
#[test]
fn test_bank_update_sysvar_account() {
use sysvar::clock::Clock;
let dummy_clock_id = solana_sdk::pubkey::new_rand();
let (mut genesis_config, _mint_keypair) = create_genesis_config(500);
let expected_previous_slot = 3;
let expected_next_slot = expected_previous_slot + 1;
// First, initialize the clock sysvar
activate_all_features(&mut genesis_config);
let bank1 = Arc::new(Bank::new(&genesis_config));
assert_eq!(bank1.calculate_capitalization(), bank1.capitalization());
assert_capitalization_diff(
&bank1,
|| {
bank1.update_sysvar_account(&dummy_clock_id, |optional_account| {
assert!(optional_account.is_none());
create_account(
&Clock {
slot: expected_previous_slot,
..Clock::default()
},
bank1.inherit_specially_retained_account_fields(optional_account),
)
});
let current_account = bank1.get_account(&dummy_clock_id).unwrap();
assert_eq!(
expected_previous_slot,
from_account::<Clock, _>(¤t_account).unwrap().slot
);
},
|old, new| {
assert_eq!(old + 1, new);
},
);
assert_capitalization_diff(
&bank1,
|| {
bank1.update_sysvar_account(&dummy_clock_id, |optional_account| {
assert!(optional_account.is_none());
create_account(
&Clock {
slot: expected_previous_slot,
..Clock::default()
},
bank1.inherit_specially_retained_account_fields(optional_account),
)
})
},
|old, new| {
// creating new sysvar twice in a slot shouldn't increment capitalization twice
assert_eq!(old, new);
},
);
// Updating should increment the clock's slot
let bank2 = Arc::new(Bank::new_from_parent(&bank1, &Pubkey::default(), 1));
assert_capitalization_diff(
&bank2,
|| {
bank2.update_sysvar_account(&dummy_clock_id, |optional_account| {
let slot = from_account::<Clock, _>(optional_account.as_ref().unwrap())
.unwrap()
.slot
+ 1;
create_account(
&Clock {
slot,
..Clock::default()
},
bank2.inherit_specially_retained_account_fields(optional_account),
)
});
let current_account = bank2.get_account(&dummy_clock_id).unwrap();
assert_eq!(
expected_next_slot,
from_account::<Clock, _>(¤t_account).unwrap().slot
);
},
|old, new| {
// if existing, capitalization shouldn't change
assert_eq!(old, new);
},
);
// Updating again should give bank1's sysvar to the closure not bank2's.
// Thus, assert with same expected_next_slot as previously
assert_capitalization_diff(
&bank2,
|| {
bank2.update_sysvar_account(&dummy_clock_id, |optional_account| {
let slot = from_account::<Clock, _>(optional_account.as_ref().unwrap())
.unwrap()
.slot
+ 1;
create_account(
&Clock {
slot,
..Clock::default()
},
bank2.inherit_specially_retained_account_fields(optional_account),
)
});
let current_account = bank2.get_account(&dummy_clock_id).unwrap();
assert_eq!(
expected_next_slot,
from_account::<Clock, _>(¤t_account).unwrap().slot
);
},
|old, new| {
// updating twice in a slot shouldn't increment capitalization twice
assert_eq!(old, new);
},
);
}
#[test]
fn test_bank_epoch_vote_accounts() {
let leader_pubkey = solana_sdk::pubkey::new_rand();
let leader_lamports = 3;
let mut genesis_config =
create_genesis_config_with_leader(5, &leader_pubkey, leader_lamports).genesis_config;
// set this up weird, forces future generation, odd mod(), etc.
// this says: "vote_accounts for epoch X should be generated at slot index 3 in epoch X-2...
const SLOTS_PER_EPOCH: u64 = MINIMUM_SLOTS_PER_EPOCH as u64;
const LEADER_SCHEDULE_SLOT_OFFSET: u64 = SLOTS_PER_EPOCH * 3 - 3;
// no warmup allows me to do the normal division stuff below
genesis_config.epoch_schedule =
EpochSchedule::custom(SLOTS_PER_EPOCH, LEADER_SCHEDULE_SLOT_OFFSET, false);
let parent = Arc::new(Bank::new(&genesis_config));
let mut leader_vote_stake: Vec<_> = parent
.epoch_vote_accounts(0)
.map(|accounts| {
accounts
.iter()
.filter_map(|(pubkey, (stake, account))| {
if let Ok(vote_state) = account.vote_state().as_ref() {
if vote_state.node_pubkey == leader_pubkey {
Some((*pubkey, *stake))
} else {
None
}
} else {
None
}
})
.collect()
})
.unwrap();
assert_eq!(leader_vote_stake.len(), 1);
let (leader_vote_account, leader_stake) = leader_vote_stake.pop().unwrap();
assert!(leader_stake > 0);
let leader_stake = Stake {
delegation: Delegation {
stake: leader_lamports,
activation_epoch: std::u64::MAX, // bootstrap
..Delegation::default()
},
..Stake::default()
};
let mut epoch = 1;
loop {
if epoch > LEADER_SCHEDULE_SLOT_OFFSET / SLOTS_PER_EPOCH {
break;
}
let vote_accounts = parent.epoch_vote_accounts(epoch);
assert!(vote_accounts.is_some());
// epoch_stakes are a snapshot at the leader_schedule_slot_offset boundary
// in the prior epoch (0 in this case)
assert_eq!(
leader_stake.stake(0, None, true),
vote_accounts.unwrap().get(&leader_vote_account).unwrap().0
);
epoch += 1;
}
// child crosses epoch boundary and is the first slot in the epoch
let child = Bank::new_from_parent(
&parent,
&leader_pubkey,
SLOTS_PER_EPOCH - (LEADER_SCHEDULE_SLOT_OFFSET % SLOTS_PER_EPOCH),
);
assert!(child.epoch_vote_accounts(epoch).is_some());
assert_eq!(
leader_stake.stake(child.epoch(), None, true),
child
.epoch_vote_accounts(epoch)
.unwrap()
.get(&leader_vote_account)
.unwrap()
.0
);
// child crosses epoch boundary but isn't the first slot in the epoch, still
// makes an epoch stakes snapshot at 1
let child = Bank::new_from_parent(
&parent,
&leader_pubkey,
SLOTS_PER_EPOCH - (LEADER_SCHEDULE_SLOT_OFFSET % SLOTS_PER_EPOCH) + 1,
);
assert!(child.epoch_vote_accounts(epoch).is_some());
assert_eq!(
leader_stake.stake(child.epoch(), None, true),
child
.epoch_vote_accounts(epoch)
.unwrap()
.get(&leader_vote_account)
.unwrap()
.0
);
}
#[test]
fn test_zero_signatures() {
solana_logger::setup();
let (genesis_config, mint_keypair) = create_genesis_config(500);
let mut bank = Bank::new(&genesis_config);
bank.fee_calculator.lamports_per_signature = 2;
let key = Keypair::new();
let mut transfer_instruction =
system_instruction::transfer(&mint_keypair.pubkey(), &key.pubkey(), 0);
transfer_instruction.accounts[0].is_signer = false;
let message = Message::new(&[transfer_instruction], None);
let tx = Transaction::new(&[&Keypair::new(); 0], message, bank.last_blockhash());
assert_eq!(
bank.process_transaction(&tx),
Err(TransactionError::SanitizeFailure)
);
assert_eq!(bank.get_balance(&key.pubkey()), 0);
}
#[test]
fn test_bank_get_slots_in_epoch() {
let (genesis_config, _) = create_genesis_config(500);
let bank = Bank::new(&genesis_config);
assert_eq!(bank.get_slots_in_epoch(0), MINIMUM_SLOTS_PER_EPOCH as u64);
assert_eq!(
bank.get_slots_in_epoch(2),
(MINIMUM_SLOTS_PER_EPOCH * 4) as u64
);
assert_eq!(
bank.get_slots_in_epoch(5000),
genesis_config.epoch_schedule.slots_per_epoch
);
}
#[test]
fn test_is_delta_true() {
let (genesis_config, mint_keypair) = create_genesis_config(500);
let bank = Arc::new(Bank::new(&genesis_config));
let key1 = Keypair::new();
let tx_transfer_mint_to_1 =
system_transaction::transfer(&mint_keypair, &key1.pubkey(), 1, genesis_config.hash());
assert_eq!(bank.process_transaction(&tx_transfer_mint_to_1), Ok(()));
assert_eq!(bank.is_delta.load(Relaxed), true);
let bank1 = new_from_parent(&bank);
let hash1 = bank1.hash_internal_state();
assert_eq!(bank1.is_delta.load(Relaxed), false);
assert_ne!(hash1, bank.hash());
// ticks don't make a bank into a delta or change its state unless a block boundary is crossed
bank1.register_tick(&Hash::default());
assert_eq!(bank1.is_delta.load(Relaxed), false);
assert_eq!(bank1.hash_internal_state(), hash1);
}
#[test]
fn test_is_empty() {
let (genesis_config, mint_keypair) = create_genesis_config(500);
let bank0 = Arc::new(Bank::new(&genesis_config));
let key1 = Keypair::new();
// The zeroth bank is empty becasue there are no transactions
assert_eq!(bank0.is_empty(), true);
// Set is_delta to true, bank is no longer empty
let tx_transfer_mint_to_1 =
system_transaction::transfer(&mint_keypair, &key1.pubkey(), 1, genesis_config.hash());
assert_eq!(bank0.process_transaction(&tx_transfer_mint_to_1), Ok(()));
assert_eq!(bank0.is_empty(), false);
}
#[test]
fn test_bank_inherit_tx_count() {
let (genesis_config, mint_keypair) = create_genesis_config(500);
let bank0 = Arc::new(Bank::new(&genesis_config));
// Bank 1
let bank1 = Arc::new(Bank::new_from_parent(
&bank0,
&solana_sdk::pubkey::new_rand(),
1,
));
// Bank 2
let bank2 = Bank::new_from_parent(&bank0, &solana_sdk::pubkey::new_rand(), 2);
// transfer a token
assert_eq!(
bank1.process_transaction(&system_transaction::transfer(
&mint_keypair,
&Keypair::new().pubkey(),
1,
genesis_config.hash(),
)),
Ok(())
);
assert_eq!(bank0.transaction_count(), 0);
assert_eq!(bank2.transaction_count(), 0);
assert_eq!(bank1.transaction_count(), 1);
bank1.squash();
assert_eq!(bank0.transaction_count(), 0);
assert_eq!(bank2.transaction_count(), 0);
assert_eq!(bank1.transaction_count(), 1);
let bank6 = Bank::new_from_parent(&bank1, &solana_sdk::pubkey::new_rand(), 3);
assert_eq!(bank1.transaction_count(), 1);
assert_eq!(bank6.transaction_count(), 1);
bank6.squash();
assert_eq!(bank6.transaction_count(), 1);
}
#[test]
fn test_bank_inherit_fee_rate_governor() {
let (mut genesis_config, _mint_keypair) = create_genesis_config(500);
genesis_config
.fee_rate_governor
.target_lamports_per_signature = 123;
let bank0 = Arc::new(Bank::new(&genesis_config));
let bank1 = Arc::new(new_from_parent(&bank0));
assert_eq!(
bank0.fee_rate_governor.target_lamports_per_signature / 2,
bank1
.fee_rate_governor
.create_fee_calculator()
.lamports_per_signature
);
}
#[test]
fn test_bank_vote_accounts() {
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config_with_leader(500, &solana_sdk::pubkey::new_rand(), 1);
let bank = Arc::new(Bank::new(&genesis_config));
let vote_accounts = bank.vote_accounts();
assert_eq!(vote_accounts.len(), 1); // bootstrap validator has
// to have a vote account
let vote_keypair = Keypair::new();
let instructions = vote_instruction::create_account(
&mint_keypair.pubkey(),
&vote_keypair.pubkey(),
&VoteInit {
node_pubkey: mint_keypair.pubkey(),
authorized_voter: vote_keypair.pubkey(),
authorized_withdrawer: vote_keypair.pubkey(),
commission: 0,
},
10,
);
let message = Message::new(&instructions, Some(&mint_keypair.pubkey()));
let transaction = Transaction::new(
&[&mint_keypair, &vote_keypair],
message,
bank.last_blockhash(),
);
bank.process_transaction(&transaction).unwrap();
let vote_accounts = bank.vote_accounts().into_iter().collect::<HashMap<_, _>>();
assert_eq!(vote_accounts.len(), 2);
assert!(vote_accounts.get(&vote_keypair.pubkey()).is_some());
assert!(bank.withdraw(&vote_keypair.pubkey(), 10).is_ok());
let vote_accounts = bank.vote_accounts();
assert_eq!(vote_accounts.len(), 1);
}
#[test]
fn test_bank_cloned_stake_delegations() {
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config_with_leader(500, &solana_sdk::pubkey::new_rand(), 1);
let bank = Arc::new(Bank::new(&genesis_config));
let stake_delegations = bank.cloned_stake_delegations();
assert_eq!(stake_delegations.len(), 1); // bootstrap validator has
// to have a stake delegation
let vote_keypair = Keypair::new();
let mut instructions = vote_instruction::create_account(
&mint_keypair.pubkey(),
&vote_keypair.pubkey(),
&VoteInit {
node_pubkey: mint_keypair.pubkey(),
authorized_voter: vote_keypair.pubkey(),
authorized_withdrawer: vote_keypair.pubkey(),
commission: 0,
},
10,
);
let stake_keypair = Keypair::new();
instructions.extend(stake_instruction::create_account_and_delegate_stake(
&mint_keypair.pubkey(),
&stake_keypair.pubkey(),
&vote_keypair.pubkey(),
&Authorized::auto(&stake_keypair.pubkey()),
&Lockup::default(),
10,
));
let message = Message::new(&instructions, Some(&mint_keypair.pubkey()));
let transaction = Transaction::new(
&[&mint_keypair, &vote_keypair, &stake_keypair],
message,
bank.last_blockhash(),
);
bank.process_transaction(&transaction).unwrap();
let stake_delegations = bank.cloned_stake_delegations();
assert_eq!(stake_delegations.len(), 2);
assert!(stake_delegations.get(&stake_keypair.pubkey()).is_some());
}
#[test]
fn test_bank_fees_account() {
let (mut genesis_config, _) = create_genesis_config(500);
genesis_config.fee_rate_governor = FeeRateGovernor::new(12345, 0);
let bank = Arc::new(Bank::new(&genesis_config));
let fees_account = bank.get_account(&sysvar::fees::id()).unwrap();
let fees = from_account::<Fees, _>(&fees_account).unwrap();
assert_eq!(
bank.fee_calculator.lamports_per_signature,
fees.fee_calculator.lamports_per_signature
);
assert_eq!(fees.fee_calculator.lamports_per_signature, 12345);
}
#[test]
fn test_is_delta_with_no_committables() {
let (genesis_config, mint_keypair) = create_genesis_config(8000);
let bank = Bank::new(&genesis_config);
bank.is_delta.store(false, Relaxed);
let keypair1 = Keypair::new();
let keypair2 = Keypair::new();
let fail_tx =
system_transaction::transfer(&keypair1, &keypair2.pubkey(), 1, bank.last_blockhash());
// Should fail with TransactionError::AccountNotFound, which means
// the account which this tx operated on will not be committed. Thus
// the bank is_delta should still be false
assert_eq!(
bank.process_transaction(&fail_tx),
Err(TransactionError::AccountNotFound)
);
// Check the bank is_delta is still false
assert!(!bank.is_delta.load(Relaxed));
// Should fail with InstructionError, but InstructionErrors are committable,
// so is_delta should be true
assert_eq!(
bank.transfer(10_001, &mint_keypair, &solana_sdk::pubkey::new_rand()),
Err(TransactionError::InstructionError(
0,
SystemError::ResultWithNegativeLamports.into(),
))
);
assert!(bank.is_delta.load(Relaxed));
}
#[test]
fn test_bank_get_program_accounts() {
let (genesis_config, mint_keypair) = create_genesis_config(500);
let parent = Arc::new(Bank::new(&genesis_config));
parent.restore_old_behavior_for_fragile_tests();
let genesis_accounts: Vec<_> = parent.get_all_accounts_with_modified_slots();
assert!(
genesis_accounts
.iter()
.any(|(pubkey, _, _)| *pubkey == mint_keypair.pubkey()),
"mint pubkey not found"
);
assert!(
genesis_accounts
.iter()
.any(|(pubkey, _, _)| solana_sdk::sysvar::is_sysvar_id(pubkey)),
"no sysvars found"
);
let bank0 = Arc::new(new_from_parent(&parent));
let pubkey0 = solana_sdk::pubkey::new_rand();
let program_id = Pubkey::new(&[2; 32]);
let account0 = AccountSharedData::new(1, 0, &program_id);
bank0.store_account(&pubkey0, &account0);
assert_eq!(
bank0.get_program_accounts_modified_since_parent(&program_id),
vec![(pubkey0, account0.clone())]
);
let bank1 = Arc::new(new_from_parent(&bank0));
bank1.squash();
assert_eq!(
bank0.get_program_accounts(&program_id),
vec![(pubkey0, account0.clone())]
);
assert_eq!(
bank1.get_program_accounts(&program_id),
vec![(pubkey0, account0)]
);
assert_eq!(
bank1.get_program_accounts_modified_since_parent(&program_id),
vec![]
);
let bank2 = Arc::new(new_from_parent(&bank1));
let pubkey1 = solana_sdk::pubkey::new_rand();
let account1 = AccountSharedData::new(3, 0, &program_id);
bank2.store_account(&pubkey1, &account1);
// Accounts with 0 lamports should be filtered out by Accounts::load_by_program()
let pubkey2 = solana_sdk::pubkey::new_rand();
let account2 = AccountSharedData::new(0, 0, &program_id);
bank2.store_account(&pubkey2, &account2);
let bank3 = Arc::new(new_from_parent(&bank2));
bank3.squash();
assert_eq!(bank1.get_program_accounts(&program_id).len(), 2);
assert_eq!(bank3.get_program_accounts(&program_id).len(), 2);
}
#[test]
fn test_get_filtered_indexed_accounts() {
let (genesis_config, _mint_keypair) = create_genesis_config(500);
let mut account_indexes = HashSet::new();
account_indexes.insert(AccountIndex::ProgramId);
let bank = Arc::new(Bank::new_with_config(
&genesis_config,
account_indexes,
false,
));
let address = Pubkey::new_unique();
let program_id = Pubkey::new_unique();
let account = AccountSharedData::new(1, 0, &program_id);
bank.store_account(&address, &account);
let indexed_accounts =
bank.get_filtered_indexed_accounts(&IndexKey::ProgramId(program_id), |_| true);
assert_eq!(indexed_accounts.len(), 1);
assert_eq!(indexed_accounts[0], (address, account));
// Even though the account is re-stored in the bank (and the index) under a new program id,
// it is still present in the index under the original program id as well. This
// demonstrates the need for a redundant post-processing filter.
let another_program_id = Pubkey::new_unique();
let new_account = AccountSharedData::new(1, 0, &another_program_id);
let bank = Arc::new(new_from_parent(&bank));
bank.store_account(&address, &new_account);
let indexed_accounts =
bank.get_filtered_indexed_accounts(&IndexKey::ProgramId(program_id), |_| true);
assert_eq!(indexed_accounts.len(), 1);
assert_eq!(indexed_accounts[0], (address, new_account.clone()));
let indexed_accounts =
bank.get_filtered_indexed_accounts(&IndexKey::ProgramId(another_program_id), |_| true);
assert_eq!(indexed_accounts.len(), 1);
assert_eq!(indexed_accounts[0], (address, new_account.clone()));
// Post-processing filter
let indexed_accounts = bank
.get_filtered_indexed_accounts(&IndexKey::ProgramId(program_id), |account| {
account.owner() == &program_id
});
assert!(indexed_accounts.is_empty());
let indexed_accounts = bank
.get_filtered_indexed_accounts(&IndexKey::ProgramId(another_program_id), |account| {
account.owner() == &another_program_id
});
assert_eq!(indexed_accounts.len(), 1);
assert_eq!(indexed_accounts[0], (address, new_account));
}
#[test]
fn test_status_cache_ancestors() {
solana_logger::setup();
let (genesis_config, _mint_keypair) = create_genesis_config(500);
let parent = Arc::new(Bank::new(&genesis_config));
let bank1 = Arc::new(new_from_parent(&parent));
let mut bank = bank1;
for _ in 0..MAX_CACHE_ENTRIES * 2 {
bank = Arc::new(new_from_parent(&bank));
bank.squash();
}
let bank = new_from_parent(&bank);
assert_eq!(
bank.status_cache_ancestors(),
(bank.slot() - MAX_CACHE_ENTRIES as u64..=bank.slot()).collect::<Vec<_>>()
);
}
#[test]
fn test_add_builtin() {
let (genesis_config, mint_keypair) = create_genesis_config(500);
let mut bank = Bank::new(&genesis_config);
fn mock_vote_program_id() -> Pubkey {
Pubkey::new(&[42u8; 32])
}
fn mock_vote_processor(
program_id: &Pubkey,
_instruction_data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> std::result::Result<(), InstructionError> {
if mock_vote_program_id() != *program_id {
return Err(InstructionError::IncorrectProgramId);
}
Err(InstructionError::Custom(42))
}
assert!(bank.get_account(&mock_vote_program_id()).is_none());
bank.add_builtin(
"mock_vote_program",
mock_vote_program_id(),
mock_vote_processor,
);
assert!(bank.get_account(&mock_vote_program_id()).is_some());
let mock_account = Keypair::new();
let mock_validator_identity = Keypair::new();
let mut instructions = vote_instruction::create_account(
&mint_keypair.pubkey(),
&mock_account.pubkey(),
&VoteInit {
node_pubkey: mock_validator_identity.pubkey(),
..VoteInit::default()
},
1,
);
instructions[1].program_id = mock_vote_program_id();
let message = Message::new(&instructions, Some(&mint_keypair.pubkey()));
let transaction = Transaction::new(
&[&mint_keypair, &mock_account, &mock_validator_identity],
message,
bank.last_blockhash(),
);
assert_eq!(
bank.process_transaction(&transaction),
Err(TransactionError::InstructionError(
1,
InstructionError::Custom(42)
))
);
}
#[test]
fn test_add_duplicate_static_program() {
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config_with_leader(500, &solana_sdk::pubkey::new_rand(), 0);
let mut bank = Bank::new(&genesis_config);
fn mock_vote_processor(
_pubkey: &Pubkey,
_data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> std::result::Result<(), InstructionError> {
Err(InstructionError::Custom(42))
}
let mock_account = Keypair::new();
let mock_validator_identity = Keypair::new();
let instructions = vote_instruction::create_account(
&mint_keypair.pubkey(),
&mock_account.pubkey(),
&VoteInit {
node_pubkey: mock_validator_identity.pubkey(),
..VoteInit::default()
},
1,
);
let message = Message::new(&instructions, Some(&mint_keypair.pubkey()));
let transaction = Transaction::new(
&[&mint_keypair, &mock_account, &mock_validator_identity],
message,
bank.last_blockhash(),
);
let vote_loader_account = bank.get_account(&solana_vote_program::id()).unwrap();
bank.add_builtin(
"solana_vote_program",
solana_vote_program::id(),
mock_vote_processor,
);
let new_vote_loader_account = bank.get_account(&solana_vote_program::id()).unwrap();
// Vote loader account should not be updated since it was included in the genesis config.
assert_eq!(vote_loader_account.data(), new_vote_loader_account.data());
assert_eq!(
bank.process_transaction(&transaction),
Err(TransactionError::InstructionError(
1,
InstructionError::Custom(42)
))
);
}
#[test]
fn test_add_instruction_processor_for_existing_unrelated_accounts() {
let (genesis_config, _mint_keypair) = create_genesis_config(500);
let mut bank = Bank::new(&genesis_config);
fn mock_ix_processor(
_pubkey: &Pubkey,
_data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> std::result::Result<(), InstructionError> {
Err(InstructionError::Custom(42))
}
// Non-native loader accounts can not be used for instruction processing
assert!(bank.stakes.read().unwrap().vote_accounts().is_empty());
assert!(bank.stakes.read().unwrap().stake_delegations().is_empty());
assert_eq!(bank.calculate_capitalization(), bank.capitalization());
let ((vote_id, vote_account), (stake_id, stake_account)) =
crate::stakes::tests::create_staked_node_accounts(1_0000);
bank.capitalization
.fetch_add(vote_account.lamports + stake_account.lamports, Relaxed);
bank.store_account(&vote_id, &vote_account);
bank.store_account(&stake_id, &stake_account);
assert!(!bank.stakes.read().unwrap().vote_accounts().is_empty());
assert!(!bank.stakes.read().unwrap().stake_delegations().is_empty());
assert_eq!(bank.calculate_capitalization(), bank.capitalization());
bank.add_builtin("mock_program1", vote_id, mock_ix_processor);
bank.add_builtin("mock_program2", stake_id, mock_ix_processor);
assert!(bank.stakes.read().unwrap().vote_accounts().is_empty());
assert!(bank.stakes.read().unwrap().stake_delegations().is_empty());
assert_eq!(bank.calculate_capitalization(), bank.capitalization());
assert_eq!(
"mock_program1",
String::from_utf8_lossy(&bank.get_account(&vote_id).unwrap_or_default().data())
);
assert_eq!(
"mock_program2",
String::from_utf8_lossy(&bank.get_account(&stake_id).unwrap_or_default().data())
);
// Re-adding builtin programs should be no-op
bank.update_accounts_hash();
let old_hash = bank.get_accounts_hash();
bank.add_builtin("mock_program1", vote_id, mock_ix_processor);
bank.add_builtin("mock_program2", stake_id, mock_ix_processor);
bank.update_accounts_hash();
let new_hash = bank.get_accounts_hash();
assert_eq!(old_hash, new_hash);
assert!(bank.stakes.read().unwrap().vote_accounts().is_empty());
assert!(bank.stakes.read().unwrap().stake_delegations().is_empty());
assert_eq!(bank.calculate_capitalization(), bank.capitalization());
assert_eq!(
"mock_program1",
String::from_utf8_lossy(&bank.get_account(&vote_id).unwrap_or_default().data())
);
assert_eq!(
"mock_program2",
String::from_utf8_lossy(&bank.get_account(&stake_id).unwrap_or_default().data())
);
}
#[test]
fn test_recent_blockhashes_sysvar() {
let (genesis_config, _mint_keypair) = create_genesis_config(500);
let mut bank = Arc::new(Bank::new(&genesis_config));
for i in 1..5 {
let bhq_account = bank.get_account(&sysvar::recent_blockhashes::id()).unwrap();
let recent_blockhashes =
from_account::<sysvar::recent_blockhashes::RecentBlockhashes, _>(&bhq_account)
.unwrap();
// Check length
assert_eq!(recent_blockhashes.len(), i);
let most_recent_hash = recent_blockhashes.iter().next().unwrap().blockhash;
// Check order
assert_eq!(Some(true), bank.check_hash_age(&most_recent_hash, 0));
goto_end_of_slot(Arc::get_mut(&mut bank).unwrap());
bank = Arc::new(new_from_parent(&bank));
}
}
#[test]
fn test_blockhash_queue_sysvar_consistency() {
let (genesis_config, _mint_keypair) = create_genesis_config(100_000);
let mut bank = Arc::new(Bank::new(&genesis_config));
goto_end_of_slot(Arc::get_mut(&mut bank).unwrap());
let bhq_account = bank.get_account(&sysvar::recent_blockhashes::id()).unwrap();
let recent_blockhashes =
from_account::<sysvar::recent_blockhashes::RecentBlockhashes, _>(&bhq_account).unwrap();
let sysvar_recent_blockhash = recent_blockhashes[0].blockhash;
let bank_last_blockhash = bank.last_blockhash();
assert_eq!(sysvar_recent_blockhash, bank_last_blockhash);
}
#[test]
fn test_bank_inherit_last_vote_sync() {
let (genesis_config, _) = create_genesis_config(500);
let bank0 = Arc::new(Bank::new(&genesis_config));
let last_ts = bank0.last_vote_sync.load(Relaxed);
assert_eq!(last_ts, 0);
bank0.last_vote_sync.store(1, Relaxed);
let bank1 =
Bank::new_from_parent(&bank0, &Pubkey::default(), bank0.get_slots_in_epoch(0) - 1);
let last_ts = bank1.last_vote_sync.load(Relaxed);
assert_eq!(last_ts, 1);
}
#[test]
fn test_hash_internal_state_unchanged() {
let (genesis_config, _) = create_genesis_config(500);
let bank0 = Arc::new(Bank::new(&genesis_config));
bank0.freeze();
let bank0_hash = bank0.hash();
let bank1 = Bank::new_from_parent(&bank0, &Pubkey::default(), 1);
bank1.freeze();
let bank1_hash = bank1.hash();
// Checkpointing should always result in a new state
assert_ne!(bank0_hash, bank1_hash);
}
#[test]
fn test_ticks_change_state() {
let (genesis_config, _) = create_genesis_config(500);
let bank = Arc::new(Bank::new(&genesis_config));
let bank1 = new_from_parent(&bank);
let hash1 = bank1.hash_internal_state();
// ticks don't change its state unless a block boundary is crossed
for _ in 0..genesis_config.ticks_per_slot {
assert_eq!(bank1.hash_internal_state(), hash1);
bank1.register_tick(&Hash::default());
}
assert_ne!(bank1.hash_internal_state(), hash1);
}
#[ignore]
#[test]
fn test_banks_leak() {
fn add_lotsa_stake_accounts(genesis_config: &mut GenesisConfig) {
const LOTSA: usize = 4_096;
(0..LOTSA).for_each(|_| {
let pubkey = solana_sdk::pubkey::new_rand();
genesis_config.add_account(
pubkey,
solana_stake_program::stake_state::create_lockup_stake_account(
&Authorized::auto(&pubkey),
&Lockup::default(),
&Rent::default(),
50_000_000,
),
);
});
}
solana_logger::setup();
let (mut genesis_config, _) = create_genesis_config(100_000_000_000_000);
add_lotsa_stake_accounts(&mut genesis_config);
let mut bank = std::sync::Arc::new(Bank::new(&genesis_config));
let mut num_banks = 0;
let pid = std::process::id();
#[cfg(not(target_os = "linux"))]
error!(
"\nYou can run this to watch RAM:\n while read -p 'banks: '; do echo $(( $(ps -o vsize= -p {})/$REPLY));done", pid
);
loop {
num_banks += 1;
bank = std::sync::Arc::new(new_from_parent(&bank));
if num_banks % 100 == 0 {
#[cfg(target_os = "linux")]
{
let pages_consumed = std::fs::read_to_string(format!("/proc/{}/statm", pid))
.unwrap()
.split_whitespace()
.next()
.unwrap()
.parse::<usize>()
.unwrap();
error!(
"at {} banks: {} mem or {}kB/bank",
num_banks,
pages_consumed * 4096,
(pages_consumed * 4) / num_banks
);
}
#[cfg(not(target_os = "linux"))]
{
error!("{} banks, sleeping for 5 sec", num_banks);
std::thread::sleep(Duration::new(5, 0));
}
}
}
}
fn get_nonce_account(bank: &Bank, nonce_pubkey: &Pubkey) -> Option<Hash> {
bank.get_account(&nonce_pubkey).and_then(|acc| {
let state =
StateMut::<nonce::state::Versions>::state(&acc).map(|v| v.convert_to_current());
match state {
Ok(nonce::State::Initialized(ref data)) => Some(data.blockhash),
_ => None,
}
})
}
fn nonce_setup(
bank: &mut Arc<Bank>,
mint_keypair: &Keypair,
custodian_lamports: u64,
nonce_lamports: u64,
nonce_authority: Option<Pubkey>,
) -> Result<(Keypair, Keypair)> {
let custodian_keypair = Keypair::new();
let nonce_keypair = Keypair::new();
/* Setup accounts */
let mut setup_ixs = vec![system_instruction::transfer(
&mint_keypair.pubkey(),
&custodian_keypair.pubkey(),
custodian_lamports,
)];
let nonce_authority = nonce_authority.unwrap_or_else(|| nonce_keypair.pubkey());
setup_ixs.extend_from_slice(&system_instruction::create_nonce_account(
&custodian_keypair.pubkey(),
&nonce_keypair.pubkey(),
&nonce_authority,
nonce_lamports,
));
let message = Message::new(&setup_ixs, Some(&mint_keypair.pubkey()));
let setup_tx = Transaction::new(
&[mint_keypair, &custodian_keypair, &nonce_keypair],
message,
bank.last_blockhash(),
);
bank.process_transaction(&setup_tx)?;
Ok((custodian_keypair, nonce_keypair))
}
fn setup_nonce_with_bank<F>(
supply_lamports: u64,
mut genesis_cfg_fn: F,
custodian_lamports: u64,
nonce_lamports: u64,
nonce_authority: Option<Pubkey>,
) -> Result<(Arc<Bank>, Keypair, Keypair, Keypair)>
where
F: FnMut(&mut GenesisConfig),
{
let (mut genesis_config, mint_keypair) = create_genesis_config(supply_lamports);
genesis_config.rent.lamports_per_byte_year = 0;
genesis_cfg_fn(&mut genesis_config);
let mut bank = Arc::new(Bank::new(&genesis_config));
// Banks 0 and 1 have no fees, wait two blocks before
// initializing our nonce accounts
for _ in 0..2 {
goto_end_of_slot(Arc::get_mut(&mut bank).unwrap());
bank = Arc::new(new_from_parent(&bank));
}
let (custodian_keypair, nonce_keypair) = nonce_setup(
&mut bank,
&mint_keypair,
custodian_lamports,
nonce_lamports,
nonce_authority,
)?;
Ok((bank, mint_keypair, custodian_keypair, nonce_keypair))
}
#[test]
fn test_check_tx_durable_nonce_ok() {
let (bank, _mint_keypair, custodian_keypair, nonce_keypair) =
setup_nonce_with_bank(10_000_000, |_| {}, 5_000_000, 250_000, None).unwrap();
let custodian_pubkey = custodian_keypair.pubkey();
let nonce_pubkey = nonce_keypair.pubkey();
let nonce_hash = get_nonce_account(&bank, &nonce_pubkey).unwrap();
let tx = Transaction::new_signed_with_payer(
&[
system_instruction::advance_nonce_account(&nonce_pubkey, &nonce_pubkey),
system_instruction::transfer(&custodian_pubkey, &nonce_pubkey, 100_000),
],
Some(&custodian_pubkey),
&[&custodian_keypair, &nonce_keypair],
nonce_hash,
);
let nonce_account = bank.get_account(&nonce_pubkey).unwrap();
assert_eq!(
bank.check_tx_durable_nonce(&tx),
Some((nonce_pubkey, nonce_account))
);
}
#[test]
fn test_check_tx_durable_nonce_not_durable_nonce_fail() {
let (bank, _mint_keypair, custodian_keypair, nonce_keypair) =
setup_nonce_with_bank(10_000_000, |_| {}, 5_000_000, 250_000, None).unwrap();
let custodian_pubkey = custodian_keypair.pubkey();
let nonce_pubkey = nonce_keypair.pubkey();
let nonce_hash = get_nonce_account(&bank, &nonce_pubkey).unwrap();
let tx = Transaction::new_signed_with_payer(
&[
system_instruction::transfer(&custodian_pubkey, &nonce_pubkey, 100_000),
system_instruction::advance_nonce_account(&nonce_pubkey, &nonce_pubkey),
],
Some(&custodian_pubkey),
&[&custodian_keypair, &nonce_keypair],
nonce_hash,
);
assert!(bank.check_tx_durable_nonce(&tx).is_none());
}
#[test]
fn test_check_tx_durable_nonce_missing_ix_pubkey_fail() {
let (bank, _mint_keypair, custodian_keypair, nonce_keypair) =
setup_nonce_with_bank(10_000_000, |_| {}, 5_000_000, 250_000, None).unwrap();
let custodian_pubkey = custodian_keypair.pubkey();
let nonce_pubkey = nonce_keypair.pubkey();
let nonce_hash = get_nonce_account(&bank, &nonce_pubkey).unwrap();
let mut tx = Transaction::new_signed_with_payer(
&[
system_instruction::advance_nonce_account(&nonce_pubkey, &nonce_pubkey),
system_instruction::transfer(&custodian_pubkey, &nonce_pubkey, 100_000),
],
Some(&custodian_pubkey),
&[&custodian_keypair, &nonce_keypair],
nonce_hash,
);
tx.message.instructions[0].accounts.clear();
assert!(bank.check_tx_durable_nonce(&tx).is_none());
}
#[test]
fn test_check_tx_durable_nonce_nonce_acc_does_not_exist_fail() {
let (bank, _mint_keypair, custodian_keypair, nonce_keypair) =
setup_nonce_with_bank(10_000_000, |_| {}, 5_000_000, 250_000, None).unwrap();
let custodian_pubkey = custodian_keypair.pubkey();
let nonce_pubkey = nonce_keypair.pubkey();
let missing_keypair = Keypair::new();
let missing_pubkey = missing_keypair.pubkey();
let nonce_hash = get_nonce_account(&bank, &nonce_pubkey).unwrap();
let tx = Transaction::new_signed_with_payer(
&[
system_instruction::advance_nonce_account(&missing_pubkey, &nonce_pubkey),
system_instruction::transfer(&custodian_pubkey, &nonce_pubkey, 100_000),
],
Some(&custodian_pubkey),
&[&custodian_keypair, &nonce_keypair],
nonce_hash,
);
assert!(bank.check_tx_durable_nonce(&tx).is_none());
}
#[test]
fn test_check_tx_durable_nonce_bad_tx_hash_fail() {
let (bank, _mint_keypair, custodian_keypair, nonce_keypair) =
setup_nonce_with_bank(10_000_000, |_| {}, 5_000_000, 250_000, None).unwrap();
let custodian_pubkey = custodian_keypair.pubkey();
let nonce_pubkey = nonce_keypair.pubkey();
let tx = Transaction::new_signed_with_payer(
&[
system_instruction::advance_nonce_account(&nonce_pubkey, &nonce_pubkey),
system_instruction::transfer(&custodian_pubkey, &nonce_pubkey, 100_000),
],
Some(&custodian_pubkey),
&[&custodian_keypair, &nonce_keypair],
Hash::default(),
);
assert!(bank.check_tx_durable_nonce(&tx).is_none());
}
#[test]
fn test_assign_from_nonce_account_fail() {
let (genesis_config, _mint_keypair) = create_genesis_config(100_000_000);
let bank = Arc::new(Bank::new(&genesis_config));
let nonce = Keypair::new();
let nonce_account = AccountSharedData::new_data(
42_424_242,
&nonce::state::Versions::new_current(nonce::State::Initialized(
nonce::state::Data::default(),
)),
&system_program::id(),
)
.unwrap();
let blockhash = bank.last_blockhash();
bank.store_account(&nonce.pubkey(), &nonce_account);
let ix = system_instruction::assign(&nonce.pubkey(), &Pubkey::new(&[9u8; 32]));
let message = Message::new(&[ix], Some(&nonce.pubkey()));
let tx = Transaction::new(&[&nonce], message, blockhash);
let expect = Err(TransactionError::InstructionError(
0,
InstructionError::ModifiedProgramId,
));
assert_eq!(bank.process_transaction(&tx), expect);
}
#[test]
fn test_durable_nonce_transaction() {
let (mut bank, _mint_keypair, custodian_keypair, nonce_keypair) =
setup_nonce_with_bank(10_000_000, |_| {}, 5_000_000, 250_000, None).unwrap();
let alice_keypair = Keypair::new();
let alice_pubkey = alice_keypair.pubkey();
let custodian_pubkey = custodian_keypair.pubkey();
let nonce_pubkey = nonce_keypair.pubkey();
assert_eq!(bank.get_balance(&custodian_pubkey), 4_750_000);
assert_eq!(bank.get_balance(&nonce_pubkey), 250_000);
/* Grab the hash stored in the nonce account */
let nonce_hash = get_nonce_account(&bank, &nonce_pubkey).unwrap();
/* Kick nonce hash off the blockhash_queue */
for _ in 0..MAX_RECENT_BLOCKHASHES + 1 {
goto_end_of_slot(Arc::get_mut(&mut bank).unwrap());
bank = Arc::new(new_from_parent(&bank));
}
/* Expect a non-Durable Nonce transfer to fail */
assert_eq!(
bank.process_transaction(&system_transaction::transfer(
&custodian_keypair,
&alice_pubkey,
100_000,
nonce_hash
),),
Err(TransactionError::BlockhashNotFound),
);
/* Check fee not charged */
assert_eq!(bank.get_balance(&custodian_pubkey), 4_750_000);
/* Durable Nonce transfer */
let durable_tx = Transaction::new_signed_with_payer(
&[
system_instruction::advance_nonce_account(&nonce_pubkey, &nonce_pubkey),
system_instruction::transfer(&custodian_pubkey, &alice_pubkey, 100_000),
],
Some(&custodian_pubkey),
&[&custodian_keypair, &nonce_keypair],
nonce_hash,
);
assert_eq!(bank.process_transaction(&durable_tx), Ok(()));
/* Check balances */
assert_eq!(bank.get_balance(&custodian_pubkey), 4_640_000);
assert_eq!(bank.get_balance(&nonce_pubkey), 250_000);
assert_eq!(bank.get_balance(&alice_pubkey), 100_000);
/* Confirm stored nonce has advanced */
let new_nonce = get_nonce_account(&bank, &nonce_pubkey).unwrap();
assert_ne!(nonce_hash, new_nonce);
/* Durable Nonce re-use fails */
let durable_tx = Transaction::new_signed_with_payer(
&[
system_instruction::advance_nonce_account(&nonce_pubkey, &nonce_pubkey),
system_instruction::transfer(&custodian_pubkey, &alice_pubkey, 100_000),
],
Some(&custodian_pubkey),
&[&custodian_keypair, &nonce_keypair],
nonce_hash,
);
assert_eq!(
bank.process_transaction(&durable_tx),
Err(TransactionError::BlockhashNotFound)
);
/* Check fee not charged and nonce not advanced */
assert_eq!(bank.get_balance(&custodian_pubkey), 4_640_000);
assert_eq!(new_nonce, get_nonce_account(&bank, &nonce_pubkey).unwrap());
let nonce_hash = new_nonce;
/* Kick nonce hash off the blockhash_queue */
for _ in 0..MAX_RECENT_BLOCKHASHES + 1 {
goto_end_of_slot(Arc::get_mut(&mut bank).unwrap());
bank = Arc::new(new_from_parent(&bank));
}
let durable_tx = Transaction::new_signed_with_payer(
&[
system_instruction::advance_nonce_account(&nonce_pubkey, &nonce_pubkey),
system_instruction::transfer(&custodian_pubkey, &alice_pubkey, 100_000_000),
],
Some(&custodian_pubkey),
&[&custodian_keypair, &nonce_keypair],
nonce_hash,
);
assert_eq!(
bank.process_transaction(&durable_tx),
Err(TransactionError::InstructionError(
1,
system_instruction::SystemError::ResultWithNegativeLamports.into(),
))
);
/* Check fee charged and nonce has advanced */
assert_eq!(bank.get_balance(&custodian_pubkey), 4_630_000);
assert_ne!(nonce_hash, get_nonce_account(&bank, &nonce_pubkey).unwrap());
/* Confirm replaying a TX that failed with InstructionError::* now
* fails with TransactionError::BlockhashNotFound
*/
assert_eq!(
bank.process_transaction(&durable_tx),
Err(TransactionError::BlockhashNotFound),
);
}
#[test]
fn test_nonce_payer() {
solana_logger::setup();
let (mut bank, _mint_keypair, custodian_keypair, nonce_keypair) =
setup_nonce_with_bank(10_000_000, |_| {}, 5_000_000, 250_000, None).unwrap();
let alice_keypair = Keypair::new();
let alice_pubkey = alice_keypair.pubkey();
let custodian_pubkey = custodian_keypair.pubkey();
let nonce_pubkey = nonce_keypair.pubkey();
debug!("alice: {}", alice_pubkey);
debug!("custodian: {}", custodian_pubkey);
debug!("nonce: {}", nonce_pubkey);
debug!("nonce account: {:?}", bank.get_account(&nonce_pubkey));
debug!("cust: {:?}", bank.get_account(&custodian_pubkey));
let nonce_hash = get_nonce_account(&bank, &nonce_pubkey).unwrap();
for _ in 0..MAX_RECENT_BLOCKHASHES + 1 {
goto_end_of_slot(Arc::get_mut(&mut bank).unwrap());
bank = Arc::new(new_from_parent(&bank));
}
let durable_tx = Transaction::new_signed_with_payer(
&[
system_instruction::advance_nonce_account(&nonce_pubkey, &nonce_pubkey),
system_instruction::transfer(&custodian_pubkey, &alice_pubkey, 100_000_000),
],
Some(&nonce_pubkey),
&[&custodian_keypair, &nonce_keypair],
nonce_hash,
);
debug!("{:?}", durable_tx);
assert_eq!(
bank.process_transaction(&durable_tx),
Err(TransactionError::InstructionError(
1,
system_instruction::SystemError::ResultWithNegativeLamports.into(),
))
);
/* Check fee charged and nonce has advanced */
assert_eq!(bank.get_balance(&nonce_pubkey), 240_000);
assert_ne!(nonce_hash, get_nonce_account(&bank, &nonce_pubkey).unwrap());
}
#[test]
fn test_nonce_fee_calculator_updates() {
let (mut genesis_config, mint_keypair) = create_genesis_config(1_000_000);
genesis_config.rent.lamports_per_byte_year = 0;
let mut bank = Arc::new(Bank::new(&genesis_config));
// Deliberately use bank 0 to initialize nonce account, so that nonce account fee_calculator indicates 0 fees
let (custodian_keypair, nonce_keypair) =
nonce_setup(&mut bank, &mint_keypair, 500_000, 100_000, None).unwrap();
let custodian_pubkey = custodian_keypair.pubkey();
let nonce_pubkey = nonce_keypair.pubkey();
// Grab the hash and fee_calculator stored in the nonce account
let (stored_nonce_hash, stored_fee_calculator) = bank
.get_account(&nonce_pubkey)
.and_then(|acc| {
let state =
StateMut::<nonce::state::Versions>::state(&acc).map(|v| v.convert_to_current());
match state {
Ok(nonce::State::Initialized(ref data)) => {
Some((data.blockhash, data.fee_calculator.clone()))
}
_ => None,
}
})
.unwrap();
// Kick nonce hash off the blockhash_queue
for _ in 0..MAX_RECENT_BLOCKHASHES + 1 {
goto_end_of_slot(Arc::get_mut(&mut bank).unwrap());
bank = Arc::new(new_from_parent(&bank));
}
// Durable Nonce transfer
let nonce_tx = Transaction::new_signed_with_payer(
&[
system_instruction::advance_nonce_account(&nonce_pubkey, &nonce_pubkey),
system_instruction::transfer(
&custodian_pubkey,
&solana_sdk::pubkey::new_rand(),
100_000,
),
],
Some(&custodian_pubkey),
&[&custodian_keypair, &nonce_keypair],
stored_nonce_hash,
);
bank.process_transaction(&nonce_tx).unwrap();
// Grab the new hash and fee_calculator; both should be updated
let (nonce_hash, fee_calculator) = bank
.get_account(&nonce_pubkey)
.and_then(|acc| {
let state =
StateMut::<nonce::state::Versions>::state(&acc).map(|v| v.convert_to_current());
match state {
Ok(nonce::State::Initialized(ref data)) => {
Some((data.blockhash, data.fee_calculator.clone()))
}
_ => None,
}
})
.unwrap();
assert_ne!(stored_nonce_hash, nonce_hash);
assert_ne!(stored_fee_calculator, fee_calculator);
}
#[test]
fn test_collect_balances() {
let (genesis_config, _mint_keypair) = create_genesis_config(500);
let parent = Arc::new(Bank::new(&genesis_config));
let bank0 = Arc::new(new_from_parent(&parent));
let keypair = Keypair::new();
let pubkey0 = solana_sdk::pubkey::new_rand();
let pubkey1 = solana_sdk::pubkey::new_rand();
let program_id = Pubkey::new(&[2; 32]);
let keypair_account = AccountSharedData::new(8, 0, &program_id);
let account0 = AccountSharedData::new(11, 0, &program_id);
let program_account = AccountSharedData::new(1, 10, &Pubkey::default());
bank0.store_account(&keypair.pubkey(), &keypair_account);
bank0.store_account(&pubkey0, &account0);
bank0.store_account(&program_id, &program_account);
let instructions = vec![CompiledInstruction::new(1, &(), vec![0])];
let tx0 = Transaction::new_with_compiled_instructions(
&[&keypair],
&[pubkey0],
Hash::default(),
vec![program_id],
instructions,
);
let instructions = vec![CompiledInstruction::new(1, &(), vec![0])];
let tx1 = Transaction::new_with_compiled_instructions(
&[&keypair],
&[pubkey1],
Hash::default(),
vec![program_id],
instructions,
);
let txs = vec![tx0, tx1];
let batch = bank0.prepare_batch(txs.iter());
let balances = bank0.collect_balances(&batch);
assert_eq!(balances.len(), 2);
assert_eq!(balances[0], vec![8, 11, 1]);
assert_eq!(balances[1], vec![8, 0, 1]);
let txs: Vec<_> = txs.iter().rev().cloned().collect();
let batch = bank0.prepare_batch(txs.iter());
let balances = bank0.collect_balances(&batch);
assert_eq!(balances.len(), 2);
assert_eq!(balances[0], vec![8, 0, 1]);
assert_eq!(balances[1], vec![8, 11, 1]);
}
#[test]
fn test_pre_post_transaction_balances() {
let (mut genesis_config, _mint_keypair) = create_genesis_config(500);
let fee_rate_governor = FeeRateGovernor::new(1, 0);
genesis_config.fee_rate_governor = fee_rate_governor;
let parent = Arc::new(Bank::new(&genesis_config));
let bank0 = Arc::new(new_from_parent(&parent));
let keypair0 = Keypair::new();
let keypair1 = Keypair::new();
let pubkey0 = solana_sdk::pubkey::new_rand();
let pubkey1 = solana_sdk::pubkey::new_rand();
let pubkey2 = solana_sdk::pubkey::new_rand();
let keypair0_account = AccountSharedData::new(8, 0, &Pubkey::default());
let keypair1_account = AccountSharedData::new(9, 0, &Pubkey::default());
let account0 = AccountSharedData::new(11, 0, &&Pubkey::default());
bank0.store_account(&keypair0.pubkey(), &keypair0_account);
bank0.store_account(&keypair1.pubkey(), &keypair1_account);
bank0.store_account(&pubkey0, &account0);
let blockhash = bank0.last_blockhash();
let tx0 = system_transaction::transfer(&keypair0, &pubkey0, 2, blockhash);
let tx1 = system_transaction::transfer(&Keypair::new(), &pubkey1, 2, blockhash);
let tx2 = system_transaction::transfer(&keypair1, &pubkey2, 12, blockhash);
let txs = vec![tx0, tx1, tx2];
let lock_result = bank0.prepare_batch(txs.iter());
let (transaction_results, transaction_balances_set, inner_instructions, transaction_logs) =
bank0.load_execute_and_commit_transactions(
&lock_result,
MAX_PROCESSING_AGE,
true,
false,
false,
&mut ExecuteTimings::default(),
);
assert!(inner_instructions[0].iter().all(|ix| ix.is_empty()));
assert_eq!(transaction_logs.len(), 0);
assert_eq!(transaction_balances_set.pre_balances.len(), 3);
assert_eq!(transaction_balances_set.post_balances.len(), 3);
assert!(transaction_results.execution_results[0].0.is_ok());
assert_eq!(transaction_balances_set.pre_balances[0], vec![8, 11, 1]);
assert_eq!(transaction_balances_set.post_balances[0], vec![5, 13, 1]);
// Failed transactions still produce balance sets
// This is a TransactionError - not possible to charge fees
assert!(transaction_results.execution_results[1].0.is_err());
assert_eq!(transaction_balances_set.pre_balances[1], vec![0, 0, 1]);
assert_eq!(transaction_balances_set.post_balances[1], vec![0, 0, 1]);
// Failed transactions still produce balance sets
// This is an InstructionError - fees charged
assert!(transaction_results.execution_results[2].0.is_err());
assert_eq!(transaction_balances_set.pre_balances[2], vec![9, 0, 1]);
assert_eq!(transaction_balances_set.post_balances[2], vec![8, 0, 1]);
}
#[test]
fn test_transaction_with_duplicate_accounts_in_instruction() {
let (genesis_config, mint_keypair) = create_genesis_config(500);
let mut bank = Bank::new(&genesis_config);
fn mock_process_instruction(
_program_id: &Pubkey,
data: &[u8],
invoke_context: &mut dyn InvokeContext,
) -> result::Result<(), InstructionError> {
let keyed_accounts = invoke_context.get_keyed_accounts()?;
let lamports = data[0] as u64;
{
let mut to_account = keyed_accounts[1].try_account_ref_mut()?;
let mut dup_account = keyed_accounts[2].try_account_ref_mut()?;
dup_account.lamports -= lamports;
to_account.checked_add_lamports(lamports).unwrap();
}
keyed_accounts[0]
.try_account_ref_mut()?
.checked_sub_lamports(lamports)?;
keyed_accounts[1]
.try_account_ref_mut()?
.checked_add_lamports(lamports)?;
Ok(())
}
let mock_program_id = Pubkey::new(&[2u8; 32]);
bank.add_builtin("mock_program", mock_program_id, mock_process_instruction);
let from_pubkey = solana_sdk::pubkey::new_rand();
let to_pubkey = solana_sdk::pubkey::new_rand();
let dup_pubkey = from_pubkey;
let from_account = AccountSharedData::new(100, 1, &mock_program_id);
let to_account = AccountSharedData::new(0, 1, &mock_program_id);
bank.store_account(&from_pubkey, &from_account);
bank.store_account(&to_pubkey, &to_account);
let account_metas = vec![
AccountMeta::new(from_pubkey, false),
AccountMeta::new(to_pubkey, false),
AccountMeta::new(dup_pubkey, false),
];
let instruction = Instruction::new_with_bincode(mock_program_id, &10, account_metas);
let tx = Transaction::new_signed_with_payer(
&[instruction],
Some(&mint_keypair.pubkey()),
&[&mint_keypair],
bank.last_blockhash(),
);
let result = bank.process_transaction(&tx);
assert_eq!(result, Ok(()));
assert_eq!(bank.get_balance(&from_pubkey), 80);
assert_eq!(bank.get_balance(&to_pubkey), 20);
}
#[test]
fn test_transaction_with_program_ids_passed_to_programs() {
let (genesis_config, mint_keypair) = create_genesis_config(500);
let mut bank = Bank::new(&genesis_config);
#[allow(clippy::unnecessary_wraps)]
fn mock_process_instruction(
_program_id: &Pubkey,
_data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> result::Result<(), InstructionError> {
Ok(())
}
let mock_program_id = Pubkey::new(&[2u8; 32]);
bank.add_builtin("mock_program", mock_program_id, mock_process_instruction);
let from_pubkey = solana_sdk::pubkey::new_rand();
let to_pubkey = solana_sdk::pubkey::new_rand();
let dup_pubkey = from_pubkey;
let from_account = AccountSharedData::new(100, 1, &mock_program_id);
let to_account = AccountSharedData::new(0, 1, &mock_program_id);
bank.store_account(&from_pubkey, &from_account);
bank.store_account(&to_pubkey, &to_account);
let account_metas = vec![
AccountMeta::new(from_pubkey, false),
AccountMeta::new(to_pubkey, false),
AccountMeta::new(dup_pubkey, false),
AccountMeta::new(mock_program_id, false),
];
let instruction = Instruction::new_with_bincode(mock_program_id, &10, account_metas);
let tx = Transaction::new_signed_with_payer(
&[instruction],
Some(&mint_keypair.pubkey()),
&[&mint_keypair],
bank.last_blockhash(),
);
let result = bank.process_transaction(&tx);
assert_eq!(result, Ok(()));
}
#[test]
fn test_account_ids_after_program_ids() {
solana_logger::setup();
let (genesis_config, mint_keypair) = create_genesis_config(500);
let mut bank = Bank::new(&genesis_config);
let from_pubkey = solana_sdk::pubkey::new_rand();
let to_pubkey = solana_sdk::pubkey::new_rand();
let account_metas = vec![
AccountMeta::new(from_pubkey, false),
AccountMeta::new(to_pubkey, false),
];
let instruction =
Instruction::new_with_bincode(solana_vote_program::id(), &10, account_metas);
let mut tx = Transaction::new_signed_with_payer(
&[instruction],
Some(&mint_keypair.pubkey()),
&[&mint_keypair],
bank.last_blockhash(),
);
tx.message.account_keys.push(solana_sdk::pubkey::new_rand());
bank.add_builtin(
"mock_vote",
solana_vote_program::id(),
mock_ok_vote_processor,
);
let result = bank.process_transaction(&tx);
assert_eq!(result, Ok(()));
let account = bank.get_account(&solana_vote_program::id()).unwrap();
info!("account: {:?}", account);
assert!(account.executable);
}
#[test]
fn test_incinerator() {
let (genesis_config, mint_keypair) = create_genesis_config(1_000_000_000_000);
let bank0 = Arc::new(Bank::new(&genesis_config));
// Move to the first normal slot so normal rent behaviour applies
let bank = Bank::new_from_parent(
&bank0,
&Pubkey::default(),
genesis_config.epoch_schedule.first_normal_slot,
);
let pre_capitalization = bank.capitalization();
// Burn a non-rent exempt amount
let burn_amount = bank.get_minimum_balance_for_rent_exemption(0) - 1;
assert_eq!(bank.get_balance(&incinerator::id()), 0);
bank.transfer(burn_amount, &mint_keypair, &incinerator::id())
.unwrap();
assert_eq!(bank.get_balance(&incinerator::id()), burn_amount);
bank.freeze();
assert_eq!(bank.get_balance(&incinerator::id()), 0);
// Ensure that no rent was collected, and the entire burn amount was removed from bank
// capitalization
assert_eq!(bank.capitalization(), pre_capitalization - burn_amount);
}
#[test]
fn test_duplicate_account_key() {
solana_logger::setup();
let (genesis_config, mint_keypair) = create_genesis_config(500);
let mut bank = Bank::new(&genesis_config);
let from_pubkey = solana_sdk::pubkey::new_rand();
let to_pubkey = solana_sdk::pubkey::new_rand();
let account_metas = vec![
AccountMeta::new(from_pubkey, false),
AccountMeta::new(to_pubkey, false),
];
bank.add_builtin(
"mock_vote",
solana_vote_program::id(),
mock_ok_vote_processor,
);
let instruction =
Instruction::new_with_bincode(solana_vote_program::id(), &10, account_metas);
let mut tx = Transaction::new_signed_with_payer(
&[instruction],
Some(&mint_keypair.pubkey()),
&[&mint_keypair],
bank.last_blockhash(),
);
tx.message.account_keys.push(from_pubkey);
let result = bank.process_transaction(&tx);
assert_eq!(result, Err(TransactionError::AccountLoadedTwice));
}
#[test]
fn test_program_id_as_payer() {
solana_logger::setup();
let (genesis_config, mint_keypair) = create_genesis_config(500);
let mut bank = Bank::new(&genesis_config);
let from_pubkey = solana_sdk::pubkey::new_rand();
let to_pubkey = solana_sdk::pubkey::new_rand();
let account_metas = vec![
AccountMeta::new(from_pubkey, false),
AccountMeta::new(to_pubkey, false),
];
bank.add_builtin(
"mock_vote",
solana_vote_program::id(),
mock_ok_vote_processor,
);
let instruction =
Instruction::new_with_bincode(solana_vote_program::id(), &10, account_metas);
let mut tx = Transaction::new_signed_with_payer(
&[instruction],
Some(&mint_keypair.pubkey()),
&[&mint_keypair],
bank.last_blockhash(),
);
info!(
"mint: {} account keys: {:?}",
mint_keypair.pubkey(),
tx.message.account_keys
);
assert_eq!(tx.message.account_keys.len(), 4);
tx.message.account_keys.clear();
tx.message.account_keys.push(solana_vote_program::id());
tx.message.account_keys.push(mint_keypair.pubkey());
tx.message.account_keys.push(from_pubkey);
tx.message.account_keys.push(to_pubkey);
tx.message.instructions[0].program_id_index = 0;
tx.message.instructions[0].accounts.clear();
tx.message.instructions[0].accounts.push(2);
tx.message.instructions[0].accounts.push(3);
let result = bank.process_transaction(&tx);
assert_eq!(result, Err(TransactionError::SanitizeFailure));
}
#[allow(clippy::unnecessary_wraps)]
fn mock_ok_vote_processor(
_pubkey: &Pubkey,
_data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> std::result::Result<(), InstructionError> {
Ok(())
}
#[test]
fn test_ref_account_key_after_program_id() {
let (genesis_config, mint_keypair) = create_genesis_config(500);
let mut bank = Bank::new(&genesis_config);
let from_pubkey = solana_sdk::pubkey::new_rand();
let to_pubkey = solana_sdk::pubkey::new_rand();
let account_metas = vec![
AccountMeta::new(from_pubkey, false),
AccountMeta::new(to_pubkey, false),
];
bank.add_builtin(
"mock_vote",
solana_vote_program::id(),
mock_ok_vote_processor,
);
let instruction =
Instruction::new_with_bincode(solana_vote_program::id(), &10, account_metas);
let mut tx = Transaction::new_signed_with_payer(
&[instruction],
Some(&mint_keypair.pubkey()),
&[&mint_keypair],
bank.last_blockhash(),
);
tx.message.account_keys.push(solana_sdk::pubkey::new_rand());
assert_eq!(tx.message.account_keys.len(), 5);
tx.message.instructions[0].accounts.remove(0);
tx.message.instructions[0].accounts.push(4);
let result = bank.process_transaction(&tx);
assert_eq!(result, Ok(()));
}
#[test]
fn test_fuzz_instructions() {
solana_logger::setup();
use rand::{thread_rng, Rng};
let (genesis_config, _mint_keypair) = create_genesis_config(1_000_000_000);
let mut bank = Bank::new(&genesis_config);
let max_programs = 5;
let program_keys: Vec<_> = (0..max_programs)
.enumerate()
.map(|i| {
let key = solana_sdk::pubkey::new_rand();
let name = format!("program{:?}", i);
bank.add_builtin(&name, key, mock_ok_vote_processor);
(key, name.as_bytes().to_vec())
})
.collect();
let max_keys = 100;
let keys: Vec<_> = (0..max_keys)
.enumerate()
.map(|_| {
let key = solana_sdk::pubkey::new_rand();
let balance = if thread_rng().gen_ratio(9, 10) {
let lamports = if thread_rng().gen_ratio(1, 5) {
thread_rng().gen_range(0, 10)
} else {
thread_rng().gen_range(20, 100)
};
let space = thread_rng().gen_range(0, 10);
let owner = Pubkey::default();
let account = AccountSharedData::new(lamports, space, &owner);
bank.store_account(&key, &account);
lamports
} else {
0
};
(key, balance)
})
.collect();
let mut results = HashMap::new();
for _ in 0..2_000 {
let num_keys = if thread_rng().gen_ratio(1, 5) {
thread_rng().gen_range(0, max_keys)
} else {
thread_rng().gen_range(1, 4)
};
let num_instructions = thread_rng().gen_range(0, max_keys - num_keys);
let mut account_keys: Vec<_> = if thread_rng().gen_ratio(1, 5) {
(0..num_keys)
.map(|_| {
let idx = thread_rng().gen_range(0, keys.len());
keys[idx].0
})
.collect()
} else {
let mut inserted = HashSet::new();
(0..num_keys)
.map(|_| {
let mut idx;
loop {
idx = thread_rng().gen_range(0, keys.len());
if !inserted.contains(&idx) {
break;
}
}
inserted.insert(idx);
keys[idx].0
})
.collect()
};
let instructions: Vec<_> = if num_keys > 0 {
(0..num_instructions)
.map(|_| {
let num_accounts_to_pass = thread_rng().gen_range(0, num_keys);
let account_indexes = (0..num_accounts_to_pass)
.map(|_| thread_rng().gen_range(0, num_keys))
.collect();
let program_index: u8 = thread_rng().gen_range(0, num_keys) as u8;
if thread_rng().gen_ratio(4, 5) {
let programs_index = thread_rng().gen_range(0, program_keys.len());
account_keys[program_index as usize] = program_keys[programs_index].0;
}
CompiledInstruction::new(program_index, &10, account_indexes)
})
.collect()
} else {
vec![]
};
let account_keys_len = std::cmp::max(account_keys.len(), 2);
let num_signatures = if thread_rng().gen_ratio(1, 5) {
thread_rng().gen_range(0, account_keys_len + 10)
} else {
thread_rng().gen_range(1, account_keys_len)
};
let num_required_signatures = if thread_rng().gen_ratio(1, 5) {
thread_rng().gen_range(0, account_keys_len + 10) as u8
} else {
thread_rng().gen_range(1, std::cmp::max(2, num_signatures)) as u8
};
let num_readonly_signed_accounts = if thread_rng().gen_ratio(1, 5) {
thread_rng().gen_range(0, account_keys_len) as u8
} else {
let max = if num_required_signatures > 1 {
num_required_signatures - 1
} else {
1
};
thread_rng().gen_range(0, max) as u8
};
let num_readonly_unsigned_accounts = if thread_rng().gen_ratio(1, 5)
|| (num_required_signatures as usize) >= account_keys_len
{
thread_rng().gen_range(0, account_keys_len) as u8
} else {
thread_rng().gen_range(0, account_keys_len - num_required_signatures as usize) as u8
};
let header = MessageHeader {
num_required_signatures,
num_readonly_signed_accounts,
num_readonly_unsigned_accounts,
};
let message = Message {
header,
account_keys,
recent_blockhash: bank.last_blockhash(),
instructions,
};
let tx = Transaction {
signatures: vec![Signature::default(); num_signatures],
message,
};
let result = bank.process_transaction(&tx);
for (key, balance) in &keys {
assert_eq!(bank.get_balance(key), *balance);
}
for (key, name) in &program_keys {
let account = bank.get_account(key).unwrap();
assert!(account.executable);
assert_eq!(account.data(), name);
}
info!("result: {:?}", result);
let result_key = format!("{:?}", result);
*results.entry(result_key).or_insert(0) += 1;
}
info!("results: {:?}", results);
}
#[test]
fn test_bank_hash_consistency() {
solana_logger::setup();
let mut genesis_config = GenesisConfig::new(
&[(
Pubkey::new(&[42; 32]),
AccountSharedData::new(1_000_000_000_000, 0, &system_program::id()),
)],
&[],
);
genesis_config.creation_time = 0;
genesis_config.cluster_type = ClusterType::MainnetBeta;
genesis_config.rent.burn_percent = 100;
let mut bank = Arc::new(Bank::new(&genesis_config));
// Check a few slots, cross an epoch boundary
assert_eq!(bank.get_slots_in_epoch(0), 32);
loop {
goto_end_of_slot(Arc::get_mut(&mut bank).unwrap());
if bank.slot == 0 {
assert_eq!(
bank.hash().to_string(),
"Cn7Wmi7w1n9NbK7RGnTQ4LpbJ2LtoJoc1sufiTwb57Ya"
);
}
if bank.slot == 32 {
assert_eq!(
bank.hash().to_string(),
"BXupB8XsZukMTnDbKshJ8qPCydWnc8BKtSj7YTJ6gAH"
);
}
if bank.slot == 64 {
assert_eq!(
bank.hash().to_string(),
"EDkKefgSMSV1NhxnGnJP7R5AGZ2JZD6oxnoZtGuEGBCU"
);
}
if bank.slot == 128 {
assert_eq!(
bank.hash().to_string(),
"AtWu4tubU9zGFChfHtQghQx3RVWtMQu6Rj49rQymFc4z"
);
break;
}
bank = Arc::new(new_from_parent(&bank));
}
}
#[test]
fn test_same_program_id_uses_unqiue_executable_accounts() {
fn nested_processor(
_program_id: &Pubkey,
_data: &[u8],
invoke_context: &mut dyn InvokeContext,
) -> result::Result<(), InstructionError> {
let keyed_accounts = invoke_context.get_keyed_accounts()?;
assert_eq!(42, keyed_accounts[0].lamports().unwrap());
let mut account = keyed_accounts[0].try_account_ref_mut()?;
account.checked_add_lamports(1)?;
Ok(())
}
let (genesis_config, mint_keypair) = create_genesis_config(50000);
let mut bank = Bank::new(&genesis_config);
// Add a new program
let program1_pubkey = solana_sdk::pubkey::new_rand();
bank.add_builtin("program", program1_pubkey, nested_processor);
// Add a new program owned by the first
let program2_pubkey = solana_sdk::pubkey::new_rand();
let mut program2_account = AccountSharedData::new(42, 1, &program1_pubkey);
program2_account.executable = true;
bank.store_account(&program2_pubkey, &program2_account);
let instruction = Instruction::new_with_bincode(program2_pubkey, &10, vec![]);
let tx = Transaction::new_signed_with_payer(
&[instruction.clone(), instruction],
Some(&mint_keypair.pubkey()),
&[&mint_keypair],
bank.last_blockhash(),
);
assert!(bank.process_transaction(&tx).is_ok());
assert_eq!(1, bank.get_balance(&program1_pubkey));
assert_eq!(42, bank.get_balance(&program2_pubkey));
}
fn get_shrink_account_size() -> usize {
let (genesis_config, _mint_keypair) = create_genesis_config(1_000_000_000);
// Set root for bank 0, with caching disabled so we can get the size
// of the storage for this slot
let mut bank0 = Arc::new(Bank::new_with_config(
&genesis_config,
HashSet::new(),
false,
));
bank0.restore_old_behavior_for_fragile_tests();
goto_end_of_slot(Arc::<Bank>::get_mut(&mut bank0).unwrap());
bank0.freeze();
bank0.squash();
let sizes = bank0
.rc
.accounts
.scan_slot(0, |stored_account| Some(stored_account.stored_size()));
// Create an account such that it takes SHRINK_RATIO of the total account space for
// the slot, so when it gets pruned, the storage entry will become a shrink candidate.
let bank0_total_size: usize = sizes.into_iter().sum();
let pubkey0_size = (bank0_total_size as f64 / (1.0 - SHRINK_RATIO)).ceil();
assert!(pubkey0_size / (pubkey0_size + bank0_total_size as f64) > SHRINK_RATIO);
pubkey0_size as usize
}
#[test]
fn test_shrink_candidate_slots_cached() {
solana_logger::setup();
let (genesis_config, _mint_keypair) = create_genesis_config(1_000_000_000);
let pubkey0 = solana_sdk::pubkey::new_rand();
let pubkey1 = solana_sdk::pubkey::new_rand();
let pubkey2 = solana_sdk::pubkey::new_rand();
// Set root for bank 0, with caching enabled
let mut bank0 = Arc::new(Bank::new_with_config(&genesis_config, HashSet::new(), true));
bank0.restore_old_behavior_for_fragile_tests();
let pubkey0_size = get_shrink_account_size();
let account0 = AccountSharedData::new(1000, pubkey0_size as usize, &Pubkey::new_unique());
bank0.store_account(&pubkey0, &account0);
goto_end_of_slot(Arc::<Bank>::get_mut(&mut bank0).unwrap());
bank0.freeze();
bank0.squash();
// Flush now so that accounts cache cleaning doesn't clean up bank 0 when later
// slots add updates to the cache
bank0.force_flush_accounts_cache();
// Store some lamports in bank 1
let some_lamports = 123;
let mut bank1 = Arc::new(new_from_parent(&bank0));
bank1.deposit(&pubkey1, some_lamports);
bank1.deposit(&pubkey2, some_lamports);
goto_end_of_slot(Arc::<Bank>::get_mut(&mut bank1).unwrap());
bank1.freeze();
bank1.squash();
// Flush now so that accounts cache cleaning doesn't clean up bank 0 when later
// slots add updates to the cache
bank1.force_flush_accounts_cache();
// Store some lamports for pubkey1 in bank 2, root bank 2
let mut bank2 = Arc::new(new_from_parent(&bank1));
bank2.deposit(&pubkey1, some_lamports);
bank2.store_account(&pubkey0, &account0);
goto_end_of_slot(Arc::<Bank>::get_mut(&mut bank2).unwrap());
bank2.freeze();
bank2.squash();
bank2.force_flush_accounts_cache();
// Clean accounts, which should add earlier slots to the shrink
// candidate set
bank2.clean_accounts(false);
// Slots 0 and 1 should be candidates for shrinking, but slot 2
// shouldn't because none of its accounts are outdated by a later
// root
assert_eq!(bank2.shrink_candidate_slots(), 2);
let alive_counts: Vec<usize> = (0..3)
.map(|slot| {
bank2
.rc
.accounts
.accounts_db
.alive_account_count_in_slot(slot)
})
.collect();
// No more slots should be shrunk
assert_eq!(bank2.shrink_candidate_slots(), 0);
// alive_counts represents the count of alive accounts in the three slots 0,1,2
assert_eq!(alive_counts, vec![9, 1, 7]);
}
#[test]
fn test_process_stale_slot_with_budget() {
solana_logger::setup();
let (genesis_config, _mint_keypair) = create_genesis_config(1_000_000_000);
let pubkey1 = solana_sdk::pubkey::new_rand();
let pubkey2 = solana_sdk::pubkey::new_rand();
let mut bank = Arc::new(Bank::new(&genesis_config));
bank.restore_old_behavior_for_fragile_tests();
assert_eq!(bank.process_stale_slot_with_budget(0, 0), 0);
assert_eq!(bank.process_stale_slot_with_budget(133, 0), 133);
assert_eq!(bank.process_stale_slot_with_budget(0, 100), 0);
assert_eq!(bank.process_stale_slot_with_budget(33, 100), 0);
assert_eq!(bank.process_stale_slot_with_budget(133, 100), 33);
goto_end_of_slot(Arc::<Bank>::get_mut(&mut bank).unwrap());
bank.squash();
let some_lamports = 123;
let mut bank = Arc::new(new_from_parent(&bank));
bank.deposit(&pubkey1, some_lamports);
bank.deposit(&pubkey2, some_lamports);
goto_end_of_slot(Arc::<Bank>::get_mut(&mut bank).unwrap());
let mut bank = Arc::new(new_from_parent(&bank));
bank.deposit(&pubkey1, some_lamports);
goto_end_of_slot(Arc::<Bank>::get_mut(&mut bank).unwrap());
bank.squash();
bank.clean_accounts(false);
let force_to_return_alive_account = 0;
assert_eq!(
bank.process_stale_slot_with_budget(22, force_to_return_alive_account),
22
);
let consumed_budgets: usize = (0..3)
.map(|_| bank.process_stale_slot_with_budget(0, force_to_return_alive_account))
.sum();
// consumed_budgets represents the count of alive accounts in the three slots 0,1,2
assert_eq!(consumed_budgets, 10);
}
#[test]
fn test_upgrade_epoch() {
let GenesisConfigInfo {
mut genesis_config,
mint_keypair,
..
} = create_genesis_config_with_leader(500, &solana_sdk::pubkey::new_rand(), 0);
genesis_config.fee_rate_governor = FeeRateGovernor::new(1, 0);
let bank = Arc::new(Bank::new(&genesis_config));
// Jump to the test-only upgrade epoch -- see `Bank::upgrade_epoch()`
let bank = Bank::new_from_parent(
&bank,
&Pubkey::default(),
genesis_config
.epoch_schedule
.get_first_slot_in_epoch(0xdead),
);
assert_eq!(bank.get_balance(&mint_keypair.pubkey()), 500);
// Normal transfers are not allowed
assert_eq!(
bank.transfer(2, &mint_keypair, &mint_keypair.pubkey()),
Err(TransactionError::ClusterMaintenance)
);
assert_eq!(bank.get_balance(&mint_keypair.pubkey()), 500); // no transaction fee charged
let vote_pubkey = solana_sdk::pubkey::new_rand();
let authorized_voter = Keypair::new();
// VoteInstruction::Vote is allowed. The transaction fails with a vote program instruction
// error because the vote account is not actually setup
let tx = Transaction::new_signed_with_payer(
&[vote_instruction::vote(
&vote_pubkey,
&authorized_voter.pubkey(),
Vote::new(vec![1], Hash::default()),
)],
Some(&mint_keypair.pubkey()),
&[&mint_keypair, &authorized_voter],
bank.last_blockhash(),
);
assert_eq!(
bank.process_transaction(&tx),
Err(TransactionError::InstructionError(
0,
InstructionError::InvalidAccountOwner
))
);
assert_eq!(bank.get_balance(&mint_keypair.pubkey()), 498); // transaction fee charged
// VoteInstruction::VoteSwitch is allowed. The transaction fails with a vote program
// instruction error because the vote account is not actually setup
let tx = Transaction::new_signed_with_payer(
&[vote_instruction::vote_switch(
&vote_pubkey,
&authorized_voter.pubkey(),
Vote::new(vec![1], Hash::default()),
Hash::default(),
)],
Some(&mint_keypair.pubkey()),
&[&mint_keypair, &authorized_voter],
bank.last_blockhash(),
);
assert_eq!(
bank.process_transaction(&tx),
Err(TransactionError::InstructionError(
0,
InstructionError::InvalidAccountOwner
))
);
assert_eq!(bank.get_balance(&mint_keypair.pubkey()), 496); // transaction fee charged
// Other vote program instructions, like VoteInstruction::UpdateCommission are not allowed
let tx = Transaction::new_signed_with_payer(
&[vote_instruction::update_commission(
&vote_pubkey,
&authorized_voter.pubkey(),
123,
)],
Some(&mint_keypair.pubkey()),
&[&mint_keypair, &authorized_voter],
bank.last_blockhash(),
);
assert_eq!(
bank.process_transaction(&tx),
Err(TransactionError::ClusterMaintenance)
);
assert_eq!(bank.get_balance(&mint_keypair.pubkey()), 496); // no transaction fee charged
}
#[test]
fn test_add_builtin_no_overwrite() {
let (genesis_config, _mint_keypair) = create_genesis_config(100_000);
#[allow(clippy::unnecessary_wraps)]
fn mock_ix_processor(
_pubkey: &Pubkey,
_data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> std::result::Result<(), InstructionError> {
Ok(())
}
let slot = 123;
let program_id = solana_sdk::pubkey::new_rand();
let mut bank = Arc::new(Bank::new_from_parent(
&Arc::new(Bank::new(&genesis_config)),
&Pubkey::default(),
slot,
));
assert_eq!(bank.get_account_modified_slot(&program_id), None);
Arc::get_mut(&mut bank)
.unwrap()
.add_builtin("mock_program", program_id, mock_ix_processor);
assert_eq!(bank.get_account_modified_slot(&program_id).unwrap().1, slot);
let mut bank = Arc::new(new_from_parent(&bank));
Arc::get_mut(&mut bank)
.unwrap()
.add_builtin("mock_program", program_id, mock_ix_processor);
assert_eq!(bank.get_account_modified_slot(&program_id).unwrap().1, slot);
Arc::get_mut(&mut bank).unwrap().replace_builtin(
"mock_program v2",
program_id,
mock_ix_processor,
);
assert_eq!(
bank.get_account_modified_slot(&program_id).unwrap().1,
bank.slot()
);
}
#[test]
fn test_add_builtin_loader_no_overwrite() {
let (genesis_config, _mint_keypair) = create_genesis_config(100_000);
#[allow(clippy::unnecessary_wraps)]
fn mock_ix_processor(
_pubkey: &Pubkey,
_data: &[u8],
_context: &mut dyn InvokeContext,
) -> std::result::Result<(), InstructionError> {
Ok(())
}
let slot = 123;
let loader_id = solana_sdk::pubkey::new_rand();
let mut bank = Arc::new(Bank::new_from_parent(
&Arc::new(Bank::new(&genesis_config)),
&Pubkey::default(),
slot,
));
assert_eq!(bank.get_account_modified_slot(&loader_id), None);
Arc::get_mut(&mut bank)
.unwrap()
.add_builtin("mock_program", loader_id, mock_ix_processor);
assert_eq!(bank.get_account_modified_slot(&loader_id).unwrap().1, slot);
let mut bank = Arc::new(new_from_parent(&bank));
Arc::get_mut(&mut bank)
.unwrap()
.add_builtin("mock_program", loader_id, mock_ix_processor);
assert_eq!(bank.get_account_modified_slot(&loader_id).unwrap().1, slot);
}
#[test]
fn test_add_native_program() {
let (mut genesis_config, _mint_keypair) = create_genesis_config(100_000);
activate_all_features(&mut genesis_config);
let slot = 123;
let program_id = solana_sdk::pubkey::new_rand();
let bank = Arc::new(Bank::new_from_parent(
&Arc::new(Bank::new(&genesis_config)),
&Pubkey::default(),
slot,
));
assert_eq!(bank.get_account_modified_slot(&program_id), None);
assert_capitalization_diff(
&bank,
|| bank.add_native_program("mock_program", &program_id, false),
|old, new| {
assert_eq!(old + 1, new);
},
);
assert_eq!(bank.get_account_modified_slot(&program_id).unwrap().1, slot);
let bank = Arc::new(new_from_parent(&bank));
assert_capitalization_diff(
&bank,
|| bank.add_native_program("mock_program", &program_id, false),
|old, new| assert_eq!(old, new),
);
assert_eq!(bank.get_account_modified_slot(&program_id).unwrap().1, slot);
let bank = Arc::new(new_from_parent(&bank));
// When replacing native_program, name must change to disambiguate from repeated
// invocations.
assert_capitalization_diff(
&bank,
|| bank.add_native_program("mock_program v2", &program_id, true),
|old, new| assert_eq!(old, new),
);
assert_eq!(
bank.get_account_modified_slot(&program_id).unwrap().1,
bank.slot()
);
let bank = Arc::new(new_from_parent(&bank));
assert_capitalization_diff(
&bank,
|| bank.add_native_program("mock_program v2", &program_id, true),
|old, new| assert_eq!(old, new),
);
// replacing with same name shouldn't update account
assert_eq!(
bank.get_account_modified_slot(&program_id).unwrap().1,
bank.parent_slot()
);
}
#[test]
fn test_add_native_program_inherited_cap_while_replacing() {
let (genesis_config, mint_keypair) = create_genesis_config(100_000);
let bank = Bank::new(&genesis_config);
let program_id = solana_sdk::pubkey::new_rand();
bank.add_native_program("mock_program", &program_id, false);
assert_eq!(bank.capitalization(), bank.calculate_capitalization());
// someone mess with program_id's balance
bank.withdraw(&mint_keypair.pubkey(), 10).unwrap();
assert_ne!(bank.capitalization(), bank.calculate_capitalization());
bank.deposit(&program_id, 10);
assert_eq!(bank.capitalization(), bank.calculate_capitalization());
bank.add_native_program("mock_program v2", &program_id, true);
assert_eq!(bank.capitalization(), bank.calculate_capitalization());
}
#[test]
fn test_add_native_program_squatted_while_not_replacing() {
let (genesis_config, mint_keypair) = create_genesis_config(100_000);
let bank = Bank::new(&genesis_config);
let program_id = solana_sdk::pubkey::new_rand();
// someone managed to squat at program_id!
bank.withdraw(&mint_keypair.pubkey(), 10).unwrap();
assert_ne!(bank.capitalization(), bank.calculate_capitalization());
bank.deposit(&program_id, 10);
assert_eq!(bank.capitalization(), bank.calculate_capitalization());
bank.add_native_program("mock_program", &program_id, false);
assert_eq!(bank.capitalization(), bank.calculate_capitalization());
}
#[test]
#[should_panic(
expected = "Can't change frozen bank by adding not-existing new native \
program (mock_program, CiXgo2KHKSDmDnV1F6B69eWFgNAPiSBjjYvfB4cvRNre). \
Maybe, inconsistent program activation is detected on snapshot restore?"
)]
fn test_add_native_program_after_frozen() {
use std::str::FromStr;
let (genesis_config, _mint_keypair) = create_genesis_config(100_000);
let slot = 123;
let program_id = Pubkey::from_str("CiXgo2KHKSDmDnV1F6B69eWFgNAPiSBjjYvfB4cvRNre").unwrap();
let bank = Bank::new_from_parent(
&Arc::new(Bank::new(&genesis_config)),
&Pubkey::default(),
slot,
);
bank.freeze();
bank.add_native_program("mock_program", &program_id, false);
}
#[test]
#[should_panic(
expected = "There is no account to replace with native program (mock_program, \
CiXgo2KHKSDmDnV1F6B69eWFgNAPiSBjjYvfB4cvRNre)."
)]
fn test_add_native_program_replace_none() {
use std::str::FromStr;
let (genesis_config, _mint_keypair) = create_genesis_config(100_000);
let slot = 123;
let program_id = Pubkey::from_str("CiXgo2KHKSDmDnV1F6B69eWFgNAPiSBjjYvfB4cvRNre").unwrap();
let bank = Bank::new_from_parent(
&Arc::new(Bank::new(&genesis_config)),
&Pubkey::default(),
slot,
);
bank.add_native_program("mock_program", &program_id, true);
}
#[test]
fn test_reconfigure_token2_native_mint() {
solana_logger::setup();
let mut genesis_config =
create_genesis_config_with_leader(5, &solana_sdk::pubkey::new_rand(), 0).genesis_config;
// ClusterType::Development - Native mint exists immediately
assert_eq!(genesis_config.cluster_type, ClusterType::Development);
let bank = Arc::new(Bank::new(&genesis_config));
assert_eq!(
bank.get_balance(&inline_spl_token_v2_0::native_mint::id()),
1000000000
);
// Testnet - Native mint blinks into existence at epoch 93
genesis_config.cluster_type = ClusterType::Testnet;
let bank = Arc::new(Bank::new(&genesis_config));
assert_eq!(
bank.get_balance(&inline_spl_token_v2_0::native_mint::id()),
0
);
bank.deposit(&inline_spl_token_v2_0::native_mint::id(), 4200000000);
let bank = Bank::new_from_parent(
&bank,
&Pubkey::default(),
genesis_config.epoch_schedule.get_first_slot_in_epoch(93),
);
let native_mint_account = bank
.get_account(&inline_spl_token_v2_0::native_mint::id())
.unwrap();
assert_eq!(native_mint_account.data().len(), 82);
assert_eq!(
bank.get_balance(&inline_spl_token_v2_0::native_mint::id()),
4200000000
);
assert_eq!(native_mint_account.owner(), &inline_spl_token_v2_0::id());
// MainnetBeta - Native mint blinks into existence at epoch 75
genesis_config.cluster_type = ClusterType::MainnetBeta;
let bank = Arc::new(Bank::new(&genesis_config));
assert_eq!(
bank.get_balance(&inline_spl_token_v2_0::native_mint::id()),
0
);
bank.deposit(&inline_spl_token_v2_0::native_mint::id(), 4200000000);
let bank = Bank::new_from_parent(
&bank,
&Pubkey::default(),
genesis_config.epoch_schedule.get_first_slot_in_epoch(75),
);
let native_mint_account = bank
.get_account(&inline_spl_token_v2_0::native_mint::id())
.unwrap();
assert_eq!(native_mint_account.data().len(), 82);
assert_eq!(
bank.get_balance(&inline_spl_token_v2_0::native_mint::id()),
4200000000
);
assert_eq!(native_mint_account.owner(), &inline_spl_token_v2_0::id());
}
#[test]
fn test_ensure_no_storage_rewards_pool() {
solana_logger::setup();
let mut genesis_config =
create_genesis_config_with_leader(5, &solana_sdk::pubkey::new_rand(), 0).genesis_config;
// Testnet - Storage rewards pool is purged at epoch 93
// Also this is with bad capitalization
genesis_config.cluster_type = ClusterType::Testnet;
genesis_config.inflation = Inflation::default();
let reward_pubkey = solana_sdk::pubkey::new_rand();
genesis_config.rewards_pools.insert(
reward_pubkey,
Account::new(u64::MAX, 0, &solana_sdk::pubkey::new_rand()),
);
let bank0 = Bank::new(&genesis_config);
// because capitalization has been reset with bogus capitalization calculation allowing overflows,
// deliberately substract 1 lamport to simulate it
bank0.capitalization.fetch_sub(1, Relaxed);
let bank0 = Arc::new(bank0);
assert_eq!(bank0.get_balance(&reward_pubkey), u64::MAX,);
let bank1 = Bank::new_from_parent(
&bank0,
&Pubkey::default(),
genesis_config.epoch_schedule.get_first_slot_in_epoch(93),
);
// assert that everything gets in order....
assert!(bank1.get_account(&reward_pubkey).is_none());
let sysvar_and_native_proram_delta = 1;
assert_eq!(
bank0.capitalization() + 1 + 1_000_000_000 + sysvar_and_native_proram_delta,
bank1.capitalization()
);
assert_eq!(bank1.capitalization(), bank1.calculate_capitalization());
// Depending on RUSTFLAGS, this test exposes rust's checked math behavior or not...
// So do some convolted setup; anyway this test itself will just be temporary
let bank0 = std::panic::AssertUnwindSafe(bank0);
let overflowing_capitalization =
std::panic::catch_unwind(|| bank0.calculate_capitalization());
if let Ok(overflowing_capitalization) = overflowing_capitalization {
info!("asserting overflowing capitalization for bank0");
assert_eq!(overflowing_capitalization, bank0.capitalization());
} else {
info!("NOT-asserting overflowing capitalization for bank0");
}
}
#[derive(Debug)]
struct TestExecutor {}
impl Executor for TestExecutor {
fn execute(
&self,
_loader_id: &Pubkey,
_program_id: &Pubkey,
_instruction_data: &[u8],
_invoke_context: &mut dyn InvokeContext,
_use_jit: bool,
) -> std::result::Result<(), InstructionError> {
Ok(())
}
}
#[test]
fn test_cached_executors() {
let key1 = solana_sdk::pubkey::new_rand();
let key2 = solana_sdk::pubkey::new_rand();
let key3 = solana_sdk::pubkey::new_rand();
let key4 = solana_sdk::pubkey::new_rand();
let executor: Arc<dyn Executor> = Arc::new(TestExecutor {});
let mut cache = CachedExecutors::new(3);
cache.put(&key1, executor.clone());
cache.put(&key2, executor.clone());
cache.put(&key3, executor.clone());
assert!(cache.get(&key1).is_some());
assert!(cache.get(&key2).is_some());
assert!(cache.get(&key3).is_some());
assert!(cache.get(&key1).is_some());
assert!(cache.get(&key1).is_some());
assert!(cache.get(&key2).is_some());
cache.put(&key4, executor.clone());
assert!(cache.get(&key1).is_some());
assert!(cache.get(&key2).is_some());
assert!(cache.get(&key3).is_none());
assert!(cache.get(&key4).is_some());
assert!(cache.get(&key4).is_some());
assert!(cache.get(&key4).is_some());
assert!(cache.get(&key4).is_some());
cache.put(&key3, executor.clone());
assert!(cache.get(&key1).is_some());
assert!(cache.get(&key2).is_none());
assert!(cache.get(&key3).is_some());
assert!(cache.get(&key4).is_some());
}
#[test]
fn test_bank_executor_cache() {
solana_logger::setup();
let (genesis_config, _) = create_genesis_config(1);
let bank = Bank::new(&genesis_config);
let key1 = solana_sdk::pubkey::new_rand();
let key2 = solana_sdk::pubkey::new_rand();
let key3 = solana_sdk::pubkey::new_rand();
let key4 = solana_sdk::pubkey::new_rand();
let executor: Arc<dyn Executor> = Arc::new(TestExecutor {});
let message = Message {
header: MessageHeader {
num_required_signatures: 1,
num_readonly_signed_accounts: 0,
num_readonly_unsigned_accounts: 1,
},
account_keys: vec![key1, key2],
recent_blockhash: Hash::default(),
instructions: vec![],
};
let loaders = &[
vec![
(key3, AccountSharedData::default()),
(key4, AccountSharedData::default()),
],
vec![(key1, AccountSharedData::default())],
];
// don't do any work if not dirty
let mut executors = Executors::default();
executors.insert(key1, executor.clone());
executors.insert(key2, executor.clone());
executors.insert(key3, executor.clone());
executors.insert(key4, executor.clone());
let executors = Rc::new(RefCell::new(executors));
executors.borrow_mut().is_dirty = false;
bank.update_executors(executors);
let executors = bank.get_executors(&message, loaders);
assert_eq!(executors.borrow().executors.len(), 0);
// do work
let mut executors = Executors::default();
executors.insert(key1, executor.clone());
executors.insert(key2, executor.clone());
executors.insert(key3, executor.clone());
executors.insert(key4, executor.clone());
let executors = Rc::new(RefCell::new(executors));
bank.update_executors(executors);
let executors = bank.get_executors(&message, loaders);
assert_eq!(executors.borrow().executors.len(), 4);
assert!(executors.borrow().executors.contains_key(&key1));
assert!(executors.borrow().executors.contains_key(&key2));
assert!(executors.borrow().executors.contains_key(&key3));
assert!(executors.borrow().executors.contains_key(&key4));
// Check inheritance
let bank = Bank::new_from_parent(&Arc::new(bank), &solana_sdk::pubkey::new_rand(), 1);
let executors = bank.get_executors(&message, loaders);
assert_eq!(executors.borrow().executors.len(), 4);
assert!(executors.borrow().executors.contains_key(&key1));
assert!(executors.borrow().executors.contains_key(&key2));
assert!(executors.borrow().executors.contains_key(&key3));
assert!(executors.borrow().executors.contains_key(&key4));
bank.remove_executor(&key1);
bank.remove_executor(&key2);
bank.remove_executor(&key3);
bank.remove_executor(&key4);
let executors = bank.get_executors(&message, loaders);
assert_eq!(executors.borrow().executors.len(), 0);
assert!(!executors.borrow().executors.contains_key(&key1));
assert!(!executors.borrow().executors.contains_key(&key2));
assert!(!executors.borrow().executors.contains_key(&key3));
assert!(!executors.borrow().executors.contains_key(&key4));
}
#[test]
fn test_bank_executor_cow() {
solana_logger::setup();
let (genesis_config, _) = create_genesis_config(1);
let root = Arc::new(Bank::new(&genesis_config));
let key1 = solana_sdk::pubkey::new_rand();
let key2 = solana_sdk::pubkey::new_rand();
let executor: Arc<dyn Executor> = Arc::new(TestExecutor {});
let loaders = &[vec![
(key1, AccountSharedData::default()),
(key2, AccountSharedData::default()),
]];
// add one to root bank
let mut executors = Executors::default();
executors.insert(key1, executor.clone());
let executors = Rc::new(RefCell::new(executors));
root.update_executors(executors);
let executors = root.get_executors(&Message::default(), loaders);
assert_eq!(executors.borrow().executors.len(), 1);
let fork1 = Bank::new_from_parent(&root, &Pubkey::default(), 1);
let fork2 = Bank::new_from_parent(&root, &Pubkey::default(), 1);
let executors = fork1.get_executors(&Message::default(), loaders);
assert_eq!(executors.borrow().executors.len(), 1);
let executors = fork2.get_executors(&Message::default(), loaders);
assert_eq!(executors.borrow().executors.len(), 1);
let mut executors = Executors::default();
executors.insert(key2, executor.clone());
let executors = Rc::new(RefCell::new(executors));
fork1.update_executors(executors);
let executors = fork1.get_executors(&Message::default(), loaders);
assert_eq!(executors.borrow().executors.len(), 2);
let executors = fork2.get_executors(&Message::default(), loaders);
assert_eq!(executors.borrow().executors.len(), 1);
fork1.remove_executor(&key1);
let executors = fork1.get_executors(&Message::default(), loaders);
assert_eq!(executors.borrow().executors.len(), 1);
let executors = fork2.get_executors(&Message::default(), loaders);
assert_eq!(executors.borrow().executors.len(), 1);
}
#[test]
fn test_compute_active_feature_set() {
let (genesis_config, _mint_keypair) = create_genesis_config(100_000);
let bank0 = Arc::new(Bank::new(&genesis_config));
let mut bank = Bank::new_from_parent(&bank0, &Pubkey::default(), 1);
let test_feature = "TestFeature11111111111111111111111111111111"
.parse::<Pubkey>()
.unwrap();
let mut feature_set = FeatureSet::default();
feature_set.inactive.insert(test_feature);
bank.feature_set = Arc::new(feature_set.clone());
let new_activations = bank.compute_active_feature_set(true);
assert!(new_activations.is_empty());
assert!(!bank.feature_set.is_active(&test_feature));
// Depositing into the `test_feature` account should do nothing
bank.deposit(&test_feature, 42);
let new_activations = bank.compute_active_feature_set(true);
assert!(new_activations.is_empty());
assert!(!bank.feature_set.is_active(&test_feature));
// Request `test_feature` activation
let feature = Feature::default();
assert_eq!(feature.activated_at, None);
bank.store_account(&test_feature, &feature::create_account(&feature, 42));
// Run `compute_active_feature_set` disallowing new activations
let new_activations = bank.compute_active_feature_set(false);
assert!(new_activations.is_empty());
assert!(!bank.feature_set.is_active(&test_feature));
let feature = feature::from_account(&bank.get_account(&test_feature).expect("get_account"))
.expect("from_account");
assert_eq!(feature.activated_at, None);
// Run `compute_active_feature_set` allowing new activations
let new_activations = bank.compute_active_feature_set(true);
assert_eq!(new_activations.len(), 1);
assert!(bank.feature_set.is_active(&test_feature));
let feature = feature::from_account(&bank.get_account(&test_feature).expect("get_account"))
.expect("from_account");
assert_eq!(feature.activated_at, Some(1));
// Reset the bank's feature set
bank.feature_set = Arc::new(feature_set);
assert!(!bank.feature_set.is_active(&test_feature));
// Running `compute_active_feature_set` will not cause new activations, but
// `test_feature` is now be active
let new_activations = bank.compute_active_feature_set(true);
assert!(new_activations.is_empty());
assert!(bank.feature_set.is_active(&test_feature));
}
#[test]
fn test_spl_token_v2_self_transfer_fix() {
let (genesis_config, _mint_keypair) = create_genesis_config(0);
let mut bank = Bank::new(&genesis_config);
// Setup original token account
bank.store_account_and_update_capitalization(
&inline_spl_token_v2_0::id(),
&AccountSharedData::from(Account {
lamports: 100,
..Account::default()
}),
);
assert_eq!(bank.get_balance(&inline_spl_token_v2_0::id()), 100);
// Setup new token account
let new_token_account = AccountSharedData::from(Account {
lamports: 123,
..Account::default()
});
bank.store_account_and_update_capitalization(
&inline_spl_token_v2_0::new_token_program::id(),
&new_token_account,
);
assert_eq!(
bank.get_balance(&inline_spl_token_v2_0::new_token_program::id()),
123
);
let original_capitalization = bank.capitalization();
bank.apply_spl_token_v2_self_transfer_fix();
// New token account is now empty
assert_eq!(
bank.get_balance(&inline_spl_token_v2_0::new_token_program::id()),
0
);
// Old token account holds the new token account
assert_eq!(
bank.get_account(&inline_spl_token_v2_0::id()),
Some(new_token_account)
);
// Lamports in the old token account were burnt
assert_eq!(bank.capitalization(), original_capitalization - 100);
}
pub fn update_vote_account_timestamp(
timestamp: BlockTimestamp,
bank: &Bank,
vote_pubkey: &Pubkey,
) {
let mut vote_account = bank.get_account(vote_pubkey).unwrap_or_default();
let mut vote_state = VoteState::from(&vote_account).unwrap_or_default();
vote_state.last_timestamp = timestamp;
let versioned = VoteStateVersions::new_current(vote_state);
VoteState::to(&versioned, &mut vote_account).unwrap();
bank.store_account(vote_pubkey, &vote_account);
}
#[test]
fn test_update_clock_timestamp() {
let leader_pubkey = solana_sdk::pubkey::new_rand();
let GenesisConfigInfo {
genesis_config,
voting_keypair,
..
} = create_genesis_config_with_leader(5, &leader_pubkey, 3);
let mut bank = Bank::new(&genesis_config);
// Advance past slot 0, which has special handling.
bank = new_from_parent(&Arc::new(bank));
bank = new_from_parent(&Arc::new(bank));
assert_eq!(
bank.clock().unix_timestamp,
bank.unix_timestamp_from_genesis()
);
bank.update_clock(None);
assert_eq!(
bank.clock().unix_timestamp,
bank.unix_timestamp_from_genesis()
);
update_vote_account_timestamp(
BlockTimestamp {
slot: bank.slot(),
timestamp: bank.unix_timestamp_from_genesis() - 1,
},
&bank,
&voting_keypair.pubkey(),
);
bank.update_clock(None);
assert_eq!(
bank.clock().unix_timestamp,
bank.unix_timestamp_from_genesis()
);
update_vote_account_timestamp(
BlockTimestamp {
slot: bank.slot(),
timestamp: bank.unix_timestamp_from_genesis(),
},
&bank,
&voting_keypair.pubkey(),
);
bank.update_clock(None);
assert_eq!(
bank.clock().unix_timestamp,
bank.unix_timestamp_from_genesis()
);
update_vote_account_timestamp(
BlockTimestamp {
slot: bank.slot(),
timestamp: bank.unix_timestamp_from_genesis() + 1,
},
&bank,
&voting_keypair.pubkey(),
);
bank.update_clock(None);
assert_eq!(
bank.clock().unix_timestamp,
bank.unix_timestamp_from_genesis() + 1
);
// Timestamp cannot go backward from ancestor Bank to child
bank = new_from_parent(&Arc::new(bank));
update_vote_account_timestamp(
BlockTimestamp {
slot: bank.slot(),
timestamp: bank.unix_timestamp_from_genesis() - 1,
},
&bank,
&voting_keypair.pubkey(),
);
bank.update_clock(None);
assert_eq!(
bank.clock().unix_timestamp,
bank.unix_timestamp_from_genesis()
);
}
fn poh_estimate_offset(bank: &Bank) -> Duration {
let mut epoch_start_slot = bank.epoch_schedule.get_first_slot_in_epoch(bank.epoch());
if epoch_start_slot == bank.slot() {
epoch_start_slot = bank
.epoch_schedule
.get_first_slot_in_epoch(bank.epoch() - 1);
}
bank.slot().saturating_sub(epoch_start_slot) as u32
* Duration::from_nanos(bank.ns_per_slot as u64)
}
#[test]
fn test_warp_timestamp_again_feature_slow() {
fn max_allowable_delta_since_epoch(bank: &Bank, max_allowable_drift: u32) -> i64 {
let poh_estimate_offset = poh_estimate_offset(bank);
(poh_estimate_offset.as_secs()
+ (poh_estimate_offset * max_allowable_drift / 100).as_secs()) as i64
}
let leader_pubkey = solana_sdk::pubkey::new_rand();
let GenesisConfigInfo {
mut genesis_config,
voting_keypair,
..
} = create_genesis_config_with_leader(5, &leader_pubkey, 3);
let slots_in_epoch = 32;
genesis_config
.accounts
.remove(&feature_set::warp_timestamp_again::id())
.unwrap();
genesis_config.epoch_schedule = EpochSchedule::new(slots_in_epoch);
let mut bank = Bank::new(&genesis_config);
let recent_timestamp: UnixTimestamp = bank.unix_timestamp_from_genesis();
let additional_secs = 8; // Greater than MAX_ALLOWABLE_DRIFT_PERCENTAGE for full epoch
update_vote_account_timestamp(
BlockTimestamp {
slot: bank.slot(),
timestamp: recent_timestamp + additional_secs,
},
&bank,
&voting_keypair.pubkey(),
);
// additional_secs greater than MAX_ALLOWABLE_DRIFT_PERCENTAGE for an epoch
// timestamp bounded to 50% deviation
for _ in 0..31 {
bank = new_from_parent(&Arc::new(bank));
assert_eq!(
bank.clock().unix_timestamp,
bank.clock().epoch_start_timestamp
+ max_allowable_delta_since_epoch(&bank, MAX_ALLOWABLE_DRIFT_PERCENTAGE),
);
assert_eq!(bank.clock().epoch_start_timestamp, recent_timestamp);
}
// Request `warp_timestamp_again` activation
let feature = Feature { activated_at: None };
bank.store_account(
&feature_set::warp_timestamp_again::id(),
&feature::create_account(&feature, 42),
);
let previous_epoch_timestamp = bank.clock().epoch_start_timestamp;
let previous_timestamp = bank.clock().unix_timestamp;
// Advance to epoch boundary to activate; time is warped to estimate with no bounding
bank = new_from_parent(&Arc::new(bank));
assert_ne!(bank.clock().epoch_start_timestamp, previous_timestamp);
assert!(
bank.clock().epoch_start_timestamp
> previous_epoch_timestamp
+ max_allowable_delta_since_epoch(&bank, MAX_ALLOWABLE_DRIFT_PERCENTAGE)
);
// Refresh vote timestamp
let recent_timestamp: UnixTimestamp = bank.clock().unix_timestamp;
let additional_secs = 8;
update_vote_account_timestamp(
BlockTimestamp {
slot: bank.slot(),
timestamp: recent_timestamp + additional_secs,
},
&bank,
&voting_keypair.pubkey(),
);
// additional_secs greater than MAX_ALLOWABLE_DRIFT_PERCENTAGE for 22 slots
// timestamp bounded to 80% deviation
for _ in 0..23 {
bank = new_from_parent(&Arc::new(bank));
assert_eq!(
bank.clock().unix_timestamp,
bank.clock().epoch_start_timestamp
+ max_allowable_delta_since_epoch(&bank, MAX_ALLOWABLE_DRIFT_PERCENTAGE_SLOW),
);
assert_eq!(bank.clock().epoch_start_timestamp, recent_timestamp);
}
for _ in 0..8 {
bank = new_from_parent(&Arc::new(bank));
assert_eq!(
bank.clock().unix_timestamp,
bank.clock().epoch_start_timestamp
+ poh_estimate_offset(&bank).as_secs() as i64
+ additional_secs,
);
assert_eq!(bank.clock().epoch_start_timestamp, recent_timestamp);
}
}
#[test]
fn test_timestamp_fast() {
fn max_allowable_delta_since_epoch(bank: &Bank, max_allowable_drift: u32) -> i64 {
let poh_estimate_offset = poh_estimate_offset(bank);
(poh_estimate_offset.as_secs()
- (poh_estimate_offset * max_allowable_drift / 100).as_secs()) as i64
}
let leader_pubkey = solana_sdk::pubkey::new_rand();
let GenesisConfigInfo {
mut genesis_config,
voting_keypair,
..
} = create_genesis_config_with_leader(5, &leader_pubkey, 3);
let slots_in_epoch = 32;
genesis_config.epoch_schedule = EpochSchedule::new(slots_in_epoch);
let mut bank = Bank::new(&genesis_config);
let recent_timestamp: UnixTimestamp = bank.unix_timestamp_from_genesis();
let additional_secs = 5; // Greater than MAX_ALLOWABLE_DRIFT_PERCENTAGE_FAST for full epoch
update_vote_account_timestamp(
BlockTimestamp {
slot: bank.slot(),
timestamp: recent_timestamp - additional_secs,
},
&bank,
&voting_keypair.pubkey(),
);
// additional_secs greater than MAX_ALLOWABLE_DRIFT_PERCENTAGE_FAST for an epoch
// timestamp bounded to 25% deviation
for _ in 0..31 {
bank = new_from_parent(&Arc::new(bank));
assert_eq!(
bank.clock().unix_timestamp,
bank.clock().epoch_start_timestamp
+ max_allowable_delta_since_epoch(&bank, MAX_ALLOWABLE_DRIFT_PERCENTAGE_FAST),
);
assert_eq!(bank.clock().epoch_start_timestamp, recent_timestamp);
}
}
#[test]
fn test_program_is_native_loader() {
let (genesis_config, mint_keypair) = create_genesis_config(50000);
let bank = Bank::new(&genesis_config);
let tx = Transaction::new_signed_with_payer(
&[Instruction::new_with_bincode(
native_loader::id(),
&(),
vec![],
)],
Some(&mint_keypair.pubkey()),
&[&mint_keypair],
bank.last_blockhash(),
);
assert_eq!(
bank.process_transaction(&tx),
Err(TransactionError::InstructionError(
0,
InstructionError::UnsupportedProgramId
))
);
}
#[test]
fn test_bad_native_loader() {
let (genesis_config, mint_keypair) = create_genesis_config(50000);
let bank = Bank::new(&genesis_config);
let to_keypair = Keypair::new();
let tx = Transaction::new_signed_with_payer(
&[
system_instruction::create_account(
&mint_keypair.pubkey(),
&to_keypair.pubkey(),
10000,
0,
&native_loader::id(),
),
Instruction::new_with_bincode(
native_loader::id(),
&(),
vec![AccountMeta::new(to_keypair.pubkey(), false)],
),
],
Some(&mint_keypair.pubkey()),
&[&mint_keypair, &to_keypair],
bank.last_blockhash(),
);
assert_eq!(
bank.process_transaction(&tx),
Err(TransactionError::InstructionError(
1,
InstructionError::Custom(NativeLoaderError::InvalidAccountData as u32)
))
);
let tx = Transaction::new_signed_with_payer(
&[
system_instruction::create_account(
&mint_keypair.pubkey(),
&to_keypair.pubkey(),
10000,
100,
&native_loader::id(),
),
Instruction::new_with_bincode(
native_loader::id(),
&(),
vec![AccountMeta::new(to_keypair.pubkey(), false)],
),
],
Some(&mint_keypair.pubkey()),
&[&mint_keypair, &to_keypair],
bank.last_blockhash(),
);
assert_eq!(
bank.process_transaction(&tx),
Err(TransactionError::InstructionError(
1,
InstructionError::Custom(NativeLoaderError::InvalidAccountData as u32)
))
);
}
#[test]
fn test_debug_bank() {
let (genesis_config, _mint_keypair) = create_genesis_config(50000);
let mut bank = Bank::new(&genesis_config);
bank.finish_init(&genesis_config, None);
let debug = format!("{:#?}", bank);
assert!(!debug.is_empty());
}
fn test_store_scan_consistency<F: 'static>(accounts_db_caching_enabled: bool, update_f: F)
where
F: Fn(Arc<Bank>, crossbeam_channel::Sender<Arc<Bank>>, Arc<HashSet<Pubkey>>, Pubkey, u64)
+ std::marker::Send,
{
// Set up initial bank
let mut genesis_config = create_genesis_config_with_leader(
10,
&solana_sdk::pubkey::new_rand(),
374_999_998_287_840,
)
.genesis_config;
genesis_config.rent = Rent::free();
let bank0 = Arc::new(Bank::new_with_config(
&genesis_config,
HashSet::new(),
accounts_db_caching_enabled,
));
// Set up pubkeys to write to
let total_pubkeys = ITER_BATCH_SIZE * 10;
let total_pubkeys_to_modify = 10;
let all_pubkeys: Vec<Pubkey> = std::iter::repeat_with(solana_sdk::pubkey::new_rand)
.take(total_pubkeys)
.collect();
let program_id = system_program::id();
let starting_lamports = 1;
let starting_account = AccountSharedData::new(starting_lamports, 0, &program_id);
// Write accounts to the store
for key in &all_pubkeys {
bank0.store_account(&key, &starting_account);
}
// Set aside a subset of accounts to modify
let pubkeys_to_modify: Arc<HashSet<Pubkey>> = Arc::new(
all_pubkeys
.into_iter()
.take(total_pubkeys_to_modify)
.collect(),
);
let exit = Arc::new(AtomicBool::new(false));
// Thread that runs scan and constantly checks for
// consistency
let pubkeys_to_modify_ = pubkeys_to_modify.clone();
let exit_ = exit.clone();
// Channel over which the bank to scan is sent
let (bank_to_scan_sender, bank_to_scan_receiver): (
crossbeam_channel::Sender<Arc<Bank>>,
crossbeam_channel::Receiver<Arc<Bank>>,
) = bounded(1);
let scan_thread = Builder::new()
.name("scan".to_string())
.spawn(move || loop {
if exit_.load(Relaxed) {
return;
}
if let Ok(bank_to_scan) =
bank_to_scan_receiver.recv_timeout(Duration::from_millis(10))
{
let accounts = bank_to_scan.get_program_accounts(&program_id);
// Should never see empty accounts because no slot ever deleted
// any of the original accounts, and the scan should reflect the
// account state at some frozen slot `X` (no partial updates).
assert!(!accounts.is_empty());
let mut expected_lamports = None;
let mut target_accounts_found = HashSet::new();
for (pubkey, account) in accounts {
let account_balance = account.lamports;
if pubkeys_to_modify_.contains(&pubkey) {
target_accounts_found.insert(pubkey);
if let Some(expected_lamports) = expected_lamports {
assert_eq!(account_balance, expected_lamports);
} else {
// All pubkeys in the specified set should have the same balance
expected_lamports = Some(account_balance);
}
}
}
// Should've found all the accounts, i.e. no partial cleans should
// be detected
assert_eq!(target_accounts_found.len(), total_pubkeys_to_modify);
}
})
.unwrap();
// Thread that constantly updates the accounts, sets
// roots, and cleans
let update_thread = Builder::new()
.name("update".to_string())
.spawn(move || {
update_f(
bank0,
bank_to_scan_sender,
pubkeys_to_modify,
program_id,
starting_lamports,
);
})
.unwrap();
// Let threads run for a while, check the scans didn't see any mixed slots
std::thread::sleep(Duration::new(5, 0));
exit.store(true, Relaxed);
scan_thread.join().unwrap();
update_thread.join().unwrap();
}
#[test]
fn test_store_scan_consistency_unrooted() {
for accounts_db_caching_enabled in &[false, true] {
test_store_scan_consistency(
*accounts_db_caching_enabled,
|bank0, bank_to_scan_sender, pubkeys_to_modify, program_id, starting_lamports| {
let mut current_major_fork_bank = bank0;
loop {
let mut current_minor_fork_bank = current_major_fork_bank.clone();
let num_new_banks = 2;
let lamports = current_minor_fork_bank.slot() + starting_lamports + 1;
// Modify banks on the two banks on the minor fork
for pubkeys_to_modify in &pubkeys_to_modify
.iter()
.chunks(pubkeys_to_modify.len() / num_new_banks)
{
current_minor_fork_bank = Arc::new(Bank::new_from_parent(
¤t_minor_fork_bank,
&solana_sdk::pubkey::new_rand(),
current_minor_fork_bank.slot() + 2,
));
let account = AccountSharedData::new(lamports, 0, &program_id);
// Write partial updates to each of the banks in the minor fork so if any of them
// get cleaned up, there will be keys with the wrong account value/missing.
for key in pubkeys_to_modify {
current_minor_fork_bank.store_account(key, &account);
}
current_minor_fork_bank.freeze();
}
// All the parent banks made in this iteration of the loop
// are currently discoverable, previous parents should have
// been squashed
assert_eq!(
current_minor_fork_bank.clone().parents_inclusive().len(),
num_new_banks + 1,
);
// `next_major_bank` needs to be sandwiched between the minor fork banks
// That way, after the squash(), the minor fork has the potential to see a
// *partial* clean of the banks < `next_major_bank`.
current_major_fork_bank = Arc::new(Bank::new_from_parent(
¤t_major_fork_bank,
&solana_sdk::pubkey::new_rand(),
current_minor_fork_bank.slot() - 1,
));
let lamports = current_major_fork_bank.slot() + starting_lamports + 1;
let account = AccountSharedData::new(lamports, 0, &program_id);
for key in pubkeys_to_modify.iter() {
// Store rooted updates to these pubkeys such that the minor
// fork updates to the same keys will be deleted by clean
current_major_fork_bank.store_account(key, &account);
}
// Send the last new bank to the scan thread to perform the scan.
// Meanwhile this thread will continually set roots on a separate fork
// and squash.
/*
bank 0
/ \
minor bank 1 \
/ current_major_fork_bank
minor bank 2
*/
// The capacity of the channel is 1 so that this thread will wait for the scan to finish before starting
// the next iteration, allowing the scan to stay in sync with these updates
// such that every scan will see this interruption.
if bank_to_scan_sender.send(current_minor_fork_bank).is_err() {
// Channel was disconnected, exit
return;
}
current_major_fork_bank.freeze();
current_major_fork_bank.squash();
// Try to get cache flush/clean to overlap with the scan
current_major_fork_bank.force_flush_accounts_cache();
current_major_fork_bank.clean_accounts(false);
}
},
)
}
}
#[test]
fn test_store_scan_consistency_root() {
for accounts_db_caching_enabled in &[false, true] {
test_store_scan_consistency(
*accounts_db_caching_enabled,
|bank0, bank_to_scan_sender, pubkeys_to_modify, program_id, starting_lamports| {
let mut current_bank = bank0.clone();
let mut prev_bank = bank0;
loop {
let lamports_this_round = current_bank.slot() + starting_lamports + 1;
let account = AccountSharedData::new(lamports_this_round, 0, &program_id);
for key in pubkeys_to_modify.iter() {
current_bank.store_account(key, &account);
}
current_bank.freeze();
// Send the previous bank to the scan thread to perform the scan.
// Meanwhile this thread will squash and update roots immediately after
// so the roots will update while scanning.
//
// The capacity of the channel is 1 so that this thread will wait for the scan to finish before starting
// the next iteration, allowing the scan to stay in sync with these updates
// such that every scan will see this interruption.
if bank_to_scan_sender.send(prev_bank).is_err() {
// Channel was disconnected, exit
return;
}
current_bank.squash();
if current_bank.slot() % 2 == 0 {
current_bank.force_flush_accounts_cache();
current_bank.clean_accounts(true);
}
prev_bank = current_bank.clone();
current_bank = Arc::new(Bank::new_from_parent(
¤t_bank,
&solana_sdk::pubkey::new_rand(),
current_bank.slot() + 1,
));
}
},
);
}
}
#[test]
fn test_stake_rewrite() {
let GenesisConfigInfo { genesis_config, .. } =
create_genesis_config_with_leader(500, &solana_sdk::pubkey::new_rand(), 1);
let bank = Arc::new(Bank::new(&genesis_config));
// quickest way of creting bad stake account
let bootstrap_stake_pubkey = bank
.cloned_stake_delegations()
.keys()
.next()
.copied()
.unwrap();
let mut bootstrap_stake_account = bank.get_account(&bootstrap_stake_pubkey).unwrap();
bootstrap_stake_account.set_lamports(10000000);
bank.store_account(&bootstrap_stake_pubkey, &bootstrap_stake_account);
assert_eq!(bank.rewrite_stakes(), (1, 1));
}
#[test]
fn test_get_inflation_start_slot_devnet_testnet() {
let GenesisConfigInfo {
mut genesis_config, ..
} = create_genesis_config_with_leader(42, &solana_sdk::pubkey::new_rand(), 42);
genesis_config
.accounts
.remove(&feature_set::pico_inflation::id())
.unwrap();
genesis_config
.accounts
.remove(&feature_set::full_inflation::devnet_and_testnet::id())
.unwrap();
for pair in feature_set::FULL_INFLATION_FEATURE_PAIRS.iter() {
genesis_config.accounts.remove(&pair.vote_id).unwrap();
genesis_config.accounts.remove(&pair.enable_id).unwrap();
}
let bank = Bank::new(&genesis_config);
// Advance slot
let mut bank = new_from_parent(&Arc::new(bank));
bank = new_from_parent(&Arc::new(bank));
assert_eq!(bank.get_inflation_start_slot(), 0);
assert_eq!(bank.slot(), 2);
// Request `pico_inflation` activation
bank.store_account(
&feature_set::pico_inflation::id(),
&feature::create_account(
&Feature {
activated_at: Some(1),
},
42,
),
);
bank.compute_active_feature_set(true);
assert_eq!(bank.get_inflation_start_slot(), 1);
// Advance slot
bank = new_from_parent(&Arc::new(bank));
assert_eq!(bank.slot(), 3);
// Request `full_inflation::devnet_and_testnet` activation,
// which takes priority over pico_inflation
bank.store_account(
&feature_set::full_inflation::devnet_and_testnet::id(),
&feature::create_account(
&Feature {
activated_at: Some(2),
},
42,
),
);
bank.compute_active_feature_set(true);
assert_eq!(bank.get_inflation_start_slot(), 2);
// Request `full_inflation::mainnet::certusone` activation,
// which should have no effect on `get_inflation_start_slot`
bank.store_account(
&feature_set::full_inflation::mainnet::certusone::vote::id(),
&feature::create_account(
&Feature {
activated_at: Some(3),
},
42,
),
);
bank.store_account(
&feature_set::full_inflation::mainnet::certusone::enable::id(),
&feature::create_account(
&Feature {
activated_at: Some(3),
},
42,
),
);
bank.compute_active_feature_set(true);
assert_eq!(bank.get_inflation_start_slot(), 2);
}
#[test]
fn test_get_inflation_start_slot_mainnet() {
let GenesisConfigInfo {
mut genesis_config, ..
} = create_genesis_config_with_leader(42, &solana_sdk::pubkey::new_rand(), 42);
genesis_config
.accounts
.remove(&feature_set::pico_inflation::id())
.unwrap();
genesis_config
.accounts
.remove(&feature_set::full_inflation::devnet_and_testnet::id())
.unwrap();
for pair in feature_set::FULL_INFLATION_FEATURE_PAIRS.iter() {
genesis_config.accounts.remove(&pair.vote_id).unwrap();
genesis_config.accounts.remove(&pair.enable_id).unwrap();
}
let bank = Bank::new(&genesis_config);
// Advance slot
let mut bank = new_from_parent(&Arc::new(bank));
bank = new_from_parent(&Arc::new(bank));
assert_eq!(bank.get_inflation_start_slot(), 0);
assert_eq!(bank.slot(), 2);
// Request `pico_inflation` activation
bank.store_account(
&feature_set::pico_inflation::id(),
&feature::create_account(
&Feature {
activated_at: Some(1),
},
42,
),
);
bank.compute_active_feature_set(true);
assert_eq!(bank.get_inflation_start_slot(), 1);
// Advance slot
bank = new_from_parent(&Arc::new(bank));
assert_eq!(bank.slot(), 3);
// Request `full_inflation::mainnet::certusone` activation,
// which takes priority over pico_inflation
bank.store_account(
&feature_set::full_inflation::mainnet::certusone::vote::id(),
&feature::create_account(
&Feature {
activated_at: Some(2),
},
42,
),
);
bank.store_account(
&feature_set::full_inflation::mainnet::certusone::enable::id(),
&feature::create_account(
&Feature {
activated_at: Some(2),
},
42,
),
);
bank.compute_active_feature_set(true);
assert_eq!(bank.get_inflation_start_slot(), 2);
// Advance slot
bank = new_from_parent(&Arc::new(bank));
assert_eq!(bank.slot(), 4);
// Request `full_inflation::devnet_and_testnet` activation,
// which should have no effect on `get_inflation_start_slot`
bank.store_account(
&feature_set::full_inflation::devnet_and_testnet::id(),
&feature::create_account(
&Feature {
activated_at: Some(bank.slot()),
},
42,
),
);
bank.compute_active_feature_set(true);
assert_eq!(bank.get_inflation_start_slot(), 2);
}
#[test]
fn test_get_inflation_num_slots_with_activations() {
let GenesisConfigInfo {
mut genesis_config, ..
} = create_genesis_config_with_leader(42, &solana_sdk::pubkey::new_rand(), 42);
let slots_per_epoch = 32;
genesis_config.epoch_schedule = EpochSchedule::new(slots_per_epoch);
genesis_config
.accounts
.remove(&feature_set::pico_inflation::id())
.unwrap();
genesis_config
.accounts
.remove(&feature_set::full_inflation::devnet_and_testnet::id())
.unwrap();
for pair in feature_set::FULL_INFLATION_FEATURE_PAIRS.iter() {
genesis_config.accounts.remove(&pair.vote_id).unwrap();
genesis_config.accounts.remove(&pair.enable_id).unwrap();
}
let mut bank = Bank::new(&genesis_config);
assert_eq!(bank.get_inflation_num_slots(), 0);
for _ in 0..2 * slots_per_epoch {
bank = new_from_parent(&Arc::new(bank));
}
assert_eq!(bank.get_inflation_num_slots(), 2 * slots_per_epoch);
// Activate pico_inflation
let pico_inflation_activation_slot = bank.slot();
bank.store_account(
&feature_set::pico_inflation::id(),
&feature::create_account(
&Feature {
activated_at: Some(pico_inflation_activation_slot),
},
42,
),
);
bank.compute_active_feature_set(true);
assert_eq!(bank.get_inflation_num_slots(), slots_per_epoch);
for _ in 0..slots_per_epoch {
bank = new_from_parent(&Arc::new(bank));
}
assert_eq!(bank.get_inflation_num_slots(), 2 * slots_per_epoch);
// Activate full_inflation::devnet_and_testnet
let full_inflation_activation_slot = bank.slot();
bank.store_account(
&feature_set::full_inflation::devnet_and_testnet::id(),
&feature::create_account(
&Feature {
activated_at: Some(full_inflation_activation_slot),
},
42,
),
);
bank.compute_active_feature_set(true);
assert_eq!(bank.get_inflation_num_slots(), slots_per_epoch);
for _ in 0..slots_per_epoch {
bank = new_from_parent(&Arc::new(bank));
}
assert_eq!(bank.get_inflation_num_slots(), 2 * slots_per_epoch);
}
#[test]
fn test_get_inflation_num_slots_already_activated() {
let GenesisConfigInfo {
mut genesis_config, ..
} = create_genesis_config_with_leader(42, &solana_sdk::pubkey::new_rand(), 42);
let slots_per_epoch = 32;
genesis_config.epoch_schedule = EpochSchedule::new(slots_per_epoch);
let mut bank = Bank::new(&genesis_config);
assert_eq!(bank.get_inflation_num_slots(), 0);
for _ in 0..slots_per_epoch {
bank = new_from_parent(&Arc::new(bank));
}
assert_eq!(bank.get_inflation_num_slots(), slots_per_epoch);
for _ in 0..slots_per_epoch {
bank = new_from_parent(&Arc::new(bank));
}
assert_eq!(bank.get_inflation_num_slots(), 2 * slots_per_epoch);
}
#[test]
fn test_stake_vote_account_validity() {
let validator_vote_keypairs0 = ValidatorVoteKeypairs::new_rand();
let validator_vote_keypairs1 = ValidatorVoteKeypairs::new_rand();
let validator_keypairs = vec![&validator_vote_keypairs0, &validator_vote_keypairs1];
let GenesisConfigInfo {
genesis_config,
mint_keypair: _,
voting_keypair: _,
} = create_genesis_config_with_vote_accounts(
1_000_000_000,
&validator_keypairs,
vec![10_000; 2],
);
let bank = Arc::new(Bank::new(&genesis_config));
let stake_delegation_accounts = bank.stake_delegation_accounts(&mut null_tracer());
assert_eq!(stake_delegation_accounts.len(), 2);
let mut vote_account = bank
.get_account(&validator_vote_keypairs0.vote_keypair.pubkey())
.unwrap_or_default();
let original_lamports = vote_account.lamports;
vote_account.set_lamports(0);
// Simulate vote account removal via full withdrawal
bank.store_account(
&validator_vote_keypairs0.vote_keypair.pubkey(),
&vote_account,
);
// Modify staked vote account owner; a vote account owned by another program could be
// freely modified with malicious data
let bogus_vote_program = Pubkey::new_unique();
vote_account.lamports = original_lamports;
vote_account.set_owner(bogus_vote_program);
bank.store_account(
&validator_vote_keypairs0.vote_keypair.pubkey(),
&vote_account,
);
assert_eq!(bank.vote_accounts().len(), 1);
// Modify stake account owner; a stake account owned by another program could be freely
// modified with malicious data
let bogus_stake_program = Pubkey::new_unique();
let mut stake_account = bank
.get_account(&validator_vote_keypairs1.stake_keypair.pubkey())
.unwrap_or_default();
stake_account.set_owner(bogus_stake_program);
bank.store_account(
&validator_vote_keypairs1.stake_keypair.pubkey(),
&stake_account,
);
// Accounts must be valid stake and vote accounts
let stake_delegation_accounts = bank.stake_delegation_accounts(&mut null_tracer());
assert_eq!(stake_delegation_accounts.len(), 0);
}
#[test]
fn test_vote_epoch_panic() {
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config_with_leader(
1_000_000_000_000_000,
&Pubkey::new_unique(),
bootstrap_validator_stake_lamports(),
);
let bank = Arc::new(Bank::new(&genesis_config));
let vote_keypair = keypair_from_seed(&[1u8; 32]).unwrap();
let stake_keypair = keypair_from_seed(&[2u8; 32]).unwrap();
let mut setup_ixs = Vec::new();
setup_ixs.extend(
vote_instruction::create_account(
&mint_keypair.pubkey(),
&vote_keypair.pubkey(),
&VoteInit {
node_pubkey: mint_keypair.pubkey(),
authorized_voter: vote_keypair.pubkey(),
authorized_withdrawer: mint_keypair.pubkey(),
commission: 0,
},
1_000_000_000,
)
.into_iter(),
);
setup_ixs.extend(
stake_instruction::create_account_and_delegate_stake(
&mint_keypair.pubkey(),
&stake_keypair.pubkey(),
&vote_keypair.pubkey(),
&Authorized::auto(&mint_keypair.pubkey()),
&Lockup::default(),
1_000_000_000_000,
)
.into_iter(),
);
setup_ixs.push(vote_instruction::withdraw(
&vote_keypair.pubkey(),
&mint_keypair.pubkey(),
1_000_000_000,
&mint_keypair.pubkey(),
));
setup_ixs.push(system_instruction::transfer(
&mint_keypair.pubkey(),
&vote_keypair.pubkey(),
1_000_000_000,
));
let result = bank.process_transaction(&Transaction::new(
&[&mint_keypair, &vote_keypair, &stake_keypair],
Message::new(&setup_ixs, Some(&mint_keypair.pubkey())),
bank.last_blockhash(),
));
assert!(result.is_ok());
let _bank = Bank::new_from_parent(
&bank,
&mint_keypair.pubkey(),
genesis_config.epoch_schedule.get_first_slot_in_epoch(1),
);
}
#[test]
fn test_tx_log_order() {
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config_with_leader(
1_000_000_000_000_000,
&Pubkey::new_unique(),
bootstrap_validator_stake_lamports(),
);
let bank = Arc::new(Bank::new(&genesis_config));
*bank.transaction_log_collector_config.write().unwrap() = TransactionLogCollectorConfig {
mentioned_addresses: HashSet::new(),
filter: TransactionLogCollectorFilter::All,
};
let blockhash = bank.last_blockhash();
let sender0 = Keypair::new();
let sender1 = Keypair::new();
bank.transfer(100, &mint_keypair, &sender0.pubkey())
.unwrap();
bank.transfer(100, &mint_keypair, &sender1.pubkey())
.unwrap();
let recipient0 = Pubkey::new_unique();
let recipient1 = Pubkey::new_unique();
let tx0 = system_transaction::transfer(&sender0, &recipient0, 10, blockhash);
let success_sig = tx0.signatures[0];
let tx1 = system_transaction::transfer(&sender1, &recipient1, 110, blockhash); // Should produce insufficient funds log
let failure_sig = tx1.signatures[0];
let txs = vec![tx1, tx0];
let batch = bank.prepare_batch(txs.iter());
let log_results = bank
.load_execute_and_commit_transactions(
&batch,
MAX_PROCESSING_AGE,
false,
false,
true,
&mut ExecuteTimings::default(),
)
.3;
assert_eq!(log_results.len(), 2);
assert!(log_results[0]
.clone()
.pop()
.unwrap()
.contains(&"failed".to_string()));
assert!(log_results[1]
.clone()
.pop()
.unwrap()
.contains(&"success".to_string()));
let stored_logs = &bank.transaction_log_collector.read().unwrap().logs;
let success_log_info = stored_logs
.iter()
.find(|transaction_log_info| transaction_log_info.signature == success_sig)
.unwrap();
assert!(success_log_info.result.is_ok());
let success_log = success_log_info.log_messages.clone().pop().unwrap();
assert!(success_log.contains(&"success".to_string()));
let failure_log_info = stored_logs
.iter()
.find(|transaction_log_info| transaction_log_info.signature == failure_sig)
.unwrap();
assert!(failure_log_info.result.is_err());
let failure_log = failure_log_info.log_messages.clone().pop().unwrap();
assert!(failure_log.contains(&"failed".to_string()));
}
#[test]
fn test_get_largest_accounts() {
let GenesisConfigInfo { genesis_config, .. } =
create_genesis_config_with_leader(42, &solana_sdk::pubkey::new_rand(), 42);
let bank = Bank::new(&genesis_config);
let pubkeys: Vec<_> = (0..5).map(|_| Pubkey::new_unique()).collect();
let pubkeys_hashset: HashSet<_> = pubkeys.iter().cloned().collect();
let pubkeys_balances: Vec<_> = pubkeys
.iter()
.cloned()
.zip(vec![
sol_to_lamports(2.0),
sol_to_lamports(3.0),
sol_to_lamports(3.0),
sol_to_lamports(4.0),
sol_to_lamports(5.0),
])
.collect();
// Initialize accounts; all have larger SOL balances than current Bank built-ins
let account0 = AccountSharedData::new(pubkeys_balances[0].1, 0, &Pubkey::default());
bank.store_account(&pubkeys_balances[0].0, &account0);
let account1 = AccountSharedData::new(pubkeys_balances[1].1, 0, &Pubkey::default());
bank.store_account(&pubkeys_balances[1].0, &account1);
let account2 = AccountSharedData::new(pubkeys_balances[2].1, 0, &Pubkey::default());
bank.store_account(&pubkeys_balances[2].0, &account2);
let account3 = AccountSharedData::new(pubkeys_balances[3].1, 0, &Pubkey::default());
bank.store_account(&pubkeys_balances[3].0, &account3);
let account4 = AccountSharedData::new(pubkeys_balances[4].1, 0, &Pubkey::default());
bank.store_account(&pubkeys_balances[4].0, &account4);
// Create HashSet to exclude an account
let exclude4: HashSet<_> = pubkeys[4..].iter().cloned().collect();
let mut sorted_accounts = pubkeys_balances.clone();
sorted_accounts.sort_by(|a, b| a.1.cmp(&b.1).reverse());
// Return only one largest account
assert_eq!(
bank.get_largest_accounts(1, &pubkeys_hashset, AccountAddressFilter::Include),
vec![(pubkeys[4], sol_to_lamports(5.0))]
);
assert_eq!(
bank.get_largest_accounts(1, &HashSet::new(), AccountAddressFilter::Exclude),
vec![(pubkeys[4], sol_to_lamports(5.0))]
);
assert_eq!(
bank.get_largest_accounts(1, &exclude4, AccountAddressFilter::Exclude),
vec![(pubkeys[3], sol_to_lamports(4.0))]
);
// Return all added accounts
let results =
bank.get_largest_accounts(10, &pubkeys_hashset, AccountAddressFilter::Include);
assert_eq!(results.len(), sorted_accounts.len());
for pubkey_balance in sorted_accounts.iter() {
assert!(results.contains(pubkey_balance));
}
let mut sorted_results = results.clone();
sorted_results.sort_by(|a, b| a.1.cmp(&b.1).reverse());
assert_eq!(sorted_results, results);
let expected_accounts = sorted_accounts[1..].to_vec();
let results = bank.get_largest_accounts(10, &exclude4, AccountAddressFilter::Exclude);
// results include 5 Bank builtins
assert_eq!(results.len(), 10);
for pubkey_balance in expected_accounts.iter() {
assert!(results.contains(pubkey_balance));
}
let mut sorted_results = results.clone();
sorted_results.sort_by(|a, b| a.1.cmp(&b.1).reverse());
assert_eq!(sorted_results, results);
// Return 3 added accounts
let expected_accounts = sorted_accounts[0..4].to_vec();
let results = bank.get_largest_accounts(4, &pubkeys_hashset, AccountAddressFilter::Include);
assert_eq!(results.len(), expected_accounts.len());
for pubkey_balance in expected_accounts.iter() {
assert!(results.contains(pubkey_balance));
}
let expected_accounts = expected_accounts[1..4].to_vec();
let results = bank.get_largest_accounts(3, &exclude4, AccountAddressFilter::Exclude);
assert_eq!(results.len(), expected_accounts.len());
for pubkey_balance in expected_accounts.iter() {
assert!(results.contains(pubkey_balance));
}
// Exclude more, and non-sequential, accounts
let exclude: HashSet<_> = vec![pubkeys[0], pubkeys[2], pubkeys[4]]
.iter()
.cloned()
.collect();
assert_eq!(
bank.get_largest_accounts(2, &exclude, AccountAddressFilter::Exclude),
vec![pubkeys_balances[3], pubkeys_balances[1]]
);
}
#[test]
fn test_transfer_sysvar() {
solana_logger::setup();
let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config_with_leader(
1_000_000_000_000_000,
&Pubkey::new_unique(),
bootstrap_validator_stake_lamports(),
);
let mut bank = Bank::new(&genesis_config);
fn mock_ix_processor(
_pubkey: &Pubkey,
_data: &[u8],
invoke_context: &mut dyn InvokeContext,
) -> std::result::Result<(), InstructionError> {
use solana_sdk::account::WritableAccount;
let keyed_accounts = invoke_context.get_keyed_accounts()?;
let mut data = keyed_accounts[1].try_account_ref_mut()?;
data.data_as_mut_slice()[0] = 5;
Ok(())
}
let program_id = solana_sdk::pubkey::new_rand();
bank.add_builtin("mock_program1", program_id, mock_ix_processor);
let blockhash = bank.last_blockhash();
let blockhash_sysvar = sysvar::recent_blockhashes::id();
let orig_lamports = bank
.get_account(&sysvar::recent_blockhashes::id())
.unwrap()
.lamports;
info!("{:?}", bank.get_account(&sysvar::recent_blockhashes::id()));
let tx = system_transaction::transfer(&mint_keypair, &blockhash_sysvar, 10, blockhash);
assert_eq!(
bank.process_transaction(&tx),
Err(TransactionError::InstructionError(
0,
InstructionError::ReadonlyLamportChange
))
);
assert_eq!(
bank.get_account(&sysvar::recent_blockhashes::id())
.unwrap()
.lamports,
orig_lamports
);
info!("{:?}", bank.get_account(&sysvar::recent_blockhashes::id()));
let accounts = vec![
AccountMeta::new(mint_keypair.pubkey(), true),
AccountMeta::new(blockhash_sysvar, false),
];
let ix = Instruction::new_with_bincode(program_id, &0, accounts);
let message = Message::new(&[ix], Some(&mint_keypair.pubkey()));
let tx = Transaction::new(&[&mint_keypair], message, blockhash);
assert_eq!(
bank.process_transaction(&tx),
Err(TransactionError::InstructionError(
0,
InstructionError::ReadonlyDataModified
))
);
}
}
| 38.242062 | 128 | 0.582313 |
62480c3ae8997f23e934002d24027f1894a7cad3 | 8,644 | use super::{
context::WeakContext, events, os, Align, Color, Context, Edge, Event, FlexDirection, Justify,
Node, NodeId, PositionType, Wrap,
};
use yoga;
/// The fundamental component, `View` is a container that supports
/// layout with **Flexbox** powered by [Yoga](https://yogalayout.com/). View maps directly
/// to the native view equivalent of the platform (e.g.. `NSView` for macOS).
///
/// `View` is designed to be nested inside other views and can have 0 to many children of
/// any type.
pub struct View {
pub(crate) id: NodeId,
pub(crate) inner: os::View,
pub(crate) context: WeakContext,
}
impl View {
pub fn new(context: &Context) -> Self {
Self {
id: context.next_id(),
inner: os::View::new(),
context: context.downgrade(),
}
}
}
//
// Node
//
impl Node for View {
fn id(&self) -> NodeId {
self.id
}
}
impl os::Node for View {
fn handle(&self) -> os::NodeHandle {
self.inner.handle()
}
}
impl From<View> for NodeId {
fn from(view: View) -> NodeId {
view.id()
}
}
//
// Container
//
impl View {
pub fn add(&mut self, node: impl Node) {
if let Some(context) = self.context.upgrade() {
self.inner.add(&node);
context.emplace_node(node);
}
}
}
//
// Events
//
impl View {
pub fn mouse_down(&mut self) -> &mut Event<events::MouseDown> {
self.inner.mouse_down()
}
pub fn mouse_up(&mut self) -> &mut Event<events::MouseUp> {
self.inner.mouse_up()
}
pub fn mouse_enter(&mut self) -> &mut Event<events::MouseEnter> {
self.inner.mouse_enter()
}
pub fn mouse_leave(&mut self) -> &mut Event<events::MouseLeave> {
self.inner.mouse_leave()
}
}
//
// Style
//
impl View {
/// Sets the background color for this view.
///
/// Default: `transparent` (`0x00_00_00_00`)
pub fn set_background_color(&mut self, color: impl Into<Color>) {
self.inner.set_background_color(color.into());
}
/// Sets the corner radius for this view.
///
/// Default: `0`
pub fn set_corner_radius(&mut self, radius: f32) {
self.inner.set_corner_radius(radius);
}
/// Sets the position type for this View which determines how it is positioned
/// within its parent.
///
/// See: https://yogalayout.com/docs/absolute-relative-layout
pub fn set_position_type(&mut self, position_type: PositionType) {
self.inner.yoga_node().set_position_type(position_type);
self.inner.set_needs_layout();
}
/// Sets the relative or absolute (depending on position type) offset from the specified
/// edge for this view.
pub fn set_position(&mut self, edge: Edge, offset: f32) {
self.inner
.yoga_node()
.set_position(edge, yoga::StyleUnit::Point(offset.into()));
self.inner.set_needs_layout();
}
/// Sets the content alignment for this view.
///
/// Content alignment defines the distribution of lines along the cross-axis.
/// This only has effect when items are wrapped to multiple lines.
pub fn set_align_content(&mut self, align: Align) {
self.inner.yoga_node().set_align_content(align);
self.inner.set_needs_layout();
}
/// Sets the item alignment for this view.
pub fn set_align_items(&mut self, align: Align) {
self.inner.yoga_node().set_align_items(align);
self.inner.set_needs_layout();
}
/// Sets the self alignment for this view.
///
/// Overrides the item alignment on the parent of this view.
pub fn set_align_self(&mut self, align: Align) {
self.inner.yoga_node().set_align_self(align);
self.inner.set_needs_layout();
}
/// Sets the flex direction for this view.
pub fn set_flex_direction(&mut self, flex_direction: FlexDirection) {
self.inner.yoga_node().set_flex_direction(flex_direction);
self.inner.set_needs_layout();
}
/// Sets the flex wrap for this view.
pub fn set_flex_wrap(&mut self, wrap: Wrap) {
self.inner.yoga_node().set_flex_wrap(wrap);
self.inner.set_needs_layout();
}
/// Sets the flex grow for this view.
///
/// Describes how any space within a container should be distributed among
/// its children along the main axis. After laying out its children, a container
/// will distribute any remaining space according to the flex grow values
/// specified by its children.
pub fn set_flex_grow(&mut self, flex_grow: f32) {
self.inner.yoga_node().set_flex_grow(flex_grow);
self.inner.set_needs_layout();
}
/// Sets the flex shrink for this view.
///
/// Describes how to shrink children along the main axis in the case that the total size of
/// the children overflow the size of the container on the main axis. flex shrink is very
/// similar to flex grow and can be thought of in the same way if any overflowing size is
/// considered to be negative remaining space. These two properties also work well
/// together by allowing children to grow and shrink as needed.
pub fn set_flex_shrink(&mut self, flex_shrink: f32) {
self.inner.yoga_node().set_flex_shrink(flex_shrink);
self.inner.set_needs_layout();
}
/// Sets the flex basis for this view.
///
/// An axis-independent way of providing the default size of an item along the main axis.
pub fn set_flex_basis(&mut self, flex_basis: f32) {
self.inner
.yoga_node()
.set_flex_basis(yoga::StyleUnit::Point(flex_basis.into()));
self.inner.set_needs_layout();
}
/// Sets the content justification for this view.
pub fn set_justify_content(&mut self, justify: Justify) {
self.inner.yoga_node().set_justify_content(justify);
self.inner.set_needs_layout();
}
/// Sets the margin of the specified edge(s) for this view.
pub fn set_margin(&mut self, edge: Edge, margin: f32) {
self.inner
.yoga_node()
.set_margin(edge, yoga::StyleUnit::Point(margin.into()));
self.inner.set_needs_layout();
}
/// Sets the padding of the specified edge(s) for this view.
pub fn set_padding(&mut self, edge: Edge, padding: f32) {
self.inner
.yoga_node()
.set_padding(edge, yoga::StyleUnit::Point(padding.into()));
self.inner.set_needs_layout();
}
/// Sets the minimum width (in pixels) for this view.
pub fn set_min_width(&mut self, width: f32) {
self.inner
.yoga_node()
.set_min_width(yoga::StyleUnit::Point(width.into()));
self.inner.set_needs_layout();
}
/// Sets the maximum width (in pixels) for this view.
pub fn set_max_width(&mut self, width: f32) {
self.inner
.yoga_node()
.set_max_width(yoga::StyleUnit::Point(width.into()));
self.inner.set_needs_layout();
}
/// Sets the minimum height (in pixels) for this view.
pub fn set_min_height(&mut self, height: f32) {
self.inner
.yoga_node()
.set_min_height(yoga::StyleUnit::Point(height.into()));
self.inner.set_needs_layout();
}
/// Sets the maximum height (in pixels) for this view.
pub fn set_max_height(&mut self, height: f32) {
self.inner
.yoga_node()
.set_max_height(yoga::StyleUnit::Point(height.into()));
self.inner.set_needs_layout();
}
/// Sets the width (in pixels) for this view.
pub fn set_width(&mut self, width: f32) {
self.inner
.yoga_node()
.set_width(yoga::StyleUnit::Point(width.into()));
self.inner.set_needs_layout();
}
/// Sets the width (in % of the parent) for this view.
pub fn set_width_percent(&mut self, width: f32) {
self.inner
.yoga_node()
.set_width(yoga::StyleUnit::Percent(width.into()));
self.inner.set_needs_layout();
}
/// Sets the height (in pixels) for this view.
pub fn set_height(&mut self, height: f32) {
self.inner
.yoga_node()
.set_height(yoga::StyleUnit::Point(height.into()));
self.inner.set_needs_layout();
}
/// Sets the height (in % of the parent) for this view.
pub fn set_height_percent(&mut self, height: f32) {
self.inner
.yoga_node()
.set_height(yoga::StyleUnit::Percent(height.into()));
self.inner.set_needs_layout();
}
}
| 30.013889 | 97 | 0.619505 |
4bb4b8cd7024cac01fae584cc5874650adf67f2c | 3,417 | #[cfg(feature = "actix")]
mod actix {
use std::env;
use actix_web::{test, App};
use matrix_sdk_appservice::*;
async fn appservice() -> Appservice {
env::set_var("RUST_LOG", "mockito=debug,matrix_sdk=debug,ruma=debug,actix_web=debug");
let _ = tracing_subscriber::fmt::try_init();
Appservice::new(
mockito::server_url().as_ref(),
"test.local",
AppserviceRegistration::try_from_yaml_file("./tests/registration.yaml").unwrap(),
)
.await
.unwrap()
}
#[actix_rt::test]
async fn test_transactions() {
let appservice = appservice().await;
let app = test::init_service(App::new().service(appservice.actix_service())).await;
let transactions = r#"{
"events": [
{
"content": {},
"type": "m.dummy"
}
]
}"#;
let transactions: serde_json::Value = serde_json::from_str(transactions).unwrap();
let req = test::TestRequest::put()
.uri("/_matrix/app/v1/transactions/1?access_token=hs_token")
.set_json(&transactions)
.to_request();
let resp = test::call_service(&app, req).await;
assert_eq!(resp.status(), 200);
}
#[actix_rt::test]
async fn test_users() {
let appservice = appservice().await;
let app = test::init_service(App::new().service(appservice.actix_service())).await;
let req = test::TestRequest::get()
.uri("/_matrix/app/v1/users/%40_botty_1%3Adev.famedly.local?access_token=hs_token")
.to_request();
let resp = test::call_service(&app, req).await;
assert_eq!(resp.status(), 200);
}
#[actix_rt::test]
async fn test_invalid_access_token() {
let appservice = appservice().await;
let app = test::init_service(App::new().service(appservice.actix_service())).await;
let transactions = r#"{
"events": [
{
"content": {},
"type": "m.dummy"
}
]
}"#;
let transactions: serde_json::Value = serde_json::from_str(transactions).unwrap();
let req = test::TestRequest::put()
.uri("/_matrix/app/v1/transactions/1?access_token=invalid_token")
.set_json(&transactions)
.to_request();
let resp = test::call_service(&app, req).await;
assert_eq!(resp.status(), 401);
}
#[actix_rt::test]
async fn test_no_access_token() {
let appservice = appservice().await;
let app = test::init_service(App::new().service(appservice.actix_service())).await;
let transactions = r#"{
"events": [
{
"content": {},
"type": "m.dummy"
}
]
}"#;
let transactions: serde_json::Value = serde_json::from_str(transactions).unwrap();
let req = test::TestRequest::put()
.uri("/_matrix/app/v1/transactions/1")
.set_json(&transactions)
.to_request();
let resp = test::call_service(&app, req).await;
// TODO: this should actually return a 401 but is 500 because something in the
// extractor fails
assert_eq!(resp.status(), 500);
}
}
| 29.713043 | 95 | 0.539655 |
4ae260492a853aae0730e3427786c4fc60665c20 | 9,657 | // Basic newtype definition
newtype! {
#[doc = r"A controller number (0 - 127) of a MIDI Control Change message."]
name = ControllerNumber, repr = u8, max = 127
}
// From related newtype to this newtype and back
impl_from_newtype_to_newtype!(ControllerNumber, crate::U7);
impl_from_newtype_to_newtype!(crate::U7, ControllerNumber);
// From lower primitives to this newtype
// -
// From this newtype to higher primitives
impl_from_newtype_to_primitive!(ControllerNumber, u8);
impl_from_newtype_to_primitive!(ControllerNumber, i8);
impl_from_newtype_to_primitive!(ControllerNumber, u16);
impl_from_newtype_to_primitive!(ControllerNumber, i16);
impl_from_newtype_to_primitive!(ControllerNumber, u32);
impl_from_newtype_to_primitive!(ControllerNumber, i32);
impl_from_newtype_to_primitive!(ControllerNumber, u64);
impl_from_newtype_to_primitive!(ControllerNumber, i64);
impl_from_newtype_to_primitive!(ControllerNumber, u128);
impl_from_newtype_to_primitive!(ControllerNumber, i128);
impl_from_newtype_to_primitive!(ControllerNumber, usize);
impl_from_newtype_to_primitive!(ControllerNumber, isize);
// TryFrom higher primitives to this newtype
impl_try_from_primitive_to_newtype!(u8, ControllerNumber);
impl_try_from_primitive_to_newtype!(u16, ControllerNumber);
impl_try_from_primitive_to_newtype!(i16, ControllerNumber);
impl_try_from_primitive_to_newtype!(u32, ControllerNumber);
impl_try_from_primitive_to_newtype!(i32, ControllerNumber);
impl_try_from_primitive_to_newtype!(u64, ControllerNumber);
impl_try_from_primitive_to_newtype!(i64, ControllerNumber);
impl_try_from_primitive_to_newtype!(u128, ControllerNumber);
impl_try_from_primitive_to_newtype!(i128, ControllerNumber);
impl_try_from_primitive_to_newtype!(usize, ControllerNumber);
impl_try_from_primitive_to_newtype!(isize, ControllerNumber);
impl ControllerNumber {
/// Returns whether this controller number can be used to make up a 14-bit Control Change
/// message.
pub fn can_be_part_of_14_bit_control_change_message(&self) -> bool {
self.0 < 64
}
/// If this controller number can be used to send the most significant byte of a 14-bit
/// Control Change message, this function returns the corresponding controller number that would
/// be used to send the least significant byte of it.
pub fn corresponding_14_bit_lsb_controller_number(&self) -> Option<ControllerNumber> {
if self.0 >= 32 {
return None;
}
Some(ControllerNumber(self.0 + 32))
}
/// Returns whether this controller number is intended to be used to send part of a (N)RPN
/// message.
pub fn is_parameter_number_message_controller_number(&self) -> bool {
matches!(self.0, 98 | 99 | 100 | 101 | 38 | 6)
}
/// Returns whether this controller number is intended to be used to send Channel Mode
/// messages.
pub fn is_channel_mode_message_controller_number(&self) -> bool {
*self >= controller_numbers::RESET_ALL_CONTROLLERS
}
}
/// Contains predefined controller numbers.
///
/// # Design
///
/// These are not associated constants of [`ControllerNumber`] because then we could only access
/// them prefixed with `ControllerNumber::`. Making [`ControllerNumber`] an enum would have been the
/// alternative, but this has other downsides such as having to introduce a special variant for
/// undefined controllers and unnecessary conversion from and to integers. From the MIDI spec
/// perspective, a controller number seems closer to a plain 7-bit integer than to an enum with
/// well-defined values. Not all of the controller numbers have a special meaning, and if they do,
/// this meaning is not necessarily important. In practice, controller numbers are often used for
/// other things than they were intended for, especially the exotic ones.
///
/// [`ControllerNumber`]: struct.ControllerNumber.html
pub mod controller_numbers {
use crate::ControllerNumber;
pub const BANK_SELECT: ControllerNumber = ControllerNumber(0x00);
pub const MODULATION_WHEEL: ControllerNumber = ControllerNumber(0x01);
pub const BREATH_CONTROLLER: ControllerNumber = ControllerNumber(0x02);
pub const FOOT_CONTROLLER: ControllerNumber = ControllerNumber(0x04);
pub const PORTAMENTO_TIME: ControllerNumber = ControllerNumber(0x05);
pub const DATA_ENTRY_MSB: ControllerNumber = ControllerNumber(0x06);
pub const CHANNEL_VOLUME: ControllerNumber = ControllerNumber(0x07);
pub const BALANCE: ControllerNumber = ControllerNumber(0x08);
pub const PAN: ControllerNumber = ControllerNumber(0x0A);
pub const EXPRESSION_CONTROLLER: ControllerNumber = ControllerNumber(0x0B);
pub const EFFECT_CONTROL_1: ControllerNumber = ControllerNumber(0x0C);
pub const EFFECT_CONTROL_2: ControllerNumber = ControllerNumber(0x0D);
pub const GENERAL_PURPOSE_CONTROLLER_1: ControllerNumber = ControllerNumber(0x10);
pub const GENERAL_PURPOSE_CONTROLLER_2: ControllerNumber = ControllerNumber(0x11);
pub const GENERAL_PURPOSE_CONTROLLER_3: ControllerNumber = ControllerNumber(0x12);
pub const GENERAL_PURPOSE_CONTROLLER_4: ControllerNumber = ControllerNumber(0x13);
pub const BANK_SELECT_LSB: ControllerNumber = ControllerNumber(0x20);
pub const MODULATION_WHEEL_LSB: ControllerNumber = ControllerNumber(0x21);
pub const BREATH_CONTROLLER_LSB: ControllerNumber = ControllerNumber(0x22);
pub const FOOT_CONTROLLER_LSB: ControllerNumber = ControllerNumber(0x24);
pub const PORTAMENTO_TIME_LSB: ControllerNumber = ControllerNumber(0x25);
pub const DATA_ENTRY_MSB_LSB: ControllerNumber = ControllerNumber(0x26);
pub const CHANNEL_VOLUME_LSB: ControllerNumber = ControllerNumber(0x27);
pub const BALANCE_LSB: ControllerNumber = ControllerNumber(0x28);
pub const PAN_LSB: ControllerNumber = ControllerNumber(0x2A);
pub const EXPRESSION_CONTROLLER_LSB: ControllerNumber = ControllerNumber(0x2B);
pub const EFFECT_CONTROL_1_LSB: ControllerNumber = ControllerNumber(0x2C);
pub const EFFECT_CONTROL_2_LSB: ControllerNumber = ControllerNumber(0x2D);
pub const GENERAL_PURPOSE_CONTROLLER_1_LSB: ControllerNumber = ControllerNumber(0x30);
pub const GENERAL_PURPOSE_CONTROLLER_2_LSB: ControllerNumber = ControllerNumber(0x31);
pub const GENERAL_PURPOSE_CONTROLLER_3_LSB: ControllerNumber = ControllerNumber(0x32);
pub const GENERAL_PURPOSE_CONTROLLER_4_LSB: ControllerNumber = ControllerNumber(0x33);
pub const DAMPER_PEDAL_ON_OFF: ControllerNumber = ControllerNumber(0x40);
pub const PORTAMENTO_ON_OFF: ControllerNumber = ControllerNumber(0x41);
pub const SOSTENUTO_ON_OFF: ControllerNumber = ControllerNumber(0x42);
pub const SOFT_PEDAL_ON_OFF: ControllerNumber = ControllerNumber(0x43);
pub const LEGATO_FOOTSWITCH: ControllerNumber = ControllerNumber(0x44);
pub const HOLD_2: ControllerNumber = ControllerNumber(0x45);
pub const SOUND_CONTROLLER_1: ControllerNumber = ControllerNumber(0x46);
pub const SOUND_CONTROLLER_2: ControllerNumber = ControllerNumber(0x47);
pub const SOUND_CONTROLLER_3: ControllerNumber = ControllerNumber(0x48);
pub const SOUND_CONTROLLER_4: ControllerNumber = ControllerNumber(0x49);
pub const SOUND_CONTROLLER_5: ControllerNumber = ControllerNumber(0x4A);
pub const SOUND_CONTROLLER_6: ControllerNumber = ControllerNumber(0x4B);
pub const SOUND_CONTROLLER_7: ControllerNumber = ControllerNumber(0x4C);
pub const SOUND_CONTROLLER_8: ControllerNumber = ControllerNumber(0x4D);
pub const SOUND_CONTROLLER_9: ControllerNumber = ControllerNumber(0x4E);
pub const SOUND_CONTROLLER_10: ControllerNumber = ControllerNumber(0x4F);
pub const GENERAL_PURPOSE_CONTROLLER_5: ControllerNumber = ControllerNumber(0x50);
pub const GENERAL_PURPOSE_CONTROLLER_6: ControllerNumber = ControllerNumber(0x51);
pub const GENERAL_PURPOSE_CONTROLLER_7: ControllerNumber = ControllerNumber(0x52);
pub const GENERAL_PURPOSE_CONTROLLER_8: ControllerNumber = ControllerNumber(0x53);
pub const PORTAMENTO_CONTROL: ControllerNumber = ControllerNumber(0x54);
pub const HIGH_RESOLUTION_VELOCITY_PREFIX: ControllerNumber = ControllerNumber(0x58);
pub const EFFECTS_1_DEPTH: ControllerNumber = ControllerNumber(0x5B);
pub const EFFECTS_2_DEPTH: ControllerNumber = ControllerNumber(0x5C);
pub const EFFECTS_3_DEPTH: ControllerNumber = ControllerNumber(0x5D);
pub const EFFECTS_4_DEPTH: ControllerNumber = ControllerNumber(0x5E);
pub const EFFECTS_5_DEPTH: ControllerNumber = ControllerNumber(0x5F);
pub const DATA_INCREMENT: ControllerNumber = ControllerNumber(0x60);
pub const DATA_DECREMENT: ControllerNumber = ControllerNumber(0x61);
pub const NON_REGISTERED_PARAMETER_NUMBER_LSB: ControllerNumber = ControllerNumber(0x62);
pub const NON_REGISTERED_PARAMETER_NUMBER_MSB: ControllerNumber = ControllerNumber(0x63);
pub const REGISTERED_PARAMETER_NUMBER_LSB: ControllerNumber = ControllerNumber(0x64);
pub const REGISTERED_PARAMETER_NUMBER_MSB: ControllerNumber = ControllerNumber(0x65);
pub const ALL_SOUND_OFF: ControllerNumber = ControllerNumber(0x78);
pub const RESET_ALL_CONTROLLERS: ControllerNumber = ControllerNumber(0x79);
pub const LOCAL_CONTROL_ON_OFF: ControllerNumber = ControllerNumber(0x7A);
pub const ALL_NOTES_OFF: ControllerNumber = ControllerNumber(0x7B);
pub const OMNI_MODE_OFF: ControllerNumber = ControllerNumber(0x7C);
pub const OMNI_MODE_ON: ControllerNumber = ControllerNumber(0x7D);
pub const MONO_MODE_ON: ControllerNumber = ControllerNumber(0x7E);
pub const POLY_MODE_ON: ControllerNumber = ControllerNumber(0x7F);
}
| 59.611111 | 100 | 0.793932 |
ef97b103f9ba0cc60cfaa7bb8f75e03438a30d53 | 9,647 | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_snake_case)]
use std::iter::repeat;
use regex::Regex;
bench_match!(misc, literal, r"y", {
format!("{}y", repeat("x").take(50).collect::<String>())
});
bench_match!(misc, not_literal, r".y", {
format!("{}y", repeat("x").take(50).collect::<String>())
});
bench_match!(misc, match_class, "[abcdw]", {
format!("{}w", repeat("xxxx").take(20).collect::<String>())
});
bench_match!(misc, match_class_in_range, "[ac]", {
format!("{}c", repeat("bbbb").take(20).collect::<String>())
});
bench_not_match!(misc, anchored_literal_short_non_match, r"^zbc(d|e)", {
"abcdefghijklmnopqrstuvwxyz".to_owned()
});
bench_not_match!(misc, anchored_literal_long_non_match, r"^zbc(d|e)", {
repeat("abcdefghijklmnopqrstuvwxyz")
.take(15)
.collect::<String>()
});
bench_match!(misc, anchored_literal_short_match, r"^.bc(d|e)", {
"abcdefghijklmnopqrstuvwxyz".to_owned()
});
bench_match!(misc, anchored_literal_long_match, r"^.bc(d|e)", {
repeat("abcdefghijklmnopqrstuvwxyz")
.take(15)
.collect::<String>()
});
bench_match!(misc, one_pass_short, r"^.bc(d|e)*$", {
"abcddddddeeeededd".to_owned()
});
bench_match!(misc, one_pass_short_not, r".bc(d|e)*$", {
"abcddddddeeeededd".to_owned()
});
bench_match!(
misc,
one_pass_long_prefix,
r"^abcdefghijklmnopqrstuvwxyz.*$",
{ "abcdefghijklmnopqrstuvwxyz".to_owned() }
);
bench_match!(
misc,
one_pass_long_prefix_not,
r"^.bcdefghijklmnopqrstuvwxyz.*$",
{ "abcdefghijklmnopqrstuvwxyz".to_owned() }
);
bench_match!(misc, long_needle1, r"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", {
repeat("a").take(100_000).collect::<String>() + "b"
});
bench_match!(misc, long_needle2, r"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbba", {
repeat("b").take(100_000).collect::<String>() + "a"
});
// This benchmark specifically targets the "reverse suffix literal"
// optimization. In particular, it is easy for a naive implementation to
// take quadratic worst case time. This benchmark provides a case for such
// a scenario.
bench_not_match!(
misc,
reverse_suffix_no_quadratic,
r"[r-z].*bcdefghijklmnopq",
{ repeat("bcdefghijklmnopq").take(500).collect::<String>() }
);
wrap_libtest! {
misc,
fn replace_all(b: &mut Bencher) {
let re = regex!("[cjrw]");
let text = "abcdefghijklmnopqrstuvwxyz";
b.iter(|| re.replace_all(text, ""));
}
}
const TXT_32: &'static str = include_str!("data/32.txt");
const TXT_1K: &'static str = include_str!("data/1K.txt");
const TXT_32K: &'static str = include_str!("data/32K.txt");
const TXT_1MB: &'static str = include_str!("data/1MB.txt");
fn get_text(corpus: &str, suffix: String) -> String {
let mut corpus = corpus.to_string();
corpus.push_str(&suffix);
corpus
}
fn easy0_suffix() -> String {
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".to_string()
}
macro_rules! easy0 {
() => {
"ABCDEFGHIJKLMNOPQRSTUVWXYZ$"
};
}
bench_match!(misc, easy0_32, easy0!(), get_text(TXT_32, easy0_suffix()));
bench_match!(misc, easy0_1K, easy0!(), get_text(TXT_1K, easy0_suffix()));
bench_match!(misc, easy0_32K, easy0!(), get_text(TXT_32K, easy0_suffix()));
bench_match!(misc, easy0_1MB, easy0!(), get_text(TXT_1MB, easy0_suffix()));
fn easy1_suffix() -> String {
"AABCCCDEEEFGGHHHIJJ".to_string()
}
macro_rules! easy1 {
() => {
r"A[AB]B[BC]C[CD]D[DE]E[EF]F[FG]G[GH]H[HI]I[IJ]J$"
};
}
bench_match!(misc, easy1_32, easy1!(), get_text(TXT_32, easy1_suffix()));
bench_match!(misc, easy1_1K, easy1!(), get_text(TXT_1K, easy1_suffix()));
bench_match!(misc, easy1_32K, easy1!(), get_text(TXT_32K, easy1_suffix()));
bench_match!(misc, easy1_1MB, easy1!(), get_text(TXT_1MB, easy1_suffix()));
fn medium_suffix() -> String {
"XABCDEFGHIJKLMNOPQRSTUVWXYZ".to_string()
}
macro_rules! medium {
() => {
r"[XYZ]ABCDEFGHIJKLMNOPQRSTUVWXYZ$"
};
}
bench_match!(
misc,
medium_32,
medium!(),
get_text(TXT_32, medium_suffix())
);
bench_match!(
misc,
medium_1K,
medium!(),
get_text(TXT_1K, medium_suffix())
);
bench_match!(
misc,
medium_32K,
medium!(),
get_text(TXT_32K, medium_suffix())
);
bench_match!(
misc,
medium_1MB,
medium!(),
get_text(TXT_1MB, medium_suffix())
);
fn hard_suffix() -> String {
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".to_string()
}
macro_rules! hard {
() => {
r"[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ$"
};
}
bench_match!(misc, hard_32, hard!(), get_text(TXT_32, hard_suffix()));
bench_match!(misc, hard_1K, hard!(), get_text(TXT_1K, hard_suffix()));
bench_match!(misc, hard_32K, hard!(), get_text(TXT_32K, hard_suffix()));
bench_match!(misc, hard_1MB, hard!(), get_text(TXT_1MB, hard_suffix()));
fn reallyhard_suffix() -> String {
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".to_string()
}
macro_rules! reallyhard {
() => {
// The point of this being "really" hard is that it should completely
// thwart any prefix or suffix literal optimizations.
r"[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ.*"
};
}
bench_match!(
misc,
reallyhard_32,
reallyhard!(),
get_text(TXT_32, reallyhard_suffix())
);
bench_match!(
misc,
reallyhard_1K,
reallyhard!(),
get_text(TXT_1K, reallyhard_suffix())
);
bench_match!(
misc,
reallyhard_32K,
reallyhard!(),
get_text(TXT_32K, reallyhard_suffix())
);
bench_match!(
misc,
reallyhard_1MB,
reallyhard!(),
get_text(TXT_1MB, reallyhard_suffix())
);
fn reallyhard2_suffix() -> String {
"Sherlock Holmes".to_string()
}
macro_rules! reallyhard2 {
() => {
r"\w+\s+Holmes"
};
}
bench_match!(
misc,
reallyhard2_1K,
reallyhard2!(),
get_text(TXT_1K, reallyhard2_suffix())
);
//
// Benchmarks to justify the short-haystack NFA fallthrough optimization
// implemented by `read_captures_at` in regex/src/exec.rs. See github issue
// #348.
//
// The procedure used to try to determine the right hardcoded cutoff
// for the short-haystack optimization in issue #348 is as follows.
//
// ```
// > cd bench
// > cargo bench --features re-rust short_hay | tee dfa-nfa.res
// > # modify the `MatchType::Dfa` branch in exec.rs:read_captures_at
// > # to just execute the nfa
// > cargo bench --features re-rust short_hay | tee nfa-only.res
// > cargo benchcmp dfa-nfa.res nfa-only.res
// ```
//
// The expected result is that short inputs will go faster under
// the nfa-only mode, but at some turnover point the dfa-nfa mode
// will start to win again. Unfortunately, that is not what happened.
// Instead there was no noticeable change in the bench results, so
// I've opted to just do the more conservative anchor optimization.
//
bench_captures!(
misc,
short_haystack_1x,
Regex::new(r"(bbbb)cccc(bbb)").unwrap(),
2,
String::from("aaaabbbbccccbbbdddd")
);
bench_captures!(
misc,
short_haystack_2x,
Regex::new(r"(bbbb)cccc(bbb)").unwrap(),
2,
format!(
"{}bbbbccccbbb{}",
repeat("aaaa").take(2).collect::<String>(),
repeat("dddd").take(2).collect::<String>(),
)
);
bench_captures!(
misc,
short_haystack_3x,
Regex::new(r"(bbbb)cccc(bbb)").unwrap(),
2,
format!(
"{}bbbbccccbbb{}",
repeat("aaaa").take(3).collect::<String>(),
repeat("dddd").take(3).collect::<String>(),
)
);
bench_captures!(
misc,
short_haystack_4x,
Regex::new(r"(bbbb)cccc(bbb)").unwrap(),
2,
format!(
"{}bbbbccccbbb{}",
repeat("aaaa").take(4).collect::<String>(),
repeat("dddd").take(4).collect::<String>(),
)
);
bench_captures!(
misc,
short_haystack_10x,
Regex::new(r"(bbbb)cccc(bbb)").unwrap(),
2,
format!(
"{}bbbbccccbbb{}",
repeat("aaaa").take(10).collect::<String>(),
repeat("dddd").take(10).collect::<String>(),
)
);
bench_captures!(
misc,
short_haystack_100x,
Regex::new(r"(bbbb)cccc(bbb)").unwrap(),
2,
format!(
"{}bbbbccccbbb{}",
repeat("aaaa").take(100).collect::<String>(),
repeat("dddd").take(100).collect::<String>(),
)
);
bench_captures!(
misc,
short_haystack_1000x,
Regex::new(r"(bbbb)cccc(bbb)").unwrap(),
2,
format!(
"{}bbbbccccbbb{}",
repeat("aaaa").take(1000).collect::<String>(),
repeat("dddd").take(1000).collect::<String>(),
)
);
bench_captures!(
misc,
short_haystack_10000x,
Regex::new(r"(bbbb)cccc(bbb)").unwrap(),
2,
format!(
"{}bbbbccccbbb{}",
repeat("aaaa").take(10000).collect::<String>(),
repeat("dddd").take(10000).collect::<String>(),
)
);
bench_captures!(
misc,
short_haystack_100000x,
Regex::new(r"(bbbb)cccc(bbb)").unwrap(),
2,
format!(
"{}bbbbccccbbb{}",
repeat("aaaa").take(100000).collect::<String>(),
repeat("dddd").take(100000).collect::<String>(),
)
);
bench_captures!(
misc,
short_haystack_1000000x,
Regex::new(r"(bbbb)cccc(bbb)").unwrap(),
2,
format!(
"{}bbbbccccbbb{}",
repeat("aaaa").take(1000000).collect::<String>(),
repeat("dddd").take(1000000).collect::<String>(),
)
);
| 25.588859 | 77 | 0.636882 |
031b209a9201cdc54cb5977cce3773426c7f581f | 1,843 | use actix::prelude::*;
use crate::Message;
use super::{PluginContext, OnCommand};
use std::error::Error;
use std::fs::File;
use std::io::{BufRead, BufReader};
use rand::{thread_rng, seq::SliceRandom};
pub struct GenWord {}
impl GenWord {
pub fn new(ctx: PluginContext<Self>) -> Self {
ctx.on_command("genword", ctx.recipient());
Self {}
}
}
impl Actor for GenWord {
type Context = Context<Self>;
}
impl Handler<OnCommand> for GenWord {
type Result = ();
fn handle(&mut self, event: OnCommand, ctx: &mut Context<Self>) {
if event.command != "genword" {
return;
}
let message = event.message;
match gen_word() {
Ok(word) => {
message.reply(&word);
},
Err(e) => {
message.reply("Failed to generate word");
eprintln!("[genword] {}", e);
}
};
}
}
lazy_static! {
static ref WORDS: Result<Vec<String>, Box<Error + Send + Sync>> = {
let file = File::open("/usr/share/dict/american-english")?;
let file = BufReader::new(file);
let mut words = Vec::new();
for word in file.lines() {
let word = word?;
if !word.chars().all(|c| c.is_lowercase() && c.is_alphanumeric()) {
continue
}
if word.len() < 3 || word.len() > 7 {
continue;
}
words.push(word);
}
Ok(words)
};
}
fn gen_word() -> Result<String, String> {
let word = format!("{} {}", random_word()?, random_word()?);
Ok(word)
}
fn random_word() -> Result<&'static str, String> {
let words = WORDS.as_ref().map_err(<_>::to_string)?;
let word = words.choose(&mut thread_rng()).ok_or("No word in word list")?;
Ok(&*word)
}
| 23.935065 | 79 | 0.522518 |
5dc46d8fdb461773a6f658465c980b52208a06de | 1,600 | //! This file defines the extern "C" API, which is compatible with the
//! [Wasm C API](https://github.com/WebAssembly/wasm-c-api).
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals)]
#![allow(unknown_lints)]
#![allow(improper_ctypes_definitions)]
// TODO complete the C API
mod config;
mod engine;
mod error;
mod r#extern;
mod func;
mod global;
mod instance;
mod linker;
mod memory;
mod module;
mod r#ref;
mod store;
mod table;
mod trap;
mod types;
mod val;
mod vec;
pub use crate::config::*;
pub use crate::engine::*;
pub use crate::error::*;
pub use crate::func::*;
pub use crate::global::*;
pub use crate::instance::*;
pub use crate::linker::*;
pub use crate::memory::*;
pub use crate::module::*;
pub use crate::r#extern::*;
pub use crate::r#ref::*;
pub use crate::store::*;
pub use crate::table::*;
pub use crate::trap::*;
pub use crate::types::*;
pub use crate::val::*;
pub use crate::vec::*;
#[cfg(feature = "wasi")]
mod wasi;
#[cfg(feature = "wasi")]
pub use crate::wasi::*;
#[cfg(feature = "wat")]
mod wat2wasm;
#[cfg(feature = "wat")]
pub use crate::wat2wasm::*;
#[repr(C)]
#[derive(Clone)]
pub struct wasm_foreign_t {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Clone)]
pub struct wasm_shared_module_t {
_unused: [u8; 0],
}
/// Initialize a `MaybeUninit<T>`
///
/// TODO: Replace calls to this function with
/// https://doc.rust-lang.org/nightly/std/mem/union.MaybeUninit.html#method.write
/// once it is stable.
pub(crate) fn initialize<T>(dst: &mut std::mem::MaybeUninit<T>, val: T) {
unsafe {
std::ptr::write(dst.as_mut_ptr(), val);
}
}
| 20.512821 | 81 | 0.665625 |
39ec2b46a42a84b9f49dac2baedda4ba7ae1c346 | 1,056 | use advent_of_code::utils::challenges::prelude::*;
pub mod intcode;
use intcode::Intcode;
puzzle_args!(override_memory: bool = true);
fn override_memory(machine: &mut Intcode, noun: i32, verb: i32) {
machine.memory[1] = noun;
machine.memory[2] = verb;
}
fn part_one(input: &PuzzleInput, raw_args: &RawPuzzleArgs) -> Solution {
let args = PuzzleArgs::from(raw_args);
let mut machine = Intcode::from(input);
if args.override_memory {
override_memory(&mut machine, 12, 2);
}
machine.run();
Answer(machine.memory[0] as u64)
}
fn part_two(input: &PuzzleInput, _raw_args: &RawPuzzleArgs) -> Solution {
let target = 19690720;
let mut machine = Intcode::from(input);
for noun in 0..=99 {
for verb in 0..=99 {
machine.reset();
override_memory(&mut machine, noun, verb);
machine.run();
if machine.memory[0] == target {
return Answer((100 * noun + verb) as u64)
}
}
}
Unsolved
}
solve!(part_one, part_two);
| 25.142857 | 73 | 0.609848 |
de53416440ef5f37345ba3de8c253332ab54b579 | 693 | // Instruction opcodes
pub const OPCODE_NOP: u8 = 0x00;
pub const OPCODE_LOADI_B: u8 = 0x01;
pub const OPCODE_LOADI_2B: u8 = 0x02;
pub const OPCODE_LOADI_4B: u8 = 0x03;
pub const OPCODE_LOADI_8B: u8 = 0x04;
pub const OPCODE_LOAD: u8 = 0x10;
pub const OPCODE_LOADS: u8 = 0x11;
pub const OPCODE_STORE: u8 = 0x15;
pub const OPCODE_POP: u8 = 0x20;
pub const OPCODE_FUNC_B: u8 = 0x30;
pub const OPCODE_SYS: u8 = 0x40;
pub const OPCODE_HLT: u8 = 0x50;
// Function opcodes
pub const OPCODE_ADD: u8 = 0x00;
pub const OPCODE_SUB: u8 = 0x01;
pub const OPCODE_MUL: u8 = 0x02;
pub const OPCODE_DIV: u8 = 0x03;
// System call opcodes
pub const OPCODE_PUT_B: u8 = 0x00;
pub const OPCODE_PUT_C: u8 = 0x10;
| 28.875 | 37 | 0.74026 |
9c955a9e92d55e031d7fd60850dda1045efae168 | 10,354 | mod fo_timing;
#[cfg(feature = "rapl")]
mod rapl;
mod rejection_sampling;
use liboqs_rs_bindings as oqs;
use log_derive::logfn_inputs;
use oqs::{
frodokem::{FrodoKem1344aes, FrodoKem640aes},
kyber::{Kyber1024, Kyber1024_90S, Kyber512, Kyber512_90S, Kyber768, Kyber768_90S},
};
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
pub enum FrodoParams {
// Select the 640 AES paramter set
Kem640aes,
// Select the 1344 AES paramter set
Kem1344aes,
}
#[derive(StructOpt, Debug)]
pub enum KyberParams {
// Select the 512 paramter set
Kem512,
// Select the 512 paramter set, 90's version
Kem512_90S,
// Select the 768 paramter set
Kem768,
// Select the 768 paramter set, 90's version
Kem768_90S,
// Select the 1024 paramter set
Kem1024,
// Select the 1024 paramter set, 90's version
Kem1024_90S,
}
// Choose which algorithm to run
#[derive(StructOpt, Debug)]
pub enum KemAlg {
// Select the FrodoKEM algorithm
Frodo(FrodoParams),
// Select the Kyber algorithm
Kyber(KyberParams),
}
#[derive(StructOpt, Debug)]
#[structopt(name = "type")]
pub enum Attacks {
/// Run a basic baseline analysis to find vulnerable implementations of the Fujisaki
/// Okamoto transform employed by many KEMs
FOBaseline {
#[structopt(subcommand, name = "kem-algs")]
params: KemAlg,
/// Number of warmup iterations to run before starting sampling
#[structopt(short, long)]
warmup: u64,
/// Number of samples to run
#[structopt(short, long)]
samples: u64,
/// Save measurments to a csv file
#[structopt(short("f"), long)]
save: Option<PathBuf>,
/// Measurment source, either external, internal or oracle
#[structopt(short, long)]
measure_source: fo_timing::MeasureSource,
},
/// Run the MEMCPY attack against the FrodoKEM implementation. See sources for liboqs to know
/// if your version is patched aginst this vulnerability or not.
MemcmpFrodoCrackS {
#[structopt(subcommand, name = "frodo-alg")]
params: FrodoParams,
/// Number of warmup iterations to run before starting sampling
#[structopt(short, long)]
warmup: u64,
/// Number of iterations to measure when profiling.
#[structopt(short, long)]
profiling: u64,
/// Number of iterations to measure before making a decision.
#[structopt(short, long)]
iterations: u64,
/// Save profiling measurments to a csv file
#[structopt(short("f"), long("save-profiling"))]
save_to_file: Option<PathBuf>,
/// Measurment source, either external, internal or oracle
#[structopt(short, long)]
measure_source: fo_timing::MeasureSource,
},
/// Run a variant of the baseline analysis better geared towards finding
/// small runtime differences due to cache and other non-constant time behaviour.
CacheAttackFOBaseline {
#[structopt(subcommand, name = "kem-alg")]
params: KemAlg,
/// Number of warmup iterations to run before starting sampling
#[structopt(short, long)]
warmup: u64,
/// Number of samples to test, per encapsulation
#[structopt(short, long)]
samples: u64,
/// Number of encapsulations to test, per key
#[structopt(short("e"), long)]
nencaps: u64,
/// Number of keys to test
#[structopt(short("k"), long)]
nkeys: u64,
/// Save measurments to a csv file
#[structopt(short("f"), long)]
save: Option<PathBuf>,
/// Measurment source, either external, internal or oracle
#[structopt(short, long)]
measure_source: fo_timing::MeasureSource,
},
/// Run a muiltipoint profiling of the supported algorithms
FOMultipointProfiling {
#[structopt(subcommand, name = "kem-alg")]
params: KemAlg,
/// Number of warmup iterations to run before starting sampling
#[structopt(short, long)]
warmup: u64,
/// Number of samples to test, per encapsulation
#[structopt(short, long)]
samples: u64,
/// Number of encapsulations to test, per key
#[structopt(short("e"), long)]
nencaps: u64,
/// Number of keys to test
#[structopt(short("k"), long)]
nkeys: u64,
/// Save measurments to a csv file
#[structopt(short("f"), long)]
save: Option<PathBuf>,
},
/// Run an attack on the Rejection Sampling techniques used by BIKE and HQC
RejectionSampling {
/// Select a subroutine to run
#[structopt(subcommand, name = "subroutine")]
sub: rejection_sampling::Subroutine,
},
}
#[derive(StructOpt, Debug)]
pub struct AttackOptions {
#[structopt(subcommand)]
/// Select attack variant
attack: Attacks,
}
#[logfn_inputs(Trace)]
pub fn run(options: AttackOptions) -> Result<(), String> {
match options.attack {
Attacks::FOBaseline {
params,
samples,
warmup,
measure_source,
save,
} => {
let f = match params {
KemAlg::Frodo(FrodoParams::Kem640aes) => {
fo_timing::fujisaki_okamoto_baseline::<FrodoKem640aes>
}
KemAlg::Frodo(FrodoParams::Kem1344aes) => {
fo_timing::fujisaki_okamoto_baseline::<FrodoKem1344aes>
}
KemAlg::Kyber(KyberParams::Kem512) => {
fo_timing::fujisaki_okamoto_baseline::<Kyber512>
}
KemAlg::Kyber(KyberParams::Kem512_90S) => {
fo_timing::fujisaki_okamoto_baseline::<Kyber512_90S>
}
KemAlg::Kyber(KyberParams::Kem768) => {
fo_timing::fujisaki_okamoto_baseline::<Kyber768>
}
KemAlg::Kyber(KyberParams::Kem768_90S) => {
fo_timing::fujisaki_okamoto_baseline::<Kyber768_90S>
}
KemAlg::Kyber(KyberParams::Kem1024) => {
fo_timing::fujisaki_okamoto_baseline::<Kyber1024>
}
KemAlg::Kyber(KyberParams::Kem1024_90S) => {
fo_timing::fujisaki_okamoto_baseline::<Kyber1024_90S>
}
};
f(samples, warmup, measure_source, save)
}
Attacks::MemcmpFrodoCrackS {
params,
warmup,
profiling,
iterations,
measure_source,
save_to_file,
} => {
let f = match params {
FrodoParams::Kem640aes => fo_timing::frodo_crack_s::<FrodoKem640aes>,
FrodoParams::Kem1344aes => fo_timing::frodo_crack_s::<FrodoKem1344aes>,
};
f(warmup, iterations, profiling, measure_source, save_to_file)
}
Attacks::CacheAttackFOBaseline {
params,
warmup,
nencaps,
nkeys,
samples,
save,
measure_source,
} => {
let f = match params {
KemAlg::Frodo(FrodoParams::Kem640aes) => {
fo_timing::fujisaki_okamoto_baseline_cache::<FrodoKem640aes>
}
KemAlg::Frodo(FrodoParams::Kem1344aes) => {
fo_timing::fujisaki_okamoto_baseline_cache::<FrodoKem1344aes>
}
KemAlg::Kyber(KyberParams::Kem512) => {
fo_timing::fujisaki_okamoto_baseline_cache::<Kyber512>
}
KemAlg::Kyber(KyberParams::Kem512_90S) => {
fo_timing::fujisaki_okamoto_baseline_cache::<Kyber512_90S>
}
KemAlg::Kyber(KyberParams::Kem768) => {
fo_timing::fujisaki_okamoto_baseline_cache::<Kyber768>
}
KemAlg::Kyber(KyberParams::Kem768_90S) => {
fo_timing::fujisaki_okamoto_baseline_cache::<Kyber768_90S>
}
KemAlg::Kyber(KyberParams::Kem1024) => {
fo_timing::fujisaki_okamoto_baseline_cache::<Kyber1024>
}
KemAlg::Kyber(KyberParams::Kem1024_90S) => {
fo_timing::fujisaki_okamoto_baseline_cache::<Kyber1024_90S>
}
};
f(samples, nencaps, nkeys, warmup, measure_source, save)
}
Attacks::FOMultipointProfiling {
params,
warmup,
samples,
nencaps,
nkeys,
save,
} => {
let f = match params {
KemAlg::Frodo(FrodoParams::Kem640aes) => {
fo_timing::fujisaki_okamoto_baseline_multipoint_profiling::<FrodoKem640aes>
}
KemAlg::Frodo(FrodoParams::Kem1344aes) => {
fo_timing::fujisaki_okamoto_baseline_multipoint_profiling::<FrodoKem1344aes>
}
KemAlg::Kyber(KyberParams::Kem512) => {
fo_timing::fujisaki_okamoto_baseline_multipoint_profiling::<Kyber512>
}
KemAlg::Kyber(KyberParams::Kem512_90S) => {
fo_timing::fujisaki_okamoto_baseline_multipoint_profiling::<Kyber512_90S>
}
KemAlg::Kyber(KyberParams::Kem768) => {
fo_timing::fujisaki_okamoto_baseline_multipoint_profiling::<Kyber768>
}
KemAlg::Kyber(KyberParams::Kem768_90S) => {
fo_timing::fujisaki_okamoto_baseline_multipoint_profiling::<Kyber768_90S>
}
KemAlg::Kyber(KyberParams::Kem1024) => {
fo_timing::fujisaki_okamoto_baseline_multipoint_profiling::<Kyber1024>
}
KemAlg::Kyber(KyberParams::Kem1024_90S) => {
fo_timing::fujisaki_okamoto_baseline_multipoint_profiling::<Kyber1024_90S>
}
};
f(samples, nencaps, nkeys, warmup, save)
}
Attacks::RejectionSampling { sub } => rejection_sampling::run(sub),
}
}
| 34.398671 | 97 | 0.570601 |
6128a27c184ed9a1238032551927e8832e947c9a | 2,698 | use std::error::Error;
use std::io::Write;
use clap::ArgMatches;
use rust_htslib::bam;
use rust_htslib::bam::{Read, Record};
use itertools::Itertools;
use carina::barcode::cb_string_to_u64;
use crate::fragments::count_stats;
use crate::fragments::filter;
use crate::fragments::schema::Fragment;
pub fn callback(sub_m: &ArgMatches) -> Result<(), Box<dyn Error>> {
let bam_file_path = carina::file::file_path_from_clap(sub_m, "ibam")?;
let mut obed_file = carina::file::bufwriter_from_clap(sub_m, "obed")?;
let mut input_bam = bam::Reader::from_path(bam_file_path).expect("Can't open BAM file");
let bam_header = input_bam.header().clone();
input_bam.set_threads(4).unwrap();
let (is_tenx, cb_extractor): (bool, fn(&Record) -> u64) = match sub_m.occurrences_of("tenx") {
0 => (false, |aln: &Record| -> u64 {
let qname = aln.qname();
cb_string_to_u64(&qname[(qname.len() - crate::configs::CB_LENGTH)..])
.expect("can't convert cb string to u64")
}),
_ => (true, |aln: &Record| -> u64 {
cb_string_to_u64(&aln.aux(b"CB").unwrap().string()[..crate::configs::CB_LENGTH])
.expect("can't convert cb string to u64")
}),
};
let just_stats = match sub_m.occurrences_of("stats") {
0 => false,
_ => true,
};
let mito_string = sub_m
.value_of("mitostr")
.expect("can't find string to identify mitochondrial chromosome");
let mito_tid = bam_header
.tid(mito_string.as_bytes())
.expect("Can't find mito string in the BAM file");
info!(
"Using {} as Mitochondrial Chromosome with {} as id.",
mito_string, mito_tid
);
let mut counter = count_stats::FragStats {
..Default::default()
};
for (_, read_group) in input_bam
.records()
.map(|res| res.unwrap())
.group_by(|rec| rec.qname().to_owned())
.into_iter()
{
counter.total_reads += 1;
if counter.total_reads % crate::configs::MIL == 0 {
print!(
"\rDone processing {}M reads",
counter.total_reads / crate::configs::MIL
);
std::io::stdout().flush().expect("Can't flush output");
}
let alignments: Vec<Record> = read_group.collect();
match filter::callback(&alignments, &mut counter, just_stats, is_tenx, mito_tid) {
Some((aln, maln)) => {
let frag = Fragment::new(aln, maln, cb_extractor);
frag.write(&mut obed_file, "binary")?;
}
None => continue,
};
}
println!("{}", counter);
Ok(())
}
| 32.119048 | 98 | 0.576353 |
ebdd01d942bafa3e78bc6b707c77f5604a5185e4 | 317 | use quickcheck::Arbitrary;
use crate::prelude::*;
/// Generates a value using the [`Arbitrary`] implementation of the type `T`.
///
/// Only available if the feature `quickcheck_full` is enabled.
pub fn arbitrary<T>() -> impl Die<T>
where
T: Arbitrary,
{
dice::from_fn(|mut fate| T::arbitrary(&mut fate))
}
| 22.642857 | 77 | 0.678233 |
56de1eb73e6de96b63a0779791f14404c120e609 | 402 | // Copyright 2019 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.
/// Prefix for all Font Package URLs.
pub const PKG_URL_PREFIX: &str = "fuchsia-pkg://fuchsia.com/font-package-";
/// All local font files will be stored in this directory.
pub const LOCAL_ASSET_DIRECTORY: &str = "/config/data/assets";
| 40.2 | 75 | 0.743781 |
1637f7a59d90d5cc575b0eb5f670ad09a8aac1f4 | 182 | use std::ops::Range;
/// range.contains(), but that is unstable
pub fn in_range<T: Ord + Copy>(value: T, range: &Range<T>) -> bool {
value >= range.start && value < range.end
}
| 26 | 68 | 0.626374 |
fb9e0b1a3db5379994b9b88b7dd774f23cd0f6f7 | 3,723 | use common::*;
use gfx_h::Canvas;
use red::GL;
use std::collections::{HashMap, VecDeque};
use std::time::{Duration, Instant};
#[derive(Debug, Clone)]
pub struct Plot<T: Copy> {
plot_data: PlotData,
duration: Duration,
queue: VecDeque<(Instant, T)>,
}
#[derive(Debug, Clone)]
pub struct PlotData {
pub color: Point3,
}
impl PlotData {
pub fn new(color: Point3) -> Self {
Self { color: color }
}
}
impl<T> Plot<T>
where
T: Copy,
{
pub fn new(plot_data: PlotData, duration: Duration) -> Self {
Plot {
plot_data: plot_data,
duration: duration,
queue: VecDeque::new(),
}
}
pub fn update(&mut self) {
loop {
if let Some(value) = self.queue.front() {
if Instant::now() - value.0 > self.duration {
self.queue.pop_front();
} else {
break;
}
} else {
break;
}
}
}
pub fn insert(&mut self, value: T) {
self.queue.push_back((Instant::now(), value));
}
pub fn iter(&self) -> impl Iterator<Item = (f32, T)> + '_ {
self.queue.iter().map(move |x| {
(
((Instant::now() - x.0).as_millis() as f32)
/ (self.duration.as_millis() as f32),
x.1,
)
})
}
}
pub struct TeleGraph {
duration: Duration,
plot: HashMap<String, Plot<f32>>,
}
impl TeleGraph {
pub fn new(duration: Duration) -> Self {
Self {
duration: duration,
plot: HashMap::new(),
}
}
pub fn set_color(&mut self, name: String, color: Point3) {
let plot_data = PlotData::new(color);
let this_plot = self
.plot
.entry(name)
.or_insert(Plot::new(plot_data, self.duration));
this_plot.plot_data.color = color;
}
pub fn update(&mut self) {
for p in self.plot.iter_mut() {
p.1.update()
}
}
pub fn insert(&mut self, name: String, value: f32) {
let plot_data = PlotData::new(Point3::new(1f32, 1f32, 1f32));
let this_plot = self
.plot
.entry(name)
.or_insert(Plot::new(plot_data, self.duration));
this_plot.insert(value);
}
pub fn iter(
&self,
name: String,
) -> Option<(PlotData, impl Iterator<Item = (f32, f32)> + '_)> {
if let Some(plot) = self.plot.get(&name) {
Some((plot.plot_data.clone(), plot.iter()))
} else {
None
}
}
pub fn iter_names(&self) -> impl Iterator<Item = &String> + '_ {
self.plot.keys()
}
}
pub fn render_plot<T>(
plot_data: PlotData,
iter_plot: T,
w: f32,
h: f32,
context: &GL,
viewport: &red::Viewport,
canvas: &Canvas,
frame: &mut red::Frame,
) where
T: Iterator<Item = (f32, f32)>,
{
let render_lines = move |lines: &[(Point2, Point2)],
frame: &mut red::Frame| {
canvas.draw_lines(
&lines,
&context,
frame,
&viewport,
plot_data.color,
0.1f32,
);
};
let mut prev = None;
let mut lines_to_draw = vec![];
for (x_fract, value) in iter_plot {
let x = w - w * x_fract - w / 2.0;
let y = h - h * value - h / 2.0;
let current = Point2::new(x, y);
if let Some(prev) = prev {
lines_to_draw.push((prev, current));
// render_line(prev, current, frame);
}
prev = Some(current);
}
render_lines(&lines_to_draw, frame);
}
| 24.019355 | 69 | 0.493688 |
e2f56053f0283cb5f30a83df9da5e6f4c184a9e7 | 33,683 | use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::Arc,
};
use druid::{
kurbo::Line,
piet::{Svg, Text, TextLayout, TextLayoutBuilder},
BoxConstraints, Command, Env, Event, EventCtx, FontFamily, LayoutCtx, LifeCycle,
LifeCycleCtx, MouseEvent, PaintCtx, Point, Rect, RenderContext, Size, Target,
UpdateCtx, Widget, WidgetExt, WidgetId, WidgetPod,
};
use lapce_data::{
command::{LapceUICommand, LAPCE_UI_COMMAND},
config::{Config, LapceTheme},
data::LapceTabData,
};
use lapce_rpc::file::FileNodeItem;
use crate::{
editor::view::LapceEditorView,
explorer::{get_item_children, get_item_children_mut},
scroll::LapceScrollNew,
svg::{file_svg_new, get_svg},
tab::LapceButton,
};
#[derive(Clone)]
pub struct FilePickerData {
pub widget_id: WidgetId,
pub editor_view_id: WidgetId,
pub active: bool,
root: FileNodeItem,
pub home: PathBuf,
pub pwd: PathBuf,
}
impl FilePickerData {
pub fn new() -> Self {
let root = FileNodeItem {
path_buf: PathBuf::from("/"),
is_dir: true,
read: false,
open: false,
children: HashMap::new(),
children_open_count: 0,
};
let home = PathBuf::from("/");
let pwd = PathBuf::from("/");
Self {
widget_id: WidgetId::next(),
editor_view_id: WidgetId::next(),
active: false,
root,
home,
pwd,
}
}
pub fn set_item_children(
&mut self,
path: &Path,
children: HashMap<PathBuf, FileNodeItem>,
) {
if let Some(node) = self.get_file_node_mut(path) {
node.open = true;
node.read = true;
node.children = children;
}
for p in path.ancestors() {
self.update_node_count(&PathBuf::from(p));
}
}
pub fn init_home(&mut self, home: &Path) {
self.home = home.to_path_buf();
let mut current_file_node = FileNodeItem {
path_buf: home.to_path_buf(),
is_dir: true,
read: false,
open: false,
children: HashMap::new(),
children_open_count: 0,
};
let mut current_path = home.to_path_buf();
let mut ancestors = home.ancestors();
ancestors.next();
for p in ancestors {
let mut file_node = FileNodeItem {
path_buf: PathBuf::from(p),
is_dir: true,
read: false,
open: true,
children: HashMap::new(),
children_open_count: 0,
};
file_node
.children
.insert(current_path.clone(), current_file_node.clone());
current_file_node = file_node;
current_path = PathBuf::from(p);
}
self.root = current_file_node;
self.pwd = home.to_path_buf();
}
pub fn get_file_node_mut(&mut self, path: &Path) -> Option<&mut FileNodeItem> {
let mut node = Some(&mut self.root);
let ancestors = path.ancestors().collect::<Vec<&Path>>();
for p in ancestors[..ancestors.len() - 1].iter().rev() {
node = Some(node?.children.get_mut(&PathBuf::from(p))?);
}
node
}
pub fn get_file_node(&self, path: &Path) -> Option<&FileNodeItem> {
let mut node = Some(&self.root);
let ancestors = path.ancestors().collect::<Vec<&Path>>();
for p in ancestors[..ancestors.len() - 1].iter().rev() {
node = Some(node?.children.get(&PathBuf::from(p))?);
}
node
}
pub fn update_node_count(&mut self, path: &Path) -> Option<()> {
let node = self.get_file_node_mut(path)?;
if node.is_dir {
if node.open {
node.children_open_count = node
.children
.iter()
.map(|(_, item)| item.children_open_count + 1)
.sum::<usize>();
} else {
node.children_open_count = 0;
}
}
None
}
}
impl Default for FilePickerData {
fn default() -> Self {
Self::new()
}
}
pub struct FilePicker {
widget_id: WidgetId,
pwd: WidgetPod<LapceTabData, Box<dyn Widget<LapceTabData>>>,
explorer: WidgetPod<LapceTabData, Box<dyn Widget<LapceTabData>>>,
control: WidgetPod<LapceTabData, Box<dyn Widget<LapceTabData>>>,
}
impl FilePicker {
pub fn new(data: &LapceTabData) -> Self {
let pwd = FilePickerPwd::new(data);
let explorer = LapceScrollNew::new(FilePickerExplorer::new());
let control = FilePickerControl::new();
Self {
widget_id: data.picker.widget_id,
pwd: WidgetPod::new(pwd.boxed()),
explorer: WidgetPod::new(explorer.boxed()),
control: WidgetPod::new(control.boxed()),
}
}
}
impl Widget<LapceTabData> for FilePicker {
fn id(&self) -> Option<WidgetId> {
Some(self.widget_id)
}
fn event(
&mut self,
ctx: &mut EventCtx,
event: &Event,
data: &mut LapceTabData,
env: &Env,
) {
if data.picker.active {
self.pwd.event(ctx, event, data, env);
self.explorer.event(ctx, event, data, env);
self.control.event(ctx, event, data, env);
}
}
fn lifecycle(
&mut self,
ctx: &mut LifeCycleCtx,
event: &LifeCycle,
data: &LapceTabData,
env: &Env,
) {
self.pwd.lifecycle(ctx, event, data, env);
self.explorer.lifecycle(ctx, event, data, env);
self.control.lifecycle(ctx, event, data, env);
}
fn update(
&mut self,
ctx: &mut UpdateCtx,
_old_data: &LapceTabData,
data: &LapceTabData,
env: &Env,
) {
self.pwd.update(ctx, data, env);
self.explorer.update(ctx, data, env);
self.control.update(ctx, data, env);
}
fn layout(
&mut self,
ctx: &mut LayoutCtx,
_bc: &BoxConstraints,
data: &LapceTabData,
env: &Env,
) -> Size {
let self_size = Size::new(500.0, 400.0);
let pwd_size =
self.pwd
.layout(ctx, &BoxConstraints::tight(self_size), data, env);
self.pwd.set_origin(ctx, data, env, Point::ZERO);
let control_size =
self.control
.layout(ctx, &BoxConstraints::tight(self_size), data, env);
self.control.set_origin(
ctx,
data,
env,
Point::new(0.0, self_size.height - control_size.height),
);
self.explorer.layout(
ctx,
&BoxConstraints::tight(Size::new(
self_size.width,
self_size.height - pwd_size.height - control_size.height,
)),
data,
env,
);
self.explorer
.set_origin(ctx, data, env, Point::new(0.0, pwd_size.height));
self_size
}
fn paint(&mut self, ctx: &mut PaintCtx, data: &LapceTabData, env: &Env) {
if !data.picker.active {
return;
}
let rect = ctx.size().to_rect();
let shadow_width = 5.0;
ctx.blurred_rect(
rect,
shadow_width,
data.config
.get_color_unchecked(LapceTheme::LAPCE_DROPDOWN_SHADOW),
);
ctx.fill(
rect,
data.config
.get_color_unchecked(LapceTheme::PANEL_BACKGROUND),
);
self.pwd.paint(ctx, data, env);
self.explorer.paint(ctx, data, env);
self.control.paint(ctx, data, env);
}
}
pub struct FilePickerPwd {
icons: Vec<(Rect, Svg)>,
input: WidgetPod<LapceTabData, Box<dyn Widget<LapceTabData>>>,
}
impl FilePickerPwd {
pub fn new(data: &LapceTabData) -> Self {
let input = LapceEditorView::new(data.picker.editor_view_id, None)
.hide_header()
.hide_gutter();
Self {
icons: Vec::new(),
input: WidgetPod::new(input.boxed()),
}
}
fn icon_hit_test(&self, mouse_event: &MouseEvent) -> bool {
for (rect, _) in self.icons.iter() {
if rect.contains(mouse_event.pos) {
return true;
}
}
false
}
fn mouse_down(
&self,
_ctx: &mut EventCtx,
data: &mut LapceTabData,
mouse_event: &MouseEvent,
) {
for (i, (rect, _)) in self.icons.iter().enumerate() {
if rect.contains(mouse_event.pos) && i == 0 {
if let Some(parent) = data.picker.pwd.parent() {
let path = PathBuf::from(parent);
data.set_picker_pwd(path);
}
}
}
}
}
impl Widget<LapceTabData> for FilePickerPwd {
fn event(
&mut self,
ctx: &mut EventCtx,
event: &Event,
data: &mut LapceTabData,
env: &Env,
) {
self.input.event(ctx, event, data, env);
match event {
Event::MouseMove(mouse_event) => {
ctx.set_handled();
if self.icon_hit_test(mouse_event) {
ctx.set_cursor(&druid::Cursor::Pointer);
ctx.request_paint();
} else {
ctx.clear_cursor();
ctx.request_paint();
}
}
Event::MouseDown(mouse_event) => {
ctx.set_handled();
self.mouse_down(ctx, data, mouse_event);
}
_ => (),
}
}
fn lifecycle(
&mut self,
ctx: &mut LifeCycleCtx,
event: &LifeCycle,
data: &LapceTabData,
env: &Env,
) {
self.input.lifecycle(ctx, event, data, env);
}
fn update(
&mut self,
ctx: &mut UpdateCtx,
_old_data: &LapceTabData,
data: &LapceTabData,
env: &Env,
) {
self.input.update(ctx, data, env);
}
fn layout(
&mut self,
ctx: &mut LayoutCtx,
bc: &BoxConstraints,
data: &LapceTabData,
env: &Env,
) -> Size {
let line_height = data.config.editor.line_height as f64;
let input_bc = BoxConstraints::tight(Size::new(
bc.max().width - 20.0 - line_height - 30.0,
bc.max().height,
));
let input_size = self.input.layout(ctx, &input_bc, data, env);
self.input
.set_origin(ctx, data, env, Point::new(20.0, 15.0));
let self_size = Size::new(bc.max().width, input_size.height + 30.0);
let icon_size = line_height;
let gap = (self_size.height - icon_size) / 2.0;
self.icons.clear();
let x =
self_size.width - ((self.icons.len() + 1) as f64) * (gap + icon_size);
let rect = Size::new(icon_size, icon_size)
.to_rect()
.with_origin(Point::new(x, gap));
let svg = get_svg("arrow-up.svg").unwrap();
self.icons.push((rect, svg));
self_size
}
fn paint(&mut self, ctx: &mut PaintCtx, data: &LapceTabData, env: &Env) {
let size = ctx.size();
for (rect, svg) in self.icons.iter() {
ctx.stroke(
rect,
data.config.get_color_unchecked(LapceTheme::LAPCE_BORDER),
1.0,
);
ctx.draw_svg(
svg,
rect.inflate(-5.0, -5.0),
Some(
data.config
.get_color_unchecked(LapceTheme::EDITOR_FOREGROUND),
),
);
}
self.input.paint(ctx, data, env);
ctx.stroke(
Line::new(
Point::new(0.0, size.height - 0.5),
Point::new(size.width, size.height - 0.5),
),
data.config.get_color_unchecked(LapceTheme::LAPCE_BORDER),
1.0,
);
}
}
pub struct FilePickerExplorer {
toggle_rects: HashMap<usize, Rect>,
last_left_click: Option<(usize, std::time::Instant)>,
line_height: f64,
}
impl FilePickerExplorer {
pub fn new() -> Self {
Self {
toggle_rects: HashMap::new(),
last_left_click: None,
line_height: 25.0,
}
}
fn mouse_down(
&mut self,
ctx: &mut EventCtx,
data: &mut LapceTabData,
mouse_event: &MouseEvent,
) {
ctx.set_handled();
let picker = Arc::make_mut(&mut data.picker);
let pwd = picker.pwd.clone();
let index =
((mouse_event.pos.y + self.line_height) / self.line_height) as usize;
if let Some(item) = picker.get_file_node_mut(&pwd) {
let (_, node) = get_item_children_mut(0, index, item);
if let Some(node) = node {
if node.is_dir {
let mut clicked_toogle = false;
if let Some(rect) = self.toggle_rects.get(&index) {
if rect.contains(mouse_event.pos) {
clicked_toogle = true;
if node.read {
node.open = !node.open;
} else {
let tab_id = data.id;
let path = node.path_buf.clone();
let event_sink = ctx.get_external_handle();
data.proxy.read_dir(
&node.path_buf,
Box::new(move |result| {
if let Ok(res) = result {
let resp: Result<
Vec<FileNodeItem>,
serde_json::Error,
> = serde_json::from_value(res);
if let Ok(items) = resp {
let _ = event_sink.submit_command(
LAPCE_UI_COMMAND,
LapceUICommand::UpdatePickerItems(
path,
items
.iter()
.map(|item| {
(
item.path_buf
.clone(),
item.clone(),
)
})
.collect(),
),
Target::Widget(tab_id),
);
}
}
}),
);
}
}
}
let mut last_left_click =
Some((index, std::time::Instant::now()));
if !clicked_toogle {
if let Some((i, t)) = self.last_left_click.as_ref() {
if *i == index && t.elapsed().as_millis() < 500 {
// double click
self.last_left_click = None;
let tab_id = data.id;
let path = node.path_buf.clone();
let event_sink = ctx.get_external_handle();
data.proxy.read_dir(
&node.path_buf,
Box::new(move |result| {
if let Ok(res) = result {
let resp: Result<
Vec<FileNodeItem>,
serde_json::Error,
> = serde_json::from_value(res);
if let Ok(items) = resp {
let _ = event_sink.submit_command(
LAPCE_UI_COMMAND,
LapceUICommand::UpdatePickerItems(
path,
items
.iter()
.map(|item| {
(
item.path_buf
.clone(),
item.clone(),
)
})
.collect(),
),
Target::Widget(tab_id),
);
}
}
}),
);
let pwd = node.path_buf.clone();
picker.index = 0;
data.set_picker_pwd(pwd);
return;
}
}
} else {
last_left_click = None;
}
self.last_left_click = last_left_click;
} else {
if let Some((i, t)) = self.last_left_click.as_ref() {
if *i == index && t.elapsed().as_millis() < 500 {
self.last_left_click = None;
ctx.submit_command(Command::new(
LAPCE_UI_COMMAND,
LapceUICommand::OpenFile(node.path_buf.clone()),
Target::Widget(data.id),
));
picker.active = false;
return;
}
}
self.last_left_click = Some((index, std::time::Instant::now()));
}
let path = node.path_buf.clone();
for p in path.ancestors() {
picker.update_node_count(&PathBuf::from(p));
}
picker.index = index;
}
}
}
}
impl Default for FilePickerExplorer {
fn default() -> Self {
Self::new()
}
}
impl Widget<LapceTabData> for FilePickerExplorer {
fn event(
&mut self,
ctx: &mut EventCtx,
event: &Event,
data: &mut LapceTabData,
_env: &Env,
) {
match event {
Event::MouseDown(mouse_event) => {
self.mouse_down(ctx, data, mouse_event);
}
Event::MouseMove(mouse_event) => {
ctx.set_handled();
let picker = Arc::make_mut(&mut data.picker);
let pwd = picker.pwd.clone();
let index = ((mouse_event.pos.y + self.line_height)
/ self.line_height) as usize;
ctx.request_paint();
if let Some(item) = picker.get_file_node_mut(&pwd) {
let (_, node) = get_item_children(0, index, item);
if let Some(_node) = node {
ctx.set_cursor(&druid::Cursor::Pointer);
} else {
ctx.clear_cursor();
}
} else {
ctx.clear_cursor();
}
}
_ => (),
}
}
fn lifecycle(
&mut self,
_ctx: &mut LifeCycleCtx,
_event: &LifeCycle,
_data: &LapceTabData,
_env: &Env,
) {
}
fn update(
&mut self,
ctx: &mut UpdateCtx,
old_data: &LapceTabData,
data: &LapceTabData,
_env: &Env,
) {
if data.picker.root.children_open_count
!= old_data.picker.root.children_open_count
{
ctx.request_layout();
}
if data.picker.pwd != old_data.picker.pwd {
ctx.request_layout();
}
}
fn layout(
&mut self,
_ctx: &mut LayoutCtx,
bc: &BoxConstraints,
data: &LapceTabData,
_env: &Env,
) -> Size {
let height = if let Some(item) = data.picker.get_file_node(&data.picker.pwd)
{
item.children_open_count as f64 * self.line_height
} else {
bc.max().height
};
Size::new(bc.max().width, height)
}
fn paint(&mut self, ctx: &mut PaintCtx, data: &LapceTabData, _env: &Env) {
let size = ctx.size();
let rect = ctx.region().bounding_box();
let width = size.width;
let index = data.picker.index;
let min = (rect.y0 / self.line_height).floor() as usize;
let max = (rect.y1 / self.line_height) as usize + 2;
let level = 0;
self.toggle_rects.clear();
if let Some(item) = data.picker.get_file_node(&data.picker.pwd) {
let mut i = 0;
for item in item.sorted_children() {
i = paint_file_node_item_by_index(
ctx,
item,
min,
max,
self.line_height,
width,
level + 1,
i + 1,
index,
None,
&data.config,
&mut self.toggle_rects,
);
if i > max {
return;
}
}
}
}
}
#[allow(clippy::too_many_arguments)]
pub fn paint_file_node_item_by_index(
ctx: &mut PaintCtx,
item: &FileNodeItem,
min: usize,
max: usize,
line_height: f64,
width: f64,
level: usize,
current: usize,
active: usize,
hovered: Option<usize>,
config: &Config,
toggle_rects: &mut HashMap<usize, Rect>,
) -> usize {
if current > max {
return current;
}
if current + item.children_open_count < min {
return current + item.children_open_count;
}
if current >= min {
let background = if current == active {
Some(LapceTheme::PANEL_CURRENT)
} else if Some(current) == hovered {
Some(LapceTheme::PANEL_HOVERED)
} else {
None
};
if let Some(background) = background {
ctx.fill(
Rect::ZERO
.with_origin(Point::new(
0.0,
current as f64 * line_height - line_height,
))
.with_size(Size::new(width, line_height)),
config.get_color_unchecked(background),
);
}
let y = current as f64 * line_height - line_height;
let svg_y = y + 4.0;
let svg_size = 15.0;
let padding = 15.0 * level as f64;
if item.is_dir {
let icon_name = if item.open {
"chevron-down.svg"
} else {
"chevron-right.svg"
};
let svg = get_svg(icon_name).unwrap();
let rect = Size::new(svg_size, svg_size)
.to_rect()
.with_origin(Point::new(1.0 + padding, svg_y));
ctx.draw_svg(
&svg,
rect,
Some(config.get_color_unchecked(LapceTheme::EDITOR_FOREGROUND)),
);
toggle_rects.insert(current, rect);
let icon_name = if item.open {
"default_folder_opened.svg"
} else {
"default_folder.svg"
};
let svg = get_svg(icon_name).unwrap();
let rect = Size::new(svg_size, svg_size)
.to_rect()
.with_origin(Point::new(1.0 + 16.0 + padding, svg_y));
ctx.draw_svg(&svg, rect, None);
} else {
let svg = file_svg_new(&item.path_buf);
let rect = Size::new(svg_size, svg_size)
.to_rect()
.with_origin(Point::new(1.0 + 16.0 + padding, svg_y));
ctx.draw_svg(&svg, rect, None);
}
let text_layout = ctx
.text()
.new_text_layout(
item.path_buf
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_string(),
)
.font(FontFamily::SYSTEM_UI, 13.0)
.text_color(
config
.get_color_unchecked(LapceTheme::EDITOR_FOREGROUND)
.clone(),
)
.build()
.unwrap();
ctx.draw_text(
&text_layout,
Point::new(
38.0 + padding,
y + (line_height - text_layout.size().height) / 2.0,
),
);
}
let mut i = current;
if item.open {
for item in item.sorted_children() {
i = paint_file_node_item_by_index(
ctx,
item,
min,
max,
line_height,
width,
level + 1,
i + 1,
active,
hovered,
config,
toggle_rects,
);
if i > max {
return i;
}
}
}
i
}
pub struct FilePickerControl {
buttons: Vec<LapceButton>,
}
impl FilePickerControl {
pub fn new() -> Self {
Self {
buttons: Vec::new(),
}
}
fn icon_hit_test(&self, mouse_event: &MouseEvent) -> bool {
for btn in self.buttons.iter() {
if btn.rect.contains(mouse_event.pos) {
return true;
}
}
false
}
fn mouse_down(
&self,
ctx: &mut EventCtx,
data: &mut LapceTabData,
mouse_event: &MouseEvent,
) {
for btn in self.buttons.iter() {
if btn.rect.contains(mouse_event.pos) && btn.command.is(LAPCE_UI_COMMAND)
{
let command = btn.command.get_unchecked(LAPCE_UI_COMMAND);
match command {
LapceUICommand::SetWorkspace(workspace) => {
if let Some(item) =
data.picker.get_file_node(&data.picker.pwd)
{
let (_, node) =
get_item_children(0, data.picker.index, item);
if let Some(node) = node {
if node.is_dir {
let mut workspace = workspace.clone();
workspace.path = Some(node.path_buf.clone());
ctx.submit_command(Command::new(
LAPCE_UI_COMMAND,
LapceUICommand::SetWorkspace(workspace),
Target::Auto,
));
} else {
ctx.submit_command(Command::new(
LAPCE_UI_COMMAND,
LapceUICommand::OpenFile(
node.path_buf.clone(),
),
Target::Widget(data.id),
));
let picker = Arc::make_mut(&mut data.picker);
picker.active = false;
}
}
}
}
_ => {
ctx.submit_command(btn.command.clone());
}
}
}
}
}
}
impl Default for FilePickerControl {
fn default() -> Self {
Self::new()
}
}
impl Widget<LapceTabData> for FilePickerControl {
fn event(
&mut self,
ctx: &mut EventCtx,
event: &Event,
data: &mut LapceTabData,
_env: &Env,
) {
match event {
Event::MouseMove(mouse_event) => {
ctx.set_handled();
if self.icon_hit_test(mouse_event) {
ctx.set_cursor(&druid::Cursor::Pointer);
ctx.request_paint();
} else {
ctx.clear_cursor();
ctx.request_paint();
}
}
Event::MouseDown(mouse_event) => {
ctx.set_handled();
self.mouse_down(ctx, data, mouse_event);
}
_ => (),
}
}
fn lifecycle(
&mut self,
_ctx: &mut LifeCycleCtx,
_event: &LifeCycle,
_data: &LapceTabData,
_env: &Env,
) {
}
fn update(
&mut self,
_ctx: &mut UpdateCtx,
_old_data: &LapceTabData,
_data: &LapceTabData,
_env: &Env,
) {
}
fn layout(
&mut self,
ctx: &mut LayoutCtx,
bc: &BoxConstraints,
data: &LapceTabData,
_env: &Env,
) -> Size {
let self_size = Size::new(bc.max().width, 50.0);
let button_height = 25.0;
let gap = (self_size.height - button_height) / 2.0;
self.buttons.clear();
let mut x = self_size.width - gap;
let text_layout = ctx
.text()
.new_text_layout("Open")
.font(FontFamily::SYSTEM_UI, 13.0)
.text_color(
data.config
.get_color_unchecked(LapceTheme::EDITOR_FOREGROUND)
.clone(),
)
.build()
.unwrap();
let text_size = text_layout.size();
let btn_width = text_size.width + gap * 2.0;
let btn = LapceButton {
rect: Size::new(text_size.width + gap * 2.0, button_height)
.to_rect()
.with_origin(Point::new(x - btn_width, gap)),
command: Command::new(
LAPCE_UI_COMMAND,
LapceUICommand::SetWorkspace((*data.workspace).clone()),
Target::Auto,
),
text_layout,
};
self.buttons.push(btn);
x -= btn_width + gap;
let text_layout = ctx
.text()
.new_text_layout("Cancel")
.font(FontFamily::SYSTEM_UI, 13.0)
.text_color(
data.config
.get_color_unchecked(LapceTheme::EDITOR_FOREGROUND)
.clone(),
)
.build()
.unwrap();
let text_size = text_layout.size();
let btn_width = text_size.width + gap * 2.0;
let btn = LapceButton {
rect: Size::new(text_size.width + gap * 2.0, button_height)
.to_rect()
.with_origin(Point::new(x - btn_width, gap)),
command: Command::new(
LAPCE_UI_COMMAND,
LapceUICommand::CancelFilePicker,
Target::Widget(data.id),
),
text_layout,
};
self.buttons.push(btn);
self_size
}
fn paint(&mut self, ctx: &mut PaintCtx, data: &LapceTabData, _env: &Env) {
let size = ctx.size();
ctx.stroke(
Line::new(Point::new(0.0, 0.5), Point::new(size.width, 0.5)),
data.config.get_color_unchecked(LapceTheme::LAPCE_BORDER),
1.0,
);
for btn in self.buttons.iter() {
ctx.stroke(
&btn.rect,
data.config.get_color_unchecked(LapceTheme::LAPCE_BORDER),
1.0,
);
let text_size = btn.text_layout.size();
let btn_size = btn.rect.size();
let x = btn.rect.x0 + (btn_size.width - text_size.width) / 2.0;
let y = btn.rect.y0 + (btn_size.height - text_size.height) / 2.0;
ctx.draw_text(&btn.text_layout, Point::new(x, y));
}
}
}
| 32.048525 | 86 | 0.428673 |
69f92723df9fc8a2f25abbea7803866ed94e6a55 | 4,997 | use std::io;
use std::future::Future;
use std::{pin::Pin, task::{Context, Poll}};
use tokio::io::{AsyncRead, ReadBuf};
use crate::http::CookieJar;
use crate::{Request, Response};
/// An `async` response from a dispatched [`LocalRequest`](super::LocalRequest).
///
/// This `LocalResponse` implements [`tokio::io::AsyncRead`]. As such, if
/// [`into_string()`](LocalResponse::into_string()) and
/// [`into_bytes()`](LocalResponse::into_bytes()) do not suffice, the response's
/// body can be read directly:
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// use std::io;
///
/// use rocket::local::asynchronous::Client;
/// use rocket::tokio::io::AsyncReadExt;
/// use rocket::http::Status;
///
/// #[get("/")]
/// fn hello_world() -> &'static str {
/// "Hello, world!"
/// }
///
/// # /*
/// #[launch]
/// # */
/// fn rocket() -> rocket::Rocket {
/// rocket::ignite().mount("/", routes![hello_world])
/// }
///
/// # async fn read_body_manually() -> io::Result<()> {
/// // Dispatch a `GET /` request.
/// let client = Client::tracked(rocket()).await.expect("valid rocket");
/// let mut response = client.get("/").dispatch().await;
///
/// // Check metadata validity.
/// assert_eq!(response.status(), Status::Ok);
/// assert_eq!(response.body().unwrap().known_size(), Some(13));
///
/// // Read 10 bytes of the body. Note: in reality, we'd use `into_string()`.
/// let mut buffer = [0; 10];
/// response.read(&mut buffer).await?;
/// assert_eq!(buffer, "Hello, wor".as_bytes());
/// # Ok(())
/// # }
/// # rocket::async_test(read_body_manually()).expect("read okay");
/// ```
///
/// For more, see [the top-level documentation](../index.html#localresponse).
pub struct LocalResponse<'c> {
_request: Box<Request<'c>>,
response: Response<'c>,
cookies: CookieJar<'c>,
}
impl<'c> LocalResponse<'c> {
pub(crate) fn new<F, O>(req: Request<'c>, f: F) -> impl Future<Output = LocalResponse<'c>>
where F: FnOnce(&'c Request<'c>) -> O + Send,
O: Future<Output = Response<'c>> + Send
{
// `LocalResponse` is a self-referential structure. In particular,
// `inner` can refer to `_request` and its contents. As such, we must
// 1) Ensure `Request` has a stable address.
//
// This is done by `Box`ing the `Request`, using only the stable
// address thereafter.
//
// 2) Ensure no refs to `Request` or its contents leak with a lifetime
// extending beyond that of `&self`.
//
// We have no methods that return an `&Request`. However, we must
// also ensure that `Response` doesn't leak any such references. To
// do so, we don't expose the `Response` directly in any way;
// otherwise, methods like `.headers()` could, in conjunction with
// particular crafted `Responder`s, potentially be used to obtain a
// reference to contents of `Request`. All methods, instead, return
// references bounded by `self`. This is easily verified by noting
// that 1) `LocalResponse` fields are private, and 2) all `impl`s
// of `LocalResponse` aside from this method abstract the lifetime
// away as `'_`, ensuring it is not used for any output value.
let boxed_req = Box::new(req);
let request: &'c Request<'c> = unsafe { &*(&*boxed_req as *const _) };
async move {
let response: Response<'c> = f(request).await;
let mut cookies = CookieJar::new(&request.state.config.secret_key);
for cookie in response.cookies() {
cookies.add_original(cookie.into_owned());
}
LocalResponse { cookies, _request: boxed_req, response, }
}
}
}
impl LocalResponse<'_> {
pub(crate) fn _response(&self) -> &Response<'_> {
&self.response
}
pub(crate) fn _cookies(&self) -> &CookieJar<'_> {
&self.cookies
}
pub(crate) async fn _into_string(mut self) -> Option<String> {
self.response.body_string().await
}
pub(crate) async fn _into_bytes(mut self) -> Option<Vec<u8>> {
self.response.body_bytes().await
}
// Generates the public API methods, which call the private methods above.
pub_response_impl!("# use rocket::local::asynchronous::Client;\n\
use rocket::local::asynchronous::LocalResponse;" async await);
}
impl AsyncRead for LocalResponse<'_> {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
let body = match self.response.body_mut() {
Some(body) => body,
_ => return Poll::Ready(Ok(()))
};
Pin::new(body.as_reader()).poll_read(cx, buf)
}
}
impl std::fmt::Debug for LocalResponse<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self._response().fmt(f)
}
}
| 34.701389 | 94 | 0.588353 |
397fe186129965d356d8657966120b2938452b31 | 3,190 |
#[macro_use]
extern crate vst;
extern crate midly;
use vst::api;
use vst::event::{Event, MidiEvent};
use vst::buffer::{AudioBuffer, SendEventBuffer};
use vst::plugin::{CanDo, HostCallback, Info, Plugin};
use midly::{live::LiveEvent, MidiMessage};
plugin_main!(MyPlugin); // Important!
#[derive(Default)]
struct MyPlugin {
host: HostCallback,
recv_buffer: SendEventBuffer,
send_buffer: SendEventBuffer,
}
impl MyPlugin {
fn send_midi(&mut self) {
self.send_buffer
.send_events(self.recv_buffer.events().events(), &mut self.host);
self.recv_buffer.clear();
}
}
impl Plugin for MyPlugin {
fn new(host: HostCallback) -> Self {
MyPlugin {
host,
..Default::default()
}
}
fn get_info(&self) -> Info {
Info {
name: "JT51Plugin".to_string(),
vendor: "Hans Baier".to_string(),
unique_id: 19750001,
..Default::default()
}
}
fn process_events(&mut self, events: &api::Events) {
let mut result: Vec<MidiEvent> = vec![];
for event in events.events() {
match event {
Event::Midi(ev) => {
let live_event = LiveEvent::parse(&ev.data).unwrap();
match live_event {
LiveEvent::Midi { channel: _, message } => match message {
MidiMessage::NoteOn { key: _, vel: _ } | MidiMessage::NoteOff { key: _, vel: _ } => {
let note1 = MidiEvent {
data: [ev.data[0], ev.data[1] + 4, ev.data[2]],
..ev
};
let note2 = MidiEvent {
data: [ev.data[0], ev.data[1] + 8, ev.data[2]],
..ev
};
result.push(ev);
result.push(note1);
result.push(note2);
}
_ => ()
}
_ => ()
}
}
_ => ()
}
}
self.recv_buffer.store_events(result);
}
fn process(&mut self, buffer: &mut AudioBuffer<f32>) {
for (input, output) in buffer.zip() {
for (in_sample, out_sample) in input.iter().zip(output) {
*out_sample = *in_sample;
}
}
self.send_midi();
}
fn process_f64(&mut self, buffer: &mut AudioBuffer<f64>) {
for (input, output) in buffer.zip() {
for (in_sample, out_sample) in input.iter().zip(output) {
*out_sample = *in_sample;
}
}
self.send_midi();
}
fn can_do(&self, can_do: CanDo) -> vst::api::Supported {
use vst::api::Supported::*;
use vst::plugin::CanDo::*;
match can_do {
SendEvents | SendMidiEvent | ReceiveEvents | ReceiveMidiEvent => Yes,
_ => No,
}
}
}
| 29.266055 | 113 | 0.44953 |
fe36d711d869c2614bca736ee9a10c1038d86921 | 19,786 | use crate::{
cli::{CliCommand, CliCommandInfo, CliConfig, CliError, ProcessResult},
spend_utils::{resolve_spend_tx_and_check_account_balance, SpendAmount},
};
use bincode::deserialize;
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
use reqwest::blocking::Client;
use serde_json::{Map, Value};
use panoptes_account_decoder::validator_info::{
self, ValidatorInfo, MAX_LONG_FIELD_LENGTH, MAX_SHORT_FIELD_LENGTH,
};
use panoptes_clap_utils::{
input_parsers::pubkey_of,
input_validators::{is_pubkey, is_url},
keypair::DefaultSigner,
};
use panoptes_cli_output::{CliValidatorInfo, CliValidatorInfoVec};
use panoptes_client::rpc_client::RpcClient;
use panoptes_config_program::{config_instruction, get_config_data, ConfigKeys, ConfigState};
use panoptes_remote_wallet::remote_wallet::RemoteWalletManager;
use panoptes_sdk::{
account::Account,
message::Message,
pubkey::Pubkey,
signature::{Keypair, Signer},
transaction::Transaction,
};
use std::{error, sync::Arc};
// Return an error if a validator details are longer than the max length.
pub fn check_details_length(string: String) -> Result<(), String> {
if string.len() > MAX_LONG_FIELD_LENGTH {
Err(format!(
"validator details longer than {:?}-byte limit",
MAX_LONG_FIELD_LENGTH
))
} else {
Ok(())
}
}
// Return an error if url field is too long or cannot be parsed.
pub fn check_url(string: String) -> Result<(), String> {
is_url(string.clone())?;
if string.len() > MAX_SHORT_FIELD_LENGTH {
Err(format!(
"url longer than {:?}-byte limit",
MAX_SHORT_FIELD_LENGTH
))
} else {
Ok(())
}
}
// Return an error if a validator field is longer than the max length.
pub fn is_short_field(string: String) -> Result<(), String> {
if string.len() > MAX_SHORT_FIELD_LENGTH {
Err(format!(
"validator field longer than {:?}-byte limit",
MAX_SHORT_FIELD_LENGTH
))
} else {
Ok(())
}
}
fn verify_keybase(
validator_pubkey: &Pubkey,
keybase_username: &Value,
) -> Result<(), Box<dyn error::Error>> {
if let Some(keybase_username) = keybase_username.as_str() {
let url = format!(
"https://keybase.pub/{}/panoptes/validator-{:?}",
keybase_username, validator_pubkey
);
let client = Client::new();
if client.head(&url).send()?.status().is_success() {
Ok(())
} else {
Err(format!("keybase_username could not be confirmed at: {}. Please add this pubkey file to your keybase profile to connect", url).into())
}
} else {
Err(format!(
"keybase_username could not be parsed as String: {}",
keybase_username
)
.into())
}
}
fn parse_args(matches: &ArgMatches<'_>) -> Value {
let mut map = Map::new();
map.insert(
"name".to_string(),
Value::String(matches.value_of("name").unwrap().to_string()),
);
if let Some(url) = matches.value_of("website") {
map.insert("website".to_string(), Value::String(url.to_string()));
}
if let Some(details) = matches.value_of("details") {
map.insert("details".to_string(), Value::String(details.to_string()));
}
if let Some(keybase_username) = matches.value_of("keybase_username") {
map.insert(
"keybaseUsername".to_string(),
Value::String(keybase_username.to_string()),
);
}
Value::Object(map)
}
fn parse_validator_info(
pubkey: &Pubkey,
account: &Account,
) -> Result<(Pubkey, Map<String, serde_json::value::Value>), Box<dyn error::Error>> {
if account.owner != panoptes_config_program::id() {
return Err(format!("{} is not a validator info account", pubkey).into());
}
let key_list: ConfigKeys = deserialize(&account.data)?;
if !key_list.keys.is_empty() {
let (validator_pubkey, _) = key_list.keys[1];
let validator_info_string: String = deserialize(get_config_data(&account.data)?)?;
let validator_info: Map<_, _> = serde_json::from_str(&validator_info_string)?;
Ok((validator_pubkey, validator_info))
} else {
Err(format!("{} could not be parsed as a validator info account", pubkey).into())
}
}
pub trait ValidatorInfoSubCommands {
fn validator_info_subcommands(self) -> Self;
}
impl ValidatorInfoSubCommands for App<'_, '_> {
fn validator_info_subcommands(self) -> Self {
self.subcommand(
SubCommand::with_name("validator-info")
.about("Publish/get Validator info on Panoptes")
.setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(
SubCommand::with_name("publish")
.about("Publish Validator info on Panoptes")
.arg(
Arg::with_name("info_pubkey")
.short("p")
.long("info-pubkey")
.value_name("PUBKEY")
.takes_value(true)
.validator(is_pubkey)
.help("The pubkey of the Validator info account to update"),
)
.arg(
Arg::with_name("name")
.index(1)
.value_name("NAME")
.takes_value(true)
.required(true)
.validator(is_short_field)
.help("Validator name"),
)
.arg(
Arg::with_name("website")
.short("w")
.long("website")
.value_name("URL")
.takes_value(true)
.validator(check_url)
.help("Validator website url"),
)
.arg(
Arg::with_name("keybase_username")
.short("n")
.long("keybase")
.value_name("USERNAME")
.takes_value(true)
.validator(is_short_field)
.help("Validator Keybase username"),
)
.arg(
Arg::with_name("details")
.short("d")
.long("details")
.value_name("DETAILS")
.takes_value(true)
.validator(check_details_length)
.help("Validator description")
)
.arg(
Arg::with_name("force")
.long("force")
.takes_value(false)
.hidden(true) // Don't document this argument to discourage its use
.help("Override keybase username validity check"),
),
)
.subcommand(
SubCommand::with_name("get")
.about("Get and parse Panoptes Validator info")
.arg(
Arg::with_name("info_pubkey")
.index(1)
.value_name("PUBKEY")
.takes_value(true)
.validator(is_pubkey)
.help("The pubkey of the Validator info account; without this argument, returns all"),
),
)
)
}
}
pub fn parse_validator_info_command(
matches: &ArgMatches<'_>,
default_signer: &DefaultSigner,
wallet_manager: &mut Option<Arc<RemoteWalletManager>>,
) -> Result<CliCommandInfo, CliError> {
let info_pubkey = pubkey_of(matches, "info_pubkey");
// Prepare validator info
let validator_info = parse_args(matches);
Ok(CliCommandInfo {
command: CliCommand::SetValidatorInfo {
validator_info,
force_keybase: matches.is_present("force"),
info_pubkey,
},
signers: vec![default_signer.signer_from_path(matches, wallet_manager)?],
})
}
pub fn parse_get_validator_info_command(
matches: &ArgMatches<'_>,
) -> Result<CliCommandInfo, CliError> {
let info_pubkey = pubkey_of(matches, "info_pubkey");
Ok(CliCommandInfo {
command: CliCommand::GetValidatorInfo(info_pubkey),
signers: vec![],
})
}
pub fn process_set_validator_info(
rpc_client: &RpcClient,
config: &CliConfig,
validator_info: &Value,
force_keybase: bool,
info_pubkey: Option<Pubkey>,
) -> ProcessResult {
// Validate keybase username
if let Some(string) = validator_info.get("keybaseUsername") {
let result = verify_keybase(&config.signers[0].pubkey(), string);
if result.is_err() {
if force_keybase {
println!("--force supplied, ignoring: {:?}", result);
} else {
result.map_err(|err| {
CliError::BadParameter(format!("Invalid validator keybase username: {}", err))
})?;
}
}
}
let validator_string = serde_json::to_string(&validator_info).unwrap();
let validator_info = ValidatorInfo {
info: validator_string,
};
// Check for existing validator-info account
let all_config = rpc_client.get_program_accounts(&panoptes_config_program::id())?;
let existing_account = all_config
.iter()
.filter(
|(_, account)| match deserialize::<ConfigKeys>(&account.data) {
Ok(key_list) => key_list.keys.contains(&(validator_info::id(), false)),
Err(_) => false,
},
)
.find(|(pubkey, account)| {
let (validator_pubkey, _) = parse_validator_info(pubkey, account).unwrap();
validator_pubkey == config.signers[0].pubkey()
});
// Create validator-info keypair to use if info_pubkey not provided or does not exist
let info_keypair = Keypair::new();
let mut info_pubkey = if let Some(pubkey) = info_pubkey {
pubkey
} else if let Some(validator_info) = existing_account {
validator_info.0
} else {
info_keypair.pubkey()
};
// Check existence of validator-info account
let balance = rpc_client.get_balance(&info_pubkey).unwrap_or(0);
let lamports =
rpc_client.get_minimum_balance_for_rent_exemption(ValidatorInfo::max_space() as usize)?;
let signers = if balance == 0 {
if info_pubkey != info_keypair.pubkey() {
println!(
"Account {:?} does not exist. Generating new keypair...",
info_pubkey
);
info_pubkey = info_keypair.pubkey();
}
vec![config.signers[0], &info_keypair]
} else {
vec![config.signers[0]]
};
let build_message = |lamports| {
let keys = vec![
(validator_info::id(), false),
(config.signers[0].pubkey(), true),
];
if balance == 0 {
println!(
"Publishing info for Validator {:?}",
config.signers[0].pubkey()
);
let mut instructions = config_instruction::create_account::<ValidatorInfo>(
&config.signers[0].pubkey(),
&info_pubkey,
lamports,
keys.clone(),
);
instructions.extend_from_slice(&[config_instruction::store(
&info_pubkey,
true,
keys,
&validator_info,
)]);
Message::new(&instructions, Some(&config.signers[0].pubkey()))
} else {
println!(
"Updating Validator {:?} info at: {:?}",
config.signers[0].pubkey(),
info_pubkey
);
let instructions = vec![config_instruction::store(
&info_pubkey,
false,
keys,
&validator_info,
)];
Message::new(&instructions, Some(&config.signers[0].pubkey()))
}
};
// Submit transaction
let (recent_blockhash, fee_calculator) = rpc_client.get_recent_blockhash()?;
let (message, _) = resolve_spend_tx_and_check_account_balance(
rpc_client,
false,
SpendAmount::Some(lamports),
&fee_calculator,
&config.signers[0].pubkey(),
build_message,
config.commitment,
)?;
let mut tx = Transaction::new_unsigned(message);
tx.try_sign(&signers, recent_blockhash)?;
let signature_str = rpc_client.send_and_confirm_transaction_with_spinner(&tx)?;
println!("Success! Validator info published at: {:?}", info_pubkey);
println!("{}", signature_str);
Ok("".to_string())
}
pub fn process_get_validator_info(
rpc_client: &RpcClient,
config: &CliConfig,
pubkey: Option<Pubkey>,
) -> ProcessResult {
let validator_info: Vec<(Pubkey, Account)> = if let Some(validator_info_pubkey) = pubkey {
vec![(
validator_info_pubkey,
rpc_client.get_account(&validator_info_pubkey)?,
)]
} else {
let all_config = rpc_client.get_program_accounts(&panoptes_config_program::id())?;
all_config
.into_iter()
.filter(|(_, validator_info_account)| {
match deserialize::<ConfigKeys>(&validator_info_account.data) {
Ok(key_list) => key_list.keys.contains(&(validator_info::id(), false)),
Err(_) => false,
}
})
.collect()
};
let mut validator_info_list: Vec<CliValidatorInfo> = vec![];
if validator_info.is_empty() {
println!("No validator info accounts found");
}
for (validator_info_pubkey, validator_info_account) in validator_info.iter() {
let (validator_pubkey, validator_info) =
parse_validator_info(validator_info_pubkey, validator_info_account)?;
validator_info_list.push(CliValidatorInfo {
identity_pubkey: validator_pubkey.to_string(),
info_pubkey: validator_info_pubkey.to_string(),
info: validator_info,
});
}
Ok(config
.output_format
.formatted_string(&CliValidatorInfoVec::new(validator_info_list)))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cli::app;
use bincode::{serialize, serialized_size};
use serde_json::json;
#[test]
fn test_check_url() {
let url = "http://test.com";
assert_eq!(check_url(url.to_string()), Ok(()));
let long_url = "http://7cLvFwLCbyHuXQ1RGzhCMobAWYPMSZ3VbUml1qWi1nkc3FD7zj9hzTZzMvYJ.com";
assert!(check_url(long_url.to_string()).is_err());
let non_url = "not parseable";
assert!(check_url(non_url.to_string()).is_err());
}
#[test]
fn test_is_short_field() {
let name = "Alice Validator";
assert_eq!(is_short_field(name.to_string()), Ok(()));
let long_name = "Alice 7cLvFwLCbyHuXQ1RGzhCMobAWYPMSZ3VbUml1qWi1nkc3FD7zj9hzTZzMvYJt6rY9";
assert!(is_short_field(long_name.to_string()).is_err());
}
#[test]
fn test_parse_args() {
let matches = app("test", "desc", "version").get_matches_from(vec![
"test",
"validator-info",
"publish",
"Alice",
"-n",
"alice_keybase",
]);
let subcommand_matches = matches.subcommand();
assert_eq!(subcommand_matches.0, "validator-info");
assert!(subcommand_matches.1.is_some());
let subcommand_matches = subcommand_matches.1.unwrap().subcommand();
assert_eq!(subcommand_matches.0, "publish");
assert!(subcommand_matches.1.is_some());
let matches = subcommand_matches.1.unwrap();
let expected = json!({
"name": "Alice",
"keybaseUsername": "alice_keybase",
});
assert_eq!(parse_args(matches), expected);
}
#[test]
fn test_validator_info_serde() {
let mut info = Map::new();
info.insert("name".to_string(), Value::String("Alice".to_string()));
let info_string = serde_json::to_string(&Value::Object(info)).unwrap();
let validator_info = ValidatorInfo {
info: info_string.clone(),
};
assert_eq!(serialized_size(&validator_info).unwrap(), 24);
assert_eq!(
serialize(&validator_info).unwrap(),
vec![
16, 0, 0, 0, 0, 0, 0, 0, 123, 34, 110, 97, 109, 101, 34, 58, 34, 65, 108, 105, 99,
101, 34, 125
]
);
let deserialized: ValidatorInfo = deserialize(&[
16, 0, 0, 0, 0, 0, 0, 0, 123, 34, 110, 97, 109, 101, 34, 58, 34, 65, 108, 105, 99, 101,
34, 125,
])
.unwrap();
assert_eq!(deserialized.info, info_string);
}
#[test]
fn test_parse_validator_info() {
let pubkey = panoptes_sdk::pubkey::new_rand();
let keys = vec![(validator_info::id(), false), (pubkey, true)];
let config = ConfigKeys { keys };
let mut info = Map::new();
info.insert("name".to_string(), Value::String("Alice".to_string()));
let info_string = serde_json::to_string(&Value::Object(info.clone())).unwrap();
let validator_info = ValidatorInfo { info: info_string };
let data = serialize(&(config, validator_info)).unwrap();
assert_eq!(
parse_validator_info(
&Pubkey::default(),
&Account {
owner: panoptes_config_program::id(),
data,
..Account::default()
}
)
.unwrap(),
(pubkey, info)
);
}
#[test]
fn test_validator_info_max_space() {
// 70-character string
let max_short_string =
"Max Length String KWpP299aFCBWvWg1MHpSuaoTsud7cv8zMJsh99aAtP8X1s26yrR1".to_string();
// 300-character string
let max_long_string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut libero quam, volutpat et aliquet eu, varius in mi. Aenean vestibulum ex in tristique faucibus. Maecenas in imperdiet turpis. Nullam feugiat aliquet erat. Morbi malesuada turpis sed dui pulvinar lobortis. Pellentesque a lectus eu leo nullam.".to_string();
let mut info = Map::new();
info.insert("name".to_string(), Value::String(max_short_string.clone()));
info.insert(
"website".to_string(),
Value::String(max_short_string.clone()),
);
info.insert(
"keybaseUsername".to_string(),
Value::String(max_short_string),
);
info.insert("details".to_string(), Value::String(max_long_string));
let info_string = serde_json::to_string(&Value::Object(info)).unwrap();
let validator_info = ValidatorInfo { info: info_string };
assert_eq!(
serialized_size(&validator_info).unwrap(),
ValidatorInfo::max_space()
);
}
}
| 36.776952 | 345 | 0.550238 |
14fc04faf859f4d779f660decf199314ba763efb | 12,683 | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use proc_macro2::{Span, TokenStream as Tokens};
use quote::TokenStreamExt;
use syn::{Ident, Visibility};
use super::parser::*;
use super::util;
lazy_static! {
/// Used for isolating different static metrics, so that structs for labels in each metric will not conflict even
/// when they have a common prefix.
static ref SCOPE_ID: AtomicUsize = AtomicUsize::new(0);
}
pub struct TokensBuilder;
impl TokensBuilder {
pub fn build(macro_body: StaticMetricMacroBody) -> Tokens {
let mut enums_definitions = HashMap::new();
let mut tokens = Tokens::new();
for item in macro_body.items {
match item {
StaticMetricMacroBodyItem::Metric(m) => {
// If this is a metric definition, expand to a `struct`.
tokens.append_all(Self::build_metric_struct(&m, &enums_definitions));
}
StaticMetricMacroBodyItem::Enum(e) => {
// If this is a label enum definition, expand to an `enum` and
// add to the collection.
tokens.append_all(Self::build_label_enum(&e));
enums_definitions.insert(e.enum_name.clone(), e);
}
}
}
tokens
}
fn build_metric_struct(
metric: &MetricDef,
enum_definitions: &HashMap<Ident, MetricEnumDef>,
) -> Tokens {
// Check `label_enum` references.
for label in &metric.labels {
let enum_ident = label.get_enum_ident();
if let Some(e) = enum_ident {
// If metric is using a `label_enum`, it must exist before the metric definition.
let enum_def = enum_definitions.get(e);
if enum_def.is_none() {
panic!("Label enum `{}` is undefined.", e)
}
// If metric has `pub` visibility, then `label_enum` should also be `pub`.
// TODO: Support other visibility, like `pub(xx)`.
if let Visibility::Public(_) = metric.visibility {
if let Visibility::Public(_) = enum_def.unwrap().visibility {
// `pub` is ok.
} else {
// others are unexpected.
panic!(
"Label enum `{}` does not have enough visibility because it is \
used in metric `{}` which has `pub` visibility.",
e, metric.struct_name
);
}
}
}
}
let label_struct: Vec<_> = metric
.labels
.iter()
.enumerate()
.map(|(i, _)| {
let builder_context = MetricBuilderContext::new(metric, enum_definitions, i);
let code_struct = builder_context.build_struct();
let code_impl = builder_context.build_impl();
let code_trait_impl = builder_context.build_local_metric_impl();
quote! {
#code_struct
#code_impl
#code_trait_impl
}
})
.collect();
let scope_id = SCOPE_ID.fetch_add(1, Ordering::Relaxed);
let scope_name = Ident::new(
&format!("prometheus_static_scope_{}", scope_id),
Span::call_site(),
);
let visibility = &metric.visibility;
let struct_name = &metric.struct_name;
quote! {
#visibility use self::#scope_name::#struct_name;
#[allow(dead_code)]
mod #scope_name {
use ::std::collections::HashMap;
use ::prometheus::*;
use ::prometheus::local::*;
#[allow(unused_imports)]
use super::*;
#(
#label_struct
)*
}
}
}
fn build_label_enum(label_enum: &MetricEnumDef) -> Tokens {
let visibility = &label_enum.visibility;
let enum_name = &label_enum.enum_name;
let enum_item_names = label_enum.definitions.get_names();
let enum_item_values = label_enum.definitions.get_values();
let match_patterns = label_enum.build_fields_with_path();
quote! {
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[derive(Clone, Copy, PartialEq)]
#visibility enum #enum_name {
#(#enum_item_names),*
}
impl #enum_name {
pub fn get_str(&self) -> &'static str {
match self {
#(
#match_patterns => #enum_item_values,
)*
}
}
}
impl ::std::fmt::Debug for #enum_name {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "{}", self.get_str())
}
}
impl ::std::fmt::Display for #enum_name {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::std::fmt::Debug::fmt(self, f)
}
}
}
}
}
struct MetricBuilderContext<'a> {
metric: &'a MetricDef,
enum_definitions: &'a HashMap<Ident, MetricEnumDef>,
label: &'a MetricLabelDef,
label_index: usize,
is_last_label: bool,
struct_name: Ident,
member_type: Ident,
}
impl<'a> MetricBuilderContext<'a> {
fn new(
metric: &'a MetricDef,
enum_definitions: &'a HashMap<Ident, MetricEnumDef>,
label_index: usize,
) -> MetricBuilderContext<'a> {
let is_last_label = label_index == metric.labels.len() - 1;
MetricBuilderContext {
metric,
enum_definitions,
label: &metric.labels[label_index],
label_index,
is_last_label,
struct_name: util::get_label_struct_name(metric.struct_name.clone(), label_index),
member_type: util::get_member_type(
metric.struct_name.clone(),
label_index,
metric.metric_type.clone(),
is_last_label,
),
}
}
fn build_struct(&self) -> Tokens {
let struct_name = &self.struct_name;
let field_names = self
.label
.get_value_def_list(self.enum_definitions)
.get_names();
let member_types: Vec<_> = field_names.iter().map(|_| &self.member_type).collect();
quote! {
#[allow(missing_copy_implementations)]
pub struct #struct_name {
#(
pub #field_names: #member_types,
)*
}
}
}
fn build_impl(&self) -> Tokens {
let struct_name = &self.struct_name;
let impl_from = self.build_impl_from();
let impl_get = self.build_impl_get();
let impl_try_get = self.build_impl_try_get();
let impl_flush = self.build_impl_flush();
quote! {
impl #struct_name {
#impl_from
#impl_get
#impl_try_get
#impl_flush
}
}
}
fn build_local_metric_impl(&self) -> Tokens {
let struct_name = &self.struct_name;
if util::is_local_metric(self.metric.metric_type.clone()) {
quote! {
impl ::prometheus::local::LocalMetric for #struct_name {
fn flush(&self) {
#struct_name::flush(self);
}
}
}
} else {
Tokens::new()
}
}
fn build_impl_from(&self) -> Tokens {
let struct_name = &self.struct_name;
let metric_vec_type = util::to_non_local_metric_type(util::get_metric_vec_type(
self.metric.metric_type.clone(),
));
let prev_labels_ident: Vec<_> = (0..self.label_index)
.map(|i| Ident::new(&format!("label_{}", i), Span::call_site()))
.collect();
let body = self.build_impl_from_body(&prev_labels_ident);
quote! {
pub fn from(
#(
#prev_labels_ident: &str,
)*
m: &#metric_vec_type
) -> #struct_name {
#struct_name {
#body
}
}
}
}
fn build_impl_from_body(&self, prev_labels_ident: &[Ident]) -> Tokens {
let member_type = &self.member_type;
let bodies: Vec<_> = self
.label
.get_value_def_list(self.enum_definitions)
.get()
.iter()
.map(|value| {
let name = &value.name;
let value = &value.value;
if self.is_last_label {
let current_label = &self.label.label_key;
let prev_labels_str: Vec<_> = prev_labels_ident
.iter()
.enumerate()
.map(|(i, _)| &self.metric.labels[i].label_key)
.collect();
let local_suffix_call =
if util::is_local_metric(self.metric.metric_type.clone()) {
quote! { .local() }
} else {
Tokens::new()
};
quote! {
#name: m.with(&{
let mut coll = HashMap::new();
#(
coll.insert(#prev_labels_str, #prev_labels_ident);
)*
coll.insert(#current_label, #value);
coll
})#local_suffix_call,
}
} else {
let prev_labels_ident = prev_labels_ident;
quote! {
#name: #member_type::from(
#(
#prev_labels_ident,
)*
#value,
m,
),
}
}
})
.collect();
quote! {
#(
#bodies
)*
}
}
/// `fn get()` is only available when label is defined by `label_enum`.
fn build_impl_get(&self) -> Tokens {
let enum_ident = self.label.get_enum_ident();
if let Some(e) = enum_ident {
let member_type = &self.member_type;
let match_patterns = self
.enum_definitions
.get(e)
.unwrap()
.build_fields_with_path();
let fields = self
.label
.get_value_def_list(self.enum_definitions)
.get_names();
quote! {
pub fn get(&self, value: #e) -> &#member_type {
match value {
#(
#match_patterns => &self.#fields,
)*
}
}
}
} else {
Tokens::new()
}
}
fn build_impl_try_get(&self) -> Tokens {
let member_type = &self.member_type;
let value_def_list = self.label.get_value_def_list(self.enum_definitions);
let names = value_def_list.get_names();
let values = value_def_list.get_values();
quote! {
pub fn try_get(&self, value: &str) -> Option<&#member_type> {
match value {
#(
#values => Some(&self.#names),
)*
_ => None,
}
}
}
}
fn build_impl_flush(&self) -> Tokens {
if util::is_local_metric(self.metric.metric_type.clone()) {
let value_def_list = self.label.get_value_def_list(self.enum_definitions);
let names = value_def_list.get_names();
quote! {
pub fn flush(&self) {
#(self.#names.flush();)*
}
}
} else {
Tokens::new()
}
}
}
| 33.201571 | 117 | 0.466767 |
64875296882d58dc74502ce526330f6b524dc64f | 9,050 | // vim: tw=80
use crate::{
idml::{ClosedZone, IDML},
types::*,
};
use futures::{
Future,
FutureExt,
StreamExt,
TryFutureExt,
TryStreamExt,
future,
channel::{oneshot, mpsc},
stream::self,
};
use std::sync::Arc;
use tokio::task::JoinHandle;
struct SyncCleaner {
/// Handle to the DML.
idml: Arc<IDML>,
/// Dirtiness threshold. Zones with less than this percentage of freed
/// space will not be cleaned.
threshold: f32,
}
impl SyncCleaner {
/// Clean zones in the foreground, blocking the task
pub fn clean_now(&self) -> impl Future<Output=Result<(), Error>> + Send {
// Outline:
// 1) Get a list of mostly-free zones
// 2) For each zone:
// let offset = 0
// while offset < sizeof(zone)
// let record = find_record(zone, offset)
// idml.move(record)
// offset += sizeof(record)
let idml2 = self.idml.clone();
self.select_zones()
.and_then(move |zones| {
// Limit concurrency to 1. To minimize HDD seeks, it's better to
// clean one at a time. Any in-zone concurrency can be managed by
// IDML:::clean_zone.
stream::iter(zones.into_iter())
.map(Ok)
.try_for_each(move |zone| {
let idml3 = idml2.clone();
idml2.txg()
.then(move |txg_guard|
idml3.clean_zone(zone, *txg_guard)
)
})
})
}
pub fn new(idml: Arc<IDML>, threshold: f32) -> Self {
SyncCleaner{idml, threshold}
}
/// Select which zones to clean and return them sorted by cleanliness:
/// dirtiest zones first.
fn select_zones(&self)
-> impl Future<Output=Result<Vec<ClosedZone>, Error>> + Send
{
let threshold = self.threshold;
let mut zones = self.idml.list_closed_zones()
.filter(move |z| {
let dirtiness = z.freed_blocks as f32 / z.total_blocks as f32;
dirtiness >= threshold
}).collect::<Vec<ClosedZone>>();
// Sort by highest percentage of free space to least
// TODO: optimize for the case where all zones have equal size,
// removing the division.
zones.sort_unstable_by(|a, b| {
// Annoyingly, f32 only implements PartialOrd, not Ord. So we
// have to define a comparator function.
let afrac = -(a.freed_blocks as f32 / a.total_blocks as f32);
let bfrac = -(b.freed_blocks as f32 / b.total_blocks as f32);
afrac.partial_cmp(&bfrac).unwrap()
});
future::ok(zones)
}
}
/// Garbage collector.
///
/// Cleans old Zones by moving their data to empty zones and erasing them.
pub struct Cleaner {
jh: JoinHandle<()>,
tx: Option<mpsc::Sender<oneshot::Sender<()>>>
}
impl Cleaner {
const DEFAULT_THRESHOLD: f32 = 0.5;
/// Clean zones immediately. Does not wait for the result to be polled!
///
/// The returned `Receiver` will deliver notification when cleaning is
/// complete. However, there is no requirement to poll it. The client may
/// drop it, and cleaning will continue in the background.
pub fn clean(&self) -> oneshot::Receiver<()> {
let (tx, rx) = oneshot::channel();
if let Err(e) = self.tx.as_ref().unwrap().clone().try_send(tx) {
if e.is_full() {
// No worries; cleaning is idempotent
} else {
panic!("{:?}", e);
}
}
rx
}
pub fn new(idml: Arc<IDML>, thresh: Option<f32>) -> Self
{
let (tx, rx) = mpsc::channel(1);
let jh = Cleaner::run(idml,
thresh.unwrap_or(Cleaner::DEFAULT_THRESHOLD), rx);
Cleaner{jh, tx: Some(tx)}
}
// Start a task that will clean the system in the background, whenever
// requested.
fn run(idml: Arc<IDML>, thresh: f32,
rx: mpsc::Receiver<oneshot::Sender<()>>)
-> JoinHandle<()>
{
tokio::spawn(async move {
let sync_cleaner = SyncCleaner::new(idml, thresh);
rx.for_each(move |tx| {
sync_cleaner.clean_now()
.map_err(Error::unhandled)
.map_ok(move |_| {
// Ignore errors. An error here indicates that the
// client doesn't want to be notified.
let _result = tx.send(());
}).map(drop)
}).await
})
}
// Shutdown the Cleaner's background task
pub async fn shutdown(mut self) {
// Ignore return value. An error indicates that the Cleaner is already
// shut down.
drop(self.tx.take());
self.jh.await.unwrap();
}
}
// LCOV_EXCL_START
#[cfg(test)]
mod t {
use crate::util::basic_runtime;
use futures::future;
use mockall::Sequence;
use super::*;
use tokio::runtime;
/// Clean in the background
#[allow(clippy::async_yields_async)]
#[test]
fn background() {
let mut idml = IDML::default();
idml.expect_list_closed_zones()
.once()
.returning(|| {
let czs = vec![
ClosedZone{freed_blocks: 0, total_blocks: 100, zid: 0,
pba: PBA::new(0, 0), txgs: TxgT::from(0)..TxgT::from(1)}
];
Box::new(czs.into_iter())
});
idml.expect_txg().never();
idml.expect_clean_zone().never();
let rt = runtime::Builder::new_current_thread()
.build()
.unwrap();
rt.spawn(async {
let cleaner = Cleaner::new(Arc::new(idml), None);
cleaner.clean()
.map_err(Error::unhandled)
});
drop(rt); // Implicitly waits for all tasks to complete
}
/// No zone is less dirty than the threshold
#[test]
fn no_sufficiently_dirty_zones() {
let mut idml = IDML::default();
idml.expect_list_closed_zones()
.once()
.returning(|| {
let czs = vec![
ClosedZone{freed_blocks: 1, total_blocks: 100, zid: 0,
pba: PBA::new(0, 0), txgs: TxgT::from(0)..TxgT::from(1)}
];
Box::new(czs.into_iter())
});
idml.expect_txg().never();
idml.expect_clean_zone().never();
let cleaner = SyncCleaner::new(Arc::new(idml), 0.5);
basic_runtime().block_on(async {
cleaner.clean_now().await
}).unwrap();
}
#[test]
fn one_sufficiently_dirty_zone() {
const TXG: TxgT = TxgT(42);
let mut idml = IDML::default();
idml.expect_list_closed_zones()
.once()
.returning(|| {
let czs = vec![
ClosedZone{freed_blocks: 55, total_blocks: 100, zid: 0,
pba: PBA::new(0, 0), txgs: TxgT::from(0)..TxgT::from(1)}
];
Box::new(czs.into_iter())
});
idml.expect_txg()
.once()
.returning(|| Box::pin(future::ready::<&'static TxgT>(&TXG)));
idml.expect_clean_zone()
.once()
.withf(move |zone, txg| {
zone.pba == PBA::new(0, 0) &&
*txg == TXG
}).returning(|_, _| Box::pin(future::ok::<(), Error>(())));
let cleaner = SyncCleaner::new(Arc::new(idml), 0.5);
basic_runtime().block_on(async {
cleaner.clean_now().await
}).unwrap();
}
#[test]
fn two_sufficiently_dirty_zones() {
const TXG: TxgT = TxgT(42);
let mut seq = Sequence::new();
let mut idml = IDML::default();
idml.expect_list_closed_zones()
.once()
.returning(|| {
let czs = vec![
ClosedZone{freed_blocks: 55, total_blocks: 100, zid: 0,
pba: PBA::new(0, 0), txgs: TxgT::from(0)..TxgT::from(1)},
ClosedZone{freed_blocks: 25, total_blocks: 100, zid: 1,
pba: PBA::new(1, 0), txgs: TxgT::from(0)..TxgT::from(1)},
ClosedZone{freed_blocks: 75, total_blocks: 100, zid: 2,
pba: PBA::new(2, 0), txgs: TxgT::from(1)..TxgT::from(2)},
];
Box::new(czs.into_iter())
});
idml.expect_txg()
.once()
.in_sequence(&mut seq)
.returning(|| Box::pin(future::ready::<&'static TxgT>(&TXG)));
idml.expect_clean_zone()
.once()
.withf(move |zone, txg| {
zone.pba == PBA::new(2, 0) &&
*txg == TXG
}).returning(|_, _| Box::pin(future::ok::<(), Error>(())));
idml.expect_txg()
.once()
.in_sequence(&mut seq)
.returning(|| Box::pin(future::ready::<&'static TxgT>(&TXG)));
idml.expect_clean_zone()
.once()
.withf(move |zone, txg| {
zone.pba == PBA::new(0, 0) &&
*txg == TXG
}).returning(|_, _| Box::pin(future::ok::<(), Error>(())));
let cleaner = SyncCleaner::new(Arc::new(idml), 0.5);
basic_runtime().block_on(async {
cleaner.clean_now().await
}).unwrap();
}
}
// LCOV_EXCL_STOP
| 31.533101 | 80 | 0.537238 |
f5fa5c773985003d985f2a4e8c43782a53573d24 | 6,022 | mod fixture;
use git_stack::git::*;
fn no_protect() -> git_stack::git::ProtectedBranches {
git_stack::git::ProtectedBranches::new(vec![]).unwrap()
}
fn protect() -> git_stack::git::ProtectedBranches {
git_stack::git::ProtectedBranches::new(vec!["master"]).unwrap()
}
mod test_branches {
use super::*;
#[test]
fn test_all() {
let mut repo = git_stack::git::InMemoryRepo::new();
let plan =
git_fixture::Dag::load(std::path::Path::new("tests/fixtures/branches.yml")).unwrap();
fixture::populate_repo(&mut repo, plan);
let branches = Branches::new(repo.local_branches());
let result = branches.all();
let mut names: Vec<_> = result
.iter()
.flat_map(|(_, b)| b.iter().map(|b| b.name.as_str()))
.collect();
names.sort_unstable();
assert_eq!(
names,
[
"base",
"feature1",
"feature2",
"initial",
"master",
"off_master"
]
);
}
#[test]
fn test_descendants() {
let mut repo = git_stack::git::InMemoryRepo::new();
let plan =
git_fixture::Dag::load(std::path::Path::new("tests/fixtures/branches.yml")).unwrap();
fixture::populate_repo(&mut repo, plan);
let base_oid = repo.resolve("base").unwrap().id;
let branches = Branches::new(repo.local_branches());
let result = branches.descendants(&repo, base_oid);
let mut names: Vec<_> = result
.iter()
.flat_map(|(_, b)| b.iter().map(|b| b.name.as_str()))
.collect();
names.sort_unstable();
// Should pick up master (branches off base)
assert_eq!(
names,
["base", "feature1", "feature2", "master", "off_master"]
);
}
#[test]
fn test_dependents() {
let mut repo = git_stack::git::InMemoryRepo::new();
let plan =
git_fixture::Dag::load(std::path::Path::new("tests/fixtures/branches.yml")).unwrap();
fixture::populate_repo(&mut repo, plan);
let base_oid = repo.resolve("base").unwrap().id;
let head_oid = repo.resolve("feature1").unwrap().id;
let branches = Branches::new(repo.local_branches());
let result = branches.dependents(&repo, base_oid, head_oid);
let mut names: Vec<_> = result
.iter()
.flat_map(|(_, b)| b.iter().map(|b| b.name.as_str()))
.collect();
names.sort_unstable();
// Shouldn't pick up master (branches off base)
assert_eq!(names, ["base", "feature1", "feature2"]);
}
#[test]
fn test_branch() {
let mut repo = git_stack::git::InMemoryRepo::new();
let plan =
git_fixture::Dag::load(std::path::Path::new("tests/fixtures/branches.yml")).unwrap();
fixture::populate_repo(&mut repo, plan);
let base_oid = repo.resolve("base").unwrap().id;
let head_oid = repo.resolve("feature1").unwrap().id;
let branches = Branches::new(repo.local_branches());
let result = branches.branch(&repo, base_oid, head_oid);
let mut names: Vec<_> = result
.iter()
.flat_map(|(_, b)| b.iter().map(|b| b.name.as_str()))
.collect();
names.sort_unstable();
// Shouldn't pick up feature1 (dependent) or master (branches off base)
assert_eq!(names, ["base", "feature1"]);
}
#[test]
fn test_protected() {
let mut repo = git_stack::git::InMemoryRepo::new();
let plan =
git_fixture::Dag::load(std::path::Path::new("tests/fixtures/branches.yml")).unwrap();
fixture::populate_repo(&mut repo, plan);
let protect = protect();
let branches = Branches::new(repo.local_branches());
let result = branches.protected(&protect);
let mut names: Vec<_> = result
.iter()
.flat_map(|(_, b)| b.iter().map(|b| b.name.as_str()))
.collect();
names.sort_unstable();
assert_eq!(names, ["master"]);
}
}
mod test_find_protected_base {
use super::*;
#[test]
fn test_no_protected() {
let mut repo = git_stack::git::InMemoryRepo::new();
let plan =
git_fixture::Dag::load(std::path::Path::new("tests/fixtures/branches.yml")).unwrap();
fixture::populate_repo(&mut repo, plan);
let protect = no_protect();
let branches = Branches::new(repo.local_branches());
let protected = branches.protected(&protect);
let head_oid = repo.resolve("base").unwrap().id;
let branch = find_protected_base(&repo, &protected, head_oid);
assert!(branch.is_none());
}
#[test]
fn test_protected_branch() {
let mut repo = git_stack::git::InMemoryRepo::new();
let plan =
git_fixture::Dag::load(std::path::Path::new("tests/fixtures/branches.yml")).unwrap();
fixture::populate_repo(&mut repo, plan);
let protect = protect();
let branches = Branches::new(repo.local_branches());
let protected = branches.protected(&protect);
let head_oid = repo.resolve("off_master").unwrap().id;
let branch = find_protected_base(&repo, &protected, head_oid);
assert!(branch.is_some());
}
#[test]
fn test_protected_base() {
let mut repo = git_stack::git::InMemoryRepo::new();
let plan =
git_fixture::Dag::load(std::path::Path::new("tests/fixtures/branches.yml")).unwrap();
fixture::populate_repo(&mut repo, plan);
let protect = protect();
let branches = Branches::new(repo.local_branches());
let protected = branches.protected(&protect);
let head_oid = repo.resolve("base").unwrap().id;
let branch = find_protected_base(&repo, &protected, head_oid);
assert!(branch.is_some());
}
}
| 32.376344 | 97 | 0.564098 |
617e72404abe2826916be9b39ec9e202182a5c05 | 2,832 | use gtk::{cairo, gdk};
use crate::error::Error;
use crate::ui::animation::Animation;
use crate::ui::color::Color;
use super::CellMetrics;
pub struct Surfaces {
// Front buffer is where all the new content will be drawn inbetween
// draw signals.
pub front: cairo::Context,
// Back buffer is where, when required, contents of previous draw iteration
// is kept.
pub back: cairo::Context,
// Prev is a intermedate buffer to which front and back buffers are drawn
// before the contents are drawn to the screen. This allows us to aniamte
// grid_scroll changes.
pub prev: cairo::Context,
pub offset_y: f64,
pub offset_y_anim: Option<Animation<f64>>,
}
impl Surfaces {
pub fn new(
win: &gdk::Window,
cell_metrics: &CellMetrics,
rows: usize,
cols: usize,
fill: &Color,
) -> Result<Self, Error> {
Ok(Surfaces {
front: Self::create_surface(win, cell_metrics, rows, cols, fill)?,
back: Self::create_surface(win, cell_metrics, rows, cols, fill)?,
prev: Self::create_surface(win, cell_metrics, rows, cols, fill)?,
offset_y: 0.0,
offset_y_anim: None,
})
}
fn create_surface(
win: &gdk::Window,
cell_metrics: &CellMetrics,
rows: usize,
cols: usize,
fill: &Color,
) -> Result<cairo::Context, Error> {
let w = cell_metrics.width * cols as f64;
let h = cell_metrics.height * rows as f64;
let surface = win
.create_similar_surface(
cairo::Content::Color,
w.ceil() as i32,
h.ceil() as i32,
)
.ok_or(Error::FailedToCreateSurface())?;
let cairo_context = cairo::Context::new(&surface)?;
cairo_context.save()?;
cairo_context.set_source_rgb(fill.r, fill.g, fill.b);
cairo_context.paint()?;
cairo_context.restore()?;
Ok(cairo_context)
}
pub fn set_animation(&mut self, y: f64, duration_ms: i64, ft_now: i64) {
self.offset_y_anim = Some(Animation {
start: -y + self.offset_y,
end: 0.0,
start_time: ft_now,
end_time: ft_now + 1000 * duration_ms,
});
}
pub fn tick(&mut self, ft: i64) -> bool {
if let Some(ref anim) = self.offset_y_anim {
if let Some(t) = anim.tick(ft) {
// NOTE(ville): There are some precision issues when rendeing, hence the floor.
self.offset_y =
(anim.start + t * (anim.end - anim.start)).floor();
} else {
self.offset_y = anim.end;
self.offset_y_anim = None;
}
true
} else {
false
}
}
}
| 29.195876 | 95 | 0.555085 |
9bb8579e33458cdddeed0be33b1273161867a71d | 1,867 | use crate::core_foundation_sys::{
base::{ CFTypeRef, },
string::CFStringRef,
dictionary::CFDictionaryRef,
};
#[derive(Debug, Copy, Clone)]
pub enum __CVBuffer { }
pub type CVBufferRef = *mut __CVBuffer;
pub type CVAttachmentMode = u32;
pub const kCVAttachmentMode_ShouldNotPropagate: CVAttachmentMode = 0;
pub const kCVAttachmentMode_ShouldPropagate: CVAttachmentMode = 1;
extern "C" {
pub static kCVBufferPropagatedAttachmentsKey: CFStringRef;
pub static kCVBufferNonPropagatedAttachmentsKey: CFStringRef;
pub static kCVBufferMovieTimeKey: CFStringRef;
pub static kCVBufferTimeValueKey: CFStringRef;
pub static kCVBufferTimeScaleKey: CFStringRef;
pub fn CVBufferRetain(buffer: CVBufferRef) -> CVBufferRef;
pub fn CVBufferRelease(buffer: CVBufferRef);
pub fn CVBufferSetAttachment(buffer: CVBufferRef,
key: CFStringRef,
value: CFTypeRef,
attachmentMode: CVAttachmentMode);
pub fn CVBufferGetAttachment(buffer: CVBufferRef,
key: CFStringRef,
attachmentMode: *mut CVAttachmentMode) -> CFTypeRef;
pub fn CVBufferRemoveAttachment(buffer: CVBufferRef,
key: CFStringRef);
pub fn CVBufferRemoveAllAttachments(buffer: CVBufferRef);
pub fn CVBufferGetAttachments(buffer: CVBufferRef,
attachmentMode: CVAttachmentMode) -> CFDictionaryRef;
pub fn CVBufferSetAttachments(buffer: CVBufferRef,
theAttachments: CFDictionaryRef,
attachmentMode: CVAttachmentMode);
pub fn CVBufferPropagateAttachments(sourceBuffer: CVBufferRef,
destinationBuffer: CVBufferRef);
}
| 38.895833 | 87 | 0.644885 |
18d14f4f53c7518aa08436353dd6cd6a1f443d4f | 4,159 | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
account_address::AccountAddress,
account_config::lbr_type_tag,
transaction::{
RawTransaction, Script, SignedTransaction, Transaction, TransactionInfo,
TransactionListWithProof, TransactionPayload, TransactionToCommit, TransactionWithProof,
},
};
use lcs::test_helpers::assert_canonical_encode_decode;
use libra_crypto::{
ed25519::{self, Ed25519PrivateKey, Ed25519Signature},
PrivateKey, Uniform,
};
use libra_prost_ext::test_helpers::assert_protobuf_encode_decode;
use proptest::prelude::*;
use std::convert::TryFrom;
#[test]
fn test_invalid_signature() {
let proto_txn: crate::proto::types::SignedTransaction = SignedTransaction::new(
RawTransaction::new_script(
AccountAddress::random(),
0,
Script::new(vec![], vec![], vec![]),
0,
0,
lbr_type_tag(),
std::time::Duration::new(0, 0),
),
Ed25519PrivateKey::generate_for_testing().public_key(),
Ed25519Signature::try_from(&[1u8; 64][..]).unwrap(),
)
.into();
let txn = SignedTransaction::try_from(proto_txn)
.expect("initial conversion from_proto should succeed");
txn.check_signature()
.expect_err("signature checking should fail");
}
proptest! {
#[test]
fn test_sign_raw_transaction(raw_txn in any::<RawTransaction>(), keypair in ed25519::keypair_strategy()) {
let txn = raw_txn.sign(&keypair.private_key, keypair.public_key).unwrap();
let signed_txn = txn.into_inner();
assert!(signed_txn.check_signature().is_ok());
}
#[test]
fn transaction_payload_lcs_roundtrip(txn_payload in any::<TransactionPayload>()) {
assert_canonical_encode_decode(txn_payload);
}
#[test]
fn raw_transaction_lcs_roundtrip(raw_txn in any::<RawTransaction>()) {
assert_canonical_encode_decode(raw_txn);
}
#[test]
fn signed_transaction_lcs_roundtrip(signed_txn in any::<SignedTransaction>()) {
assert_canonical_encode_decode(signed_txn);
}
#[test]
fn signed_transaction_proto_roundtrip(signed_txn in any::<SignedTransaction>()) {
assert_protobuf_encode_decode::<crate::proto::types::SignedTransaction, SignedTransaction>(&signed_txn);
}
#[test]
fn transaction_info_lcs_roundtrip(txn_info in any::<TransactionInfo>()) {
assert_canonical_encode_decode(txn_info);
}
#[test]
fn transaction_info_proto_roundtrip(txn_info in any::<TransactionInfo>()) {
assert_protobuf_encode_decode::<crate::proto::types::TransactionInfo, TransactionInfo>(&txn_info);
}
#[test]
fn transaction_to_commit_proto_roundtrip(txn_to_commit in any::<TransactionToCommit>()) {
assert_protobuf_encode_decode::<crate::proto::types::TransactionToCommit, TransactionToCommit>(&txn_to_commit);
}
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(10))]
#[test]
fn transaction_list_with_proof_lcs_roundtrip(txn_list in any::<TransactionListWithProof>()) {
assert_canonical_encode_decode(txn_list);
}
#[test]
fn transaction_list_with_proof_proto_roundtrip(txn_list in any::<TransactionListWithProof>()) {
assert_protobuf_encode_decode::<crate::proto::types::TransactionListWithProof, TransactionListWithProof>(&txn_list);
}
#[test]
fn transaction_lcs_roundtrip(txn in any::<Transaction>()) {
assert_canonical_encode_decode(txn);
}
#[test]
fn transaction_proto_roundtrip(txn in any::<Transaction>()) {
assert_protobuf_encode_decode::<crate::proto::types::Transaction, Transaction>(&txn);
}
#[test]
fn transaction_with_proof_lcs_roundtrip(txn_with_proof in any::<TransactionWithProof>()) {
assert_canonical_encode_decode(txn_with_proof);
}
#[test]
fn transaction_with_proof_proto_roundtrip(txn_with_proof in any::<TransactionWithProof>()) {
assert_protobuf_encode_decode::<crate::proto::types::TransactionWithProof, TransactionWithProof>(&txn_with_proof);
}
}
| 34.658333 | 124 | 0.699447 |
7affb7861a7ec8e7017222ad4333d962a552c13d | 3,071 | #![no_std]
#![cfg_attr(not(test), no_main)]
#![feature(const_generics, const_evaluatable_checked)]
extern crate avr_std_stub;
use atmega32u4_hal::pac::Peripherals;
use kbforge::board::planck_rev2::build_system;
use kbforge::keycode::qmk::*;
use kbforge::keycode::Keycode;
use kbforge::keymap::Layered;
const CK_LOWR: Keycode = Keycode::User(0);
const CK_RAIS: Keycode = Keycode::User(1);
const LAYER_LOWER: usize = 1;
const LAYER_RAISE: usize = 2;
const LAYER_SETUP: usize = 2;
#[no_mangle]
#[cfg(not(test))]
pub extern "C" fn main() {
let keymap = Layered {
#[rustfmt::skip]
layers: [
// 0: Default/Base
[
[KC_TAB , KC_Q , KC_W , KC_E , KC_R , KC_T , KC_Y , KC_U , KC_I , KC_O , KC_P , KC_BSPC],
[KC_CLCK, KC_A , KC_S , KC_D , KC_F , KC_G , KC_H , KC_J , KC_K , KC_L , KC_SCLN, KC_QUOT],
[KC_LSFT, KC_Z , KC_X , KC_C , KC_V , KC_B , KC_N , KC_M , KC_COMM, KC_DOT , KC_SLSH, KC_RSFT],
[KC_LCTL, KC_LGUI, KC_LALT, XXXXXXX, CK_LOWR, KC_ENT , KC_SPC , CK_RAIS, XXXXXXX, KC_RALT, KC_RGUI, KC_RCTL],
],
// 1: Lower
[
[KC_ESC , KC_F1 , KC_F2 , KC_F3 , KC_F4 , _______, KC_INS , KC_HOME, KC_UP , KC_END , KC_PGUP, _______],
[_______, KC_F5 , KC_F6 , KC_F7 , KC_F8 , _______, KC_DEL , KC_LEFT, KC_DOWN, KC_RGHT, KC_PGDN, _______],
[_______, KC_F9 , KC_F10 , KC_F11 , KC_F12 , _______, _______, KC_PAUS, KC_PSCR, KC_SLCK, _______, _______],
[_______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______],
],
// 2: Raise
[
[KC_GRV , KC_1 , KC_2 , KC_3 , KC_4 , KC_5 , KC_6 , KC_7 , KC_8 , KC_9 , KC_0 , _______],
[_______, _______, _______, _______, _______, _______, _______, KC_MINS, KC_EQL , KC_LBRC, KC_RBRC, KC_BSLS],
[_______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______],
[_______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______],
],
// 3: Setup
[
[RESET , _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______],
[_______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______],
[_______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______],
[_______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______],
],
],
layer_mask: 0x00000001,
};
let peripherals = Peripherals::take().unwrap();
let mut system = build_system(peripherals, keymap);
loop {
system.poll().map_err(|_| ()).unwrap();
}
}
| 48.746032 | 125 | 0.580918 |
2f48863c856ec87ed6261f18d9ad2c6e4c090fa9 | 11,219 | use std::{
convert::TryFrom,
time::{Duration, SystemTime},
};
use crate::{
doc,
oid::ObjectId,
spec::BinarySubtype,
tests::LOCK,
Binary,
Bson,
DateTime,
Document,
JavaScriptCodeWithScope,
Regex,
Timestamp,
};
use serde_json::{json, Value};
#[test]
fn to_json() {
let _guard = LOCK.run_concurrently();
let mut doc = Document::new();
doc.insert(
"_id",
Bson::ObjectId(ObjectId::from_bytes(*b"abcdefghijkl")),
);
doc.insert("first", Bson::Int32(1));
doc.insert("second", Bson::String("foo".to_owned()));
doc.insert("alphanumeric", Bson::String("bar".to_owned()));
let data: Value = Bson::Document(doc).into();
assert!(data.is_object());
let obj = data.as_object().unwrap();
let id = obj.get("_id").unwrap();
assert!(id.is_object());
let id_val = id.get("$oid").unwrap();
assert!(id_val.is_string());
assert_eq!(id_val, "6162636465666768696a6b6c");
let first = obj.get("first").unwrap();
assert!(first.is_number());
assert_eq!(first.as_i64().unwrap(), 1);
let second = obj.get("second").unwrap();
assert!(second.is_string());
assert_eq!(second.as_str().unwrap(), "foo");
let alphanumeric = obj.get("alphanumeric").unwrap();
assert!(alphanumeric.is_string());
assert_eq!(alphanumeric.as_str().unwrap(), "bar");
}
#[test]
fn bson_default() {
let _guard = LOCK.run_concurrently();
let bson1 = Bson::default();
assert_eq!(bson1, Bson::Null);
}
#[test]
fn test_display_timestamp_type() {
let x = Timestamp {
time: 100,
increment: 200,
};
let output = "Timestamp(100, 200)";
assert_eq!(format!("{}", x), output);
assert_eq!(format!("{}", Bson::from(x)), output);
}
#[test]
fn test_display_regex_type() {
let x = Regex {
pattern: String::from("pattern"),
options: String::from("options"),
};
let output = "/pattern/options";
assert_eq!(format!("{}", x), output);
assert_eq!(format!("{}", Bson::from(x)), output);
}
#[test]
fn test_display_jscodewithcontext_type() {
let x = JavaScriptCodeWithScope {
code: String::from("code"),
scope: doc! {"x": 2},
};
let output = "code";
assert_eq!(format!("{}", x), output);
assert_eq!(format!("{}", Bson::from(x)), output);
}
#[test]
fn test_display_binary_type() {
let encoded_bytes = "aGVsbG8gd29ybGQ=";
let bytes = base64::decode(encoded_bytes).unwrap();
let x = Binary {
subtype: BinarySubtype::Generic,
bytes,
};
let output = format!("Binary(0x0, {})", encoded_bytes);
assert_eq!(format!("{}", x), output);
assert_eq!(format!("{}", Bson::from(x)), output);
}
#[test]
fn document_default() {
let _guard = LOCK.run_concurrently();
let doc1 = Document::default();
assert_eq!(doc1.keys().count(), 0);
assert_eq!(doc1, Document::new());
}
#[test]
fn from_impls() {
let _guard = LOCK.run_concurrently();
assert_eq!(Bson::from(1.5f32), Bson::Double(1.5));
assert_eq!(Bson::from(2.25f64), Bson::Double(2.25));
assert_eq!(Bson::from("data"), Bson::String(String::from("data")));
assert_eq!(
Bson::from(String::from("data")),
Bson::String(String::from("data"))
);
assert_eq!(Bson::from(doc! {}), Bson::Document(Document::new()));
assert_eq!(Bson::from(false), Bson::Boolean(false));
assert_eq!(
Bson::from(Regex {
pattern: String::from("\\s+$"),
options: String::from("i")
}),
Bson::RegularExpression(Regex {
pattern: String::from("\\s+$"),
options: String::from("i")
})
);
assert_eq!(
Bson::from(JavaScriptCodeWithScope {
code: String::from("alert(\"hi\");"),
scope: doc! {}
}),
Bson::JavaScriptCodeWithScope(JavaScriptCodeWithScope {
code: String::from("alert(\"hi\");"),
scope: doc! {}
})
);
//
assert_eq!(
Bson::from(Binary {
subtype: BinarySubtype::Generic,
bytes: vec![1, 2, 3]
}),
Bson::Binary(Binary {
subtype: BinarySubtype::Generic,
bytes: vec![1, 2, 3]
})
);
assert_eq!(Bson::from(-48i32), Bson::Int32(-48));
assert_eq!(Bson::from(-96i64), Bson::Int64(-96));
assert_eq!(Bson::from(152u32), Bson::Int32(152));
let oid = ObjectId::new();
assert_eq!(
Bson::from(b"abcdefghijkl"),
Bson::ObjectId(ObjectId::from_bytes(*b"abcdefghijkl"))
);
assert_eq!(Bson::from(oid), Bson::ObjectId(oid));
assert_eq!(
Bson::from(vec![1, 2, 3]),
Bson::Array(vec![Bson::Int32(1), Bson::Int32(2), Bson::Int32(3)])
);
assert_eq!(
Bson::try_from(json!({"_id": {"$oid": oid.to_hex()}, "name": ["bson-rs"]})).unwrap(),
Bson::Document(doc! {"_id": &oid, "name": ["bson-rs"]})
);
// References
assert_eq!(Bson::from(&24i32), Bson::Int32(24));
assert_eq!(
Bson::try_from(&String::from("data")).unwrap(),
Bson::String(String::from("data"))
);
assert_eq!(Bson::from(&oid), Bson::ObjectId(oid));
assert_eq!(
Bson::from(&doc! {"a": "b"}),
Bson::Document(doc! {"a": "b"})
);
// Optionals
assert_eq!(Bson::from(Some(4)), Bson::Int32(4));
assert_eq!(
Bson::from(Some(String::from("data"))),
Bson::String(String::from("data"))
);
assert_eq!(Bson::from(None::<i32>), Bson::Null);
assert_eq!(Bson::from(None::<String>), Bson::Null);
assert_eq!(doc! {"x": Some(4)}, doc! {"x": 4});
assert_eq!(doc! {"x": None::<i32>}, doc! {"x": Bson::Null});
let db_pointer = Bson::try_from(json!({
"$dbPointer": {
"$ref": "db.coll",
"$id": { "$oid": "507f1f77bcf86cd799439011" },
}
}))
.unwrap();
let db_pointer = db_pointer.as_db_pointer().unwrap();
assert_eq!(Bson::from(db_pointer), Bson::DbPointer(db_pointer.clone()));
}
#[test]
fn timestamp_ordering() {
let _guard = LOCK.run_concurrently();
let ts1 = Timestamp {
time: 0,
increment: 1,
};
let ts2 = Timestamp {
time: 0,
increment: 2,
};
let ts3 = Timestamp {
time: 1,
increment: 0,
};
assert!(ts1 < ts2);
assert!(ts1 < ts3);
assert!(ts2 < ts3);
}
#[test]
fn from_chrono_datetime() {
let _guard = LOCK.run_concurrently();
fn assert_millisecond_precision(dt: DateTime) {
assert!(dt.to_chrono().timestamp_subsec_micros() % 1000 == 0);
}
fn assert_subsec_millis(dt: DateTime, millis: u32) {
assert_eq!(dt.to_chrono().timestamp_subsec_millis(), millis)
}
let now = chrono::Utc::now();
let dt = DateTime::from_chrono(now);
assert_millisecond_precision(dt);
#[cfg(feature = "chrono-0_4")]
{
let bson = Bson::from(now);
assert_millisecond_precision(bson.as_datetime().unwrap().to_owned());
let from_chrono = DateTime::from(now);
assert_millisecond_precision(from_chrono);
}
let no_subsec_millis: chrono::DateTime<chrono::Utc> = "2014-11-28T12:00:09Z".parse().unwrap();
let dt = DateTime::from_chrono(no_subsec_millis);
assert_millisecond_precision(dt);
assert_subsec_millis(dt, 0);
#[cfg(feature = "chrono-0_4")]
{
let dt = DateTime::from(no_subsec_millis);
assert_millisecond_precision(dt);
assert_subsec_millis(dt, 0);
let bson = Bson::from(dt);
assert_millisecond_precision(bson.as_datetime().unwrap().to_owned());
assert_subsec_millis(bson.as_datetime().unwrap().to_owned(), 0);
}
for s in &[
"2014-11-28T12:00:09.123Z",
"2014-11-28T12:00:09.123456Z",
"2014-11-28T12:00:09.123456789Z",
] {
let chrono_dt: chrono::DateTime<chrono::Utc> = s.parse().unwrap();
let dt = DateTime::from_chrono(chrono_dt);
assert_millisecond_precision(dt);
assert_subsec_millis(dt, 123);
#[cfg(feature = "chrono-0_4")]
{
let dt = DateTime::from(chrono_dt);
assert_millisecond_precision(dt);
assert_subsec_millis(dt, 123);
let bson = Bson::from(chrono_dt);
assert_millisecond_precision(bson.as_datetime().unwrap().to_owned());
assert_subsec_millis(bson.as_datetime().unwrap().to_owned(), 123);
}
}
#[cfg(feature = "chrono-0_4")]
{
let bdt = DateTime::from(chrono::MAX_DATETIME);
assert_eq!(
bdt.to_chrono().timestamp_millis(),
chrono::MAX_DATETIME.timestamp_millis()
);
let bdt = DateTime::from(chrono::MIN_DATETIME);
assert_eq!(
bdt.to_chrono().timestamp_millis(),
chrono::MIN_DATETIME.timestamp_millis()
);
let bdt = DateTime::MAX;
assert_eq!(bdt.to_chrono(), chrono::MAX_DATETIME);
let bdt = DateTime::MIN;
assert_eq!(bdt.to_chrono(), chrono::MIN_DATETIME);
}
}
#[test]
fn system_time() {
let _guard = LOCK.run_concurrently();
let st = SystemTime::now();
let bt_into: crate::DateTime = st.into();
let bt_from = crate::DateTime::from_system_time(st);
assert_eq!(bt_into, bt_from);
assert_eq!(
bt_into.timestamp_millis(),
st.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_millis() as i64
);
let st = SystemTime::UNIX_EPOCH
.checked_add(Duration::from_millis(1234))
.unwrap();
let bt = crate::DateTime::from_system_time(st);
assert_eq!(bt.timestamp_millis(), 1234);
assert_eq!(bt.to_system_time(), st);
assert_eq!(
crate::DateTime::MAX.to_system_time(),
SystemTime::UNIX_EPOCH + Duration::from_millis(i64::MAX as u64)
);
assert_eq!(
crate::DateTime::MIN.to_system_time(),
SystemTime::UNIX_EPOCH - Duration::from_millis((i64::MIN as i128).abs() as u64)
);
assert_eq!(
crate::DateTime::from_system_time(SystemTime::UNIX_EPOCH).timestamp_millis(),
0
);
}
#[test]
fn debug_print() {
let oid = ObjectId::parse_str("000000000000000000000000").unwrap();
let doc = doc! {
"oid": oid,
"arr": Bson::Array(vec! [
Bson::Null,
Bson::Timestamp(Timestamp { time: 1, increment: 1 }),
]),
"doc": doc! { "a": 1, "b": "data"},
};
let normal_print = "Document({\"oid\": ObjectId(\"000000000000000000000000\"), \"arr\": \
Array([Null, Timestamp { time: 1, increment: 1 }]), \"doc\": \
Document({\"a\": Int32(1), \"b\": String(\"data\")})})";
let pretty_print = "Document({
\"oid\": ObjectId(
\"000000000000000000000000\",
),
\"arr\": Array([
Null,
Timestamp {
time: 1,
increment: 1,
},
]),
\"doc\": Document({
\"a\": Int32(
1,
),
\"b\": String(
\"data\",
),
}),
})";
assert_eq!(format!("{:?}", doc), normal_print);
assert_eq!(format!("{:#?}", doc), pretty_print);
}
| 28.474619 | 98 | 0.564667 |
48ac3d7f8f4e33e95e7736e7eacd147408c1f32f | 4,544 | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
use libc::{c_uchar, c_int, c_void};
/// Regex wraps a std::regex regular expression.
///
/// It cannot be used safely from multiple threads simultaneously.
pub struct Regex {
re: *mut stdcpp_regexp,
}
unsafe impl Send for Regex {}
impl Drop for Regex {
fn drop(&mut self) {
unsafe { stdcpp_regexp_free(self.re); }
}
}
#[derive(Debug)]
pub struct Error(());
impl Regex {
pub fn new(pattern: &str) -> Result<Regex, Error> {
unsafe { Ok(Regex { re: stdcpp_regexp_new(pattern.into()) }) }
}
pub fn is_match(&self, text: &str) -> bool {
unsafe {
stdcpp_regexp_match(self.re, text.into(), 0, text.len() as c_int)
}
}
pub fn find_iter<'r, 't>(&'r self, text: &'t str) -> FindMatches<'r, 't> {
FindMatches {
re: self,
text: text,
last_end: 0,
last_match: None,
}
}
fn find_at(&self, text: &str, start: usize) -> Option<(usize, usize)> {
let (mut s, mut e): (c_int, c_int) = (0, 0);
let matched = unsafe {
stdcpp_regexp_find(
self.re,
text.into(),
start as c_int,
text.len() as c_int,
&mut s,
&mut e,
)
};
if matched {
Some((s as usize, e as usize))
} else {
None
}
}
}
pub struct FindMatches<'r, 't> {
re: &'r Regex,
text: &'t str,
last_end: usize,
last_match: Option<usize>,
}
// This implementation is identical to the one Rust uses, since both Rust's
// regex engine and std::regex handle empty matches in the same way.
impl<'r, 't> Iterator for FindMatches<'r, 't> {
type Item = (usize, usize);
fn next(&mut self) -> Option<(usize, usize)> {
fn next_after_empty(text: &str, i: usize) -> usize {
let b = match text.as_bytes().get(i) {
None => return text.len() + 1,
Some(&b) => b,
};
let inc = if b <= 0x7F {
1
} else if b <= 0b110_11111 {
2
} else if b <= 0b1110_1111 {
3
} else {
4
};
i + inc
}
if self.last_end > self.text.len() {
return None;
}
let (s, e) = match self.re.find_at(self.text, self.last_end) {
None => return None,
Some((s, e)) => (s, e),
};
assert!(s >= self.last_end);
if s == e {
// This is an empty match. To ensure we make progress, start
// the next search at the smallest possible starting position
// of the next match following this one.
self.last_end = next_after_empty(&self.text, e);
// Don't accept empty matches immediately following a match.
// Just move on to the next match.
if Some(e) == self.last_match {
return self.next();
}
} else {
self.last_end = e;
}
self.last_match = Some(self.last_end);
Some((s, e))
}
}
// stdcpp FFI is below. Note that this uses a hand-rolled C API that is defined
// in stdcpp.cpp.
type stdcpp_regexp = c_void;
#[repr(C)]
struct stdcpp_string {
text: *const c_uchar,
len: c_int,
}
impl<'a> From<&'a str> for stdcpp_string {
fn from(s: &'a str) -> stdcpp_string {
stdcpp_string { text: s.as_ptr(), len: s.len() as c_int }
}
}
extern {
fn stdcpp_regexp_new(pat: stdcpp_string) -> *mut stdcpp_regexp;
fn stdcpp_regexp_free(re: *mut stdcpp_regexp);
fn stdcpp_regexp_match(
re: *mut stdcpp_regexp,
text: stdcpp_string,
startpos: c_int,
endpos: c_int,
) -> bool;
fn stdcpp_regexp_find(
re: *mut stdcpp_regexp,
text: stdcpp_string,
startpos: c_int,
endpos: c_int,
match_start: *mut c_int,
match_end: *mut c_int,
) -> bool;
}
| 27.707317 | 79 | 0.539833 |
87f82c650b5a6d93f3aeac33a2ef954f96a1d8de | 1,363 | pub struct Scanner<R: std::io::Read> {
reader: R,
}
impl<R: std::io::Read> Scanner<R> {
/// let stdin = std::io::stdin();
/// let mut sc = Scanner::new(stdin.lock());
pub fn new(reader: R) -> Self { Self { reader: reader } }
pub fn scan<T: std::str::FromStr>(&mut self) -> T {
use std::io::Read;
self.reader.by_ref().bytes().map(|c| c.unwrap() as char)
.skip_while(|c| c.is_whitespace())
.take_while(|c| !c.is_whitespace())
.collect::<String>().parse::<T>().ok().unwrap()
}
}
// #[allow(warnings)]
fn main() {
use std::io::Write;
let stdin = std::io::stdin();
let mut sc = Scanner::new(std::io::BufReader::new(stdin.lock()));
let stdout = std::io::stdout();
let out = &mut std::io::BufWriter::new(stdout.lock());
let n: usize = sc.scan();
let m: usize = sc.scan();
let mut relation = vec![0usize; n];
for _ in 0..m {
let a: usize = sc.scan::<usize>() - 1;
let b: usize = sc.scan::<usize>() - 1;
relation[a] |= 1 << b;
relation[b] |= 1 << a;
}
for i in 0..n {
let mut ff = 0usize;
for j in 0..n {
if relation[i] >> j & 1 == 0 { continue; }
ff |= relation[j];
}
ff &= !(relation[i] | 1 << i);
writeln!(out, "{}", ff.count_ones()).unwrap();
}
}
| 28.395833 | 69 | 0.493764 |
6a9671c2618a31c6d9ab441406821dc717d3cd1f | 2,887 | //! Serial
// uart_hal_macro can be called with too-many arguments
#![allow(clippy::too_many_arguments)]
use core::{fmt, marker::PhantomData};
use crate::{
gpio::*,
hal::{prelude::*, serial},
sysctl::{self, Clocks},
time::Bps,
};
use nb::{self, block};
use void::Void;
pub use tm4c129x::{UART0, UART1, UART2, UART3, UART4, UART5, UART6, UART7};
pub use tm4c_hal::{serial::*, uart_hal_macro, uart_pin_macro};
/// Serial abstraction
pub struct Serial<UART, TX, RX, RTS, CTS> {
uart: UART,
tx_pin: TX,
rx_pin: RX,
rts_pin: RTS,
cts_pin: CTS,
nl_mode: NewlineMode,
}
/// Serial receiver
pub struct Rx<UART, RX, CTS> {
_uart: PhantomData<UART>,
pin: RX,
flow_pin: CTS,
}
/// Serial transmitter
pub struct Tx<UART, TX, RTS> {
uart: UART,
pin: TX,
flow_pin: RTS,
nl_mode: NewlineMode,
}
uart_pin_macro!(UART0,
cts: [(gpioh::PH1, AF1), (gpiom::PM4, AF1), (gpiob::PB4, AF1)],
// dcd: [(gpioh::PH2, AF1), (gpiom::PM5, AF1), (gpiop::PP3, AF2)],
// dsr: [(gpioh::PH3, AF1), (gpiom::PM6, AF1), (gpiop::PP4, AF2)],
// dtr: [(gpiop::PP2, AF1)],
// ri: [(gpiok::PK7, AF1), (gpiom::PM7, AF1)],
rts: [(gpioh::PH0, AF1), (gpiob::PB5, AF1)],
rx: [(gpioa::PA0, AF1)],
tx: [(gpioa::PA1, AF1)],
);
uart_pin_macro!(UART1,
cts: [(gpion::PN1, AF1), (gpiop::PP3, AF1)],
// dcd: [(gpioe::PE2, AF1), (gpion::PN2, AF1)],
// dsr: [(gpioe::PE1, AF1), (gpion::PN3, AF1)],
// dtr: [(gpioe::PE3, AF1), (gpion::PN4, AF1)],
// ri: [(gpioe::PE4, AF1), (gpion::PN5, AF1)],
rts: [(gpioe::PE0, AF1), (gpion::PN0, AF1)],
rx: [(gpiob::PB0, AF1), (gpioq::PQ4, AF1)],
tx: [(gpiob::PB1, AF1)],
);
uart_pin_macro!(UART2,
cts: [(gpiod::PD7, AF1), (gpion::PN3, AF2)],
rts: [(gpiod::PD6, AF1), (gpion::PN2, AF2)],
rx: [(gpioa::PA6, AF1), (gpiod::PD4, AF1)],
tx: [(gpioa::PA7, AF1), (gpiod::PD5, AF1)],
);
uart_pin_macro!(UART3,
cts: [(gpiop::PP5, AF1), (gpion::PN5, AF2)],
rts: [(gpiop::PP4, AF1), (gpion::PN4, AF2)],
rx: [(gpioa::PA4, AF1), (gpioj::PJ0, AF1)],
tx: [(gpioa::PA5, AF1), (gpioj::PJ1, AF1)],
);
uart_pin_macro!(UART4,
cts: [(gpiok::PK3, AF1)],
rts: [(gpiok::PK2, AF1)],
rx: [(gpioa::PA2, AF1), (gpiok::PK0, AF1)],
tx: [(gpioa::PA3, AF1), (gpiok::PK1, AF1)],
);
uart_pin_macro!(UART5,
cts: [],
rts: [],
rx: [(gpioc::PC6, AF1)],
tx: [(gpioc::PC7, AF1)],
);
uart_pin_macro!(UART6,
cts: [],
rts: [],
rx: [(gpiop::PP0, AF1)],
tx: [(gpiop::PP1, AF1)],
);
uart_pin_macro!(UART7,
cts: [],
rts: [],
rx: [(gpioc::PC4, AF1)],
tx: [(gpioc::PC5, AF1)],
);
uart_hal_macro! {
UART0: (Uart0, uart0),
UART1: (Uart1, uart1),
UART2: (Uart2, uart2),
UART3: (Uart3, uart3),
UART4: (Uart4, uart4),
UART5: (Uart5, uart5),
UART6: (Uart6, uart6),
UART7: (Uart7, uart7),
}
| 24.260504 | 75 | 0.546935 |
4b6bac12a0ecd13c3d61f183441a5ba6f88218e5 | 6,310 | pub mod converters;
mod default_plugins;
pub mod renderer;
mod webgl2_render_pass;
mod webgl2_renderer;
mod webgl2_resources;
use crate::renderer::WebGL2RenderResourceContext;
use bevy::app::{prelude::*, Events};
use bevy::window::{WindowCreated, Windows};
pub use default_plugins::*;
use std::sync::Arc;
pub use webgl2_render_pass::*;
pub use webgl2_renderer::*;
pub use webgl2_resources::*;
use bevy::asset::{Assets, HandleUntyped};
use bevy::ecs::prelude::*;
use bevy::ecs::{
schedule::{StageLabel, SystemStage},
world::World,
};
use bevy::reflect::TypeUuid;
use bevy::render::{
pipeline::PipelineDescriptor,
renderer::{shared_buffers_update_system, RenderResourceContext, SharedBuffers},
shader::{Shader, ShaderStage},
RenderStage,
};
pub const SPRITE_PIPELINE_HANDLE: HandleUntyped =
HandleUntyped::weak_from_u64(PipelineDescriptor::TYPE_UUID, 2785347840338765446);
pub const SPRITE_SHEET_PIPELINE_HANDLE: HandleUntyped =
HandleUntyped::weak_from_u64(PipelineDescriptor::TYPE_UUID, 9016885805180281612);
pub const PBR_PIPELINE_HANDLE: HandleUntyped =
HandleUntyped::weak_from_u64(PipelineDescriptor::TYPE_UUID, 13148362314012771389);
pub const UI_PIPELINE_HANDLE: HandleUntyped =
HandleUntyped::weak_from_u64(PipelineDescriptor::TYPE_UUID, 3234320022263993878);
#[derive(Debug, Hash, PartialEq, Eq, Clone, StageLabel)]
pub enum WebGL2Stage {
PreRenderResource,
}
#[derive(Default)]
pub struct WebGL2Plugin;
impl Plugin for WebGL2Plugin {
fn build(&self, app: &mut App) {
{
let world = &mut app.world;
let cell = world.cell();
let pipelines = cell
.get_resource_mut::<Assets<PipelineDescriptor>>()
.unwrap();
let mut shaders = cell.get_resource_mut::<Assets<Shader>>().unwrap();
let shader_overrides = vec![
(
SPRITE_PIPELINE_HANDLE,
include_str!("shaders/sprite.vert"),
include_str!("shaders/sprite.frag"),
),
(
SPRITE_SHEET_PIPELINE_HANDLE,
include_str!("shaders/sprite_sheet.vert"),
include_str!("shaders/sprite_sheet.frag"),
),
(
PBR_PIPELINE_HANDLE,
include_str!("shaders/pbr.vert"),
include_str!("shaders/pbr.frag"),
),
(
UI_PIPELINE_HANDLE,
include_str!("shaders/ui.vert"),
include_str!("shaders/ui.frag"),
),
];
for (pipeline_handle, vert_source, frag_source) in shader_overrides {
if let Some(pipeline) = pipelines.get(pipeline_handle) {
let _ = shaders.set(
&pipeline.shader_stages.vertex,
Shader::from_glsl(ShaderStage::Vertex, vert_source),
);
if let Some(frag_handle) = &pipeline.shader_stages.fragment {
let _ = shaders.set(
frag_handle,
Shader::from_glsl(ShaderStage::Fragment, frag_source),
);
}
}
}
}
let world = &mut app.world;
let render_system = webgl2_render_system(world);
let handle_events_system = webgl2_handle_window_created_events_system();
app.add_stage_before(
RenderStage::RenderResource,
WebGL2Stage::PreRenderResource,
SystemStage::parallel(),
)
.add_system_to_stage(
WebGL2Stage::PreRenderResource,
handle_events_system.exclusive_system(),
)
.add_system_to_stage(RenderStage::Render, render_system.exclusive_system())
.add_system_to_stage(
RenderStage::PostRender,
shared_buffers_update_system.system(),
);
}
}
pub fn webgl2_handle_window_created_events_system() -> impl FnMut(&mut World) {
let events = Events::<WindowCreated>::default();
let mut window_created_event_reader = events.get_reader();
move |world| {
let events = {
let window_created_events = world.get_resource::<Events<WindowCreated>>().unwrap();
window_created_event_reader
.iter(&window_created_events)
.cloned()
.collect::<Vec<_>>()
};
for window_created_event in events {
let window_id = {
let windows = world.get_resource::<Windows>().unwrap();
let window = windows
.get(window_created_event.id)
.expect("Received window created event for non-existent window");
window.id()
};
let render_resource_context = {
let device = &*world.get_resource::<Arc<Device>>().unwrap();
let winit_windows = world.get_resource::<bevy::winit::WinitWindows>().unwrap();
let winit_window = winit_windows.get_window(window_id).unwrap();
let mut render_resource_context = WebGL2RenderResourceContext::new(device.clone());
render_resource_context.initialize(&winit_window);
render_resource_context
};
world.insert_resource::<Box<dyn RenderResourceContext>>(Box::new(
render_resource_context,
));
//resources.insert(SharedBuffers::new(Box::new(render_resource_context)));
world.insert_resource(SharedBuffers::new(4096));
}
}
}
pub fn webgl2_render_system(world: &mut World) -> impl FnMut(&mut World) {
let mut webgl2_renderer = WebGL2Renderer::default();
let device = webgl2_renderer.device.clone();
world.insert_resource(device);
move |world| {
webgl2_renderer.update(world);
}
}
#[macro_export]
macro_rules! gl_call {
($device:ident . $func:ident ( $( $i:expr),* $(,)? ) ) => {
{
// trace!("gl call: {} {:?}", stringify!($func ( $( $i ),*)), ( $( $i ),*) );
let result = $device . $func( $( $i ),* );
result
}
};
}
| 36.264368 | 99 | 0.583835 |
76ac0310e49d0761ca5b7a0a0ed1adb6bfe0a630 | 43,793 | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
//! This crate provides [`DiemDB`] which represents physical storage of the core Diem data
//! structures.
//!
//! It relays read/write operations on the physical storage via [`schemadb`] to the underlying
//! Key-Value storage system, and implements diem data structures on top of it.
#[cfg(any(feature = "diemsum"))]
pub mod diemsum;
// Used in this and other crates for testing.
#[cfg(any(test, feature = "fuzzing"))]
pub mod test_helper;
pub mod backup;
pub mod errors;
pub mod metrics;
pub mod schema;
mod change_set;
mod event_store;
mod ledger_counters;
mod ledger_store;
mod pruner;
mod state_store;
mod system_store;
mod transaction_store;
#[cfg(any(test, feature = "fuzzing"))]
#[allow(dead_code)]
mod diemdb_test;
#[cfg(feature = "fuzzing")]
pub use diemdb_test::test_save_blocks_impl;
use crate::{
backup::{backup_handler::BackupHandler, restore_handler::RestoreHandler},
change_set::{ChangeSet, SealedChangeSet},
errors::DiemDbError,
event_store::EventStore,
ledger_counters::LedgerCounters,
ledger_store::LedgerStore,
metrics::{
DIEM_STORAGE_API_LATENCY_SECONDS, DIEM_STORAGE_COMMITTED_TXNS,
DIEM_STORAGE_LATEST_TXN_VERSION, DIEM_STORAGE_LEDGER_VERSION,
DIEM_STORAGE_NEXT_BLOCK_EPOCH, DIEM_STORAGE_OTHER_TIMERS_SECONDS,
DIEM_STORAGE_ROCKSDB_PROPERTIES,
},
pruner::Pruner,
schema::*,
state_store::StateStore,
system_store::SystemStore,
transaction_store::TransactionStore,
};
use anyhow::{ensure, format_err, Result};
use diem_config::config::RocksdbConfig;
use diem_crypto::hash::{CryptoHash, HashValue, SPARSE_MERKLE_PLACEHOLDER_HASH};
use diem_logger::prelude::*;
use diem_types::{
account_address::AccountAddress,
account_state::AccountState,
account_state_blob::{AccountStateBlob, AccountStateWithProof},
contract_event::{ContractEvent, EventByVersionWithProof, EventWithProof},
epoch_change::EpochChangeProof,
event::EventKey,
ledger_info::LedgerInfoWithSignatures,
proof::{
AccountStateProof, AccumulatorConsistencyProof, EventProof, SparseMerkleProof,
TransactionInfoListWithProof,
},
state_proof::StateProof,
transaction::{
AccountTransactionsWithProof, TransactionInfo, TransactionListWithProof,
TransactionToCommit, TransactionWithProof, Version, PRE_GENESIS_VERSION,
},
};
use itertools::{izip, zip_eq};
use move_core_types::{
language_storage::{ModuleId, StructTag},
resolver::{ModuleResolver, ResourceResolver},
};
use once_cell::sync::Lazy;
use schemadb::{ColumnFamilyName, Options, DB, DEFAULT_CF_NAME};
use std::{
collections::HashMap,
convert::TryFrom,
iter::Iterator,
path::Path,
sync::{mpsc, Arc, Mutex},
thread::{self, JoinHandle},
time::{Duration, Instant},
};
use storage_interface::{DbReader, DbWriter, MoveDbReader, Order, StartupInfo, TreeState};
const MAX_LIMIT: u64 = 1000;
// TODO: Either implement an iteration API to allow a very old client to loop through a long history
// or guarantee that there is always a recent enough waypoint and client knows to boot from there.
const MAX_NUM_EPOCH_ENDING_LEDGER_INFO: usize = 100;
static ROCKSDB_PROPERTY_MAP: Lazy<HashMap<&str, &str>> = Lazy::new(|| {
[
(
"diem_rocksdb_live_sst_files_size_bytes",
"rocksdb.live-sst-files-size",
),
(
"diem_rocksdb_all_memtables_size_bytes",
"rocksdb.size-all-mem-tables",
),
(
"diem_rocksdb_num_running_compactions",
"rocksdb.num-running-compactions",
),
(
"diem_rocksdb_num_running_flushes",
"rocksdb.num-running-flushes",
),
(
"diem_rocksdb_block_cache_usage_bytes",
"rocksdb.block-cache-usage",
),
(
"diem_rocksdb_cf_size_bytes",
"rocksdb.estimate-live-data-size",
),
]
.iter()
.cloned()
.collect()
});
fn error_if_too_many_requested(num_requested: u64, max_allowed: u64) -> Result<()> {
if num_requested > max_allowed {
Err(DiemDbError::TooManyRequested(num_requested, max_allowed).into())
} else {
Ok(())
}
}
fn gen_rocksdb_options(config: &RocksdbConfig) -> Options {
let mut db_opts = Options::default();
db_opts.set_max_open_files(config.max_open_files);
db_opts.set_max_total_wal_size(config.max_total_wal_size);
db_opts
}
fn update_rocksdb_properties(db: &DB) -> Result<()> {
let _timer = DIEM_STORAGE_OTHER_TIMERS_SECONDS
.with_label_values(&["update_rocksdb_properties"])
.start_timer();
for cf_name in DiemDB::column_families() {
for (property_name, rocksdb_property_argument) in &*ROCKSDB_PROPERTY_MAP {
DIEM_STORAGE_ROCKSDB_PROPERTIES
.with_label_values(&[cf_name, property_name])
.set(db.get_property(cf_name, rocksdb_property_argument)? as i64);
}
}
Ok(())
}
#[derive(Debug)]
struct RocksdbPropertyReporter {
sender: Mutex<mpsc::Sender<()>>,
join_handle: Option<JoinHandle<()>>,
}
impl RocksdbPropertyReporter {
fn new(db: Arc<DB>) -> Self {
let (send, recv) = mpsc::channel();
let join_handle = Some(thread::spawn(move || loop {
if let Err(e) = update_rocksdb_properties(&db) {
warn!(
error = ?e,
"Updating rocksdb property failed."
);
}
// report rocksdb properties each 10 seconds
match recv.recv_timeout(Duration::from_secs(10)) {
Ok(_) => break,
Err(mpsc::RecvTimeoutError::Timeout) => (),
Err(mpsc::RecvTimeoutError::Disconnected) => break,
}
}));
Self {
sender: Mutex::new(send),
join_handle,
}
}
}
impl Drop for RocksdbPropertyReporter {
fn drop(&mut self) {
// Notify the property reporting thread to exit
self.sender.lock().unwrap().send(()).unwrap();
self.join_handle
.take()
.expect("Rocksdb property reporting thread must exist.")
.join()
.expect("Rocksdb property reporting thread should join peacefully.");
}
}
/// This holds a handle to the underlying DB responsible for physical storage and provides APIs for
/// access to the core Diem data structures.
#[derive(Debug)]
pub struct DiemDB {
db: Arc<DB>,
ledger_store: Arc<LedgerStore>,
transaction_store: Arc<TransactionStore>,
state_store: Arc<StateStore>,
event_store: Arc<EventStore>,
system_store: SystemStore,
rocksdb_property_reporter: RocksdbPropertyReporter,
pruner: Option<Pruner>,
}
impl DiemDB {
fn column_families() -> Vec<ColumnFamilyName> {
vec![
/* LedgerInfo CF = */ DEFAULT_CF_NAME,
EPOCH_BY_VERSION_CF_NAME,
EVENT_ACCUMULATOR_CF_NAME,
EVENT_BY_KEY_CF_NAME,
EVENT_BY_VERSION_CF_NAME,
EVENT_CF_NAME,
JELLYFISH_MERKLE_NODE_CF_NAME,
LEDGER_COUNTERS_CF_NAME,
STALE_NODE_INDEX_CF_NAME,
TRANSACTION_CF_NAME,
TRANSACTION_ACCUMULATOR_CF_NAME,
TRANSACTION_BY_ACCOUNT_CF_NAME,
TRANSACTION_BY_HASH_CF_NAME,
TRANSACTION_INFO_CF_NAME,
]
}
fn new_with_db(db: DB, prune_window: Option<u64>) -> Self {
let db = Arc::new(db);
DiemDB {
db: Arc::clone(&db),
event_store: Arc::new(EventStore::new(Arc::clone(&db))),
ledger_store: Arc::new(LedgerStore::new(Arc::clone(&db))),
state_store: Arc::new(StateStore::new(Arc::clone(&db))),
transaction_store: Arc::new(TransactionStore::new(Arc::clone(&db))),
system_store: SystemStore::new(Arc::clone(&db)),
rocksdb_property_reporter: RocksdbPropertyReporter::new(Arc::clone(&db)),
pruner: prune_window.map(|n| Pruner::new(Arc::clone(&db), n)),
}
}
pub fn open<P: AsRef<Path> + Clone>(
db_root_path: P,
readonly: bool,
prune_window: Option<u64>,
rocksdb_config: RocksdbConfig,
) -> Result<Self> {
ensure!(
prune_window.is_none() || !readonly,
"Do not set prune_window when opening readonly.",
);
let path = db_root_path.as_ref().join("diemdb");
let instant = Instant::now();
let mut rocksdb_opts = gen_rocksdb_options(&rocksdb_config);
let db = if readonly {
DB::open_readonly(
path.clone(),
"diemdb_ro",
Self::column_families(),
&rocksdb_opts,
)?
} else {
rocksdb_opts.create_if_missing(true);
rocksdb_opts.create_missing_column_families(true);
DB::open(
path.clone(),
"diemdb",
Self::column_families(),
&rocksdb_opts,
)?
};
let ret = Self::new_with_db(db, prune_window);
info!(
path = path,
time_ms = %instant.elapsed().as_millis(),
"Opened DiemDB.",
);
Ok(ret)
}
pub fn open_as_secondary<P: AsRef<Path> + Clone>(
db_root_path: P,
secondary_path: P,
mut rocksdb_config: RocksdbConfig,
) -> Result<Self> {
let primary_path = db_root_path.as_ref().join("diemdb");
let secondary_path = secondary_path.as_ref().to_path_buf();
// Secondary needs `max_open_files = -1` per https://github.com/facebook/rocksdb/wiki/Secondary-instance
rocksdb_config.max_open_files = -1;
let rocksdb_opts = gen_rocksdb_options(&rocksdb_config);
Ok(Self::new_with_db(
DB::open_as_secondary(
primary_path,
secondary_path,
"diemdb_sec",
Self::column_families(),
&rocksdb_opts,
)?,
None, // prune_window
))
}
/// This opens db in non-readonly mode, without the pruner.
#[cfg(any(test, feature = "fuzzing"))]
pub fn new_for_test<P: AsRef<Path> + Clone>(db_root_path: P) -> Self {
Self::open(
db_root_path,
false, /* readonly */
None, /* pruner */
RocksdbConfig::default(),
)
.expect("Unable to open DiemDB")
}
/// This force the db to update rocksdb properties immediately.
pub fn update_rocksdb_properties(&self) -> Result<()> {
update_rocksdb_properties(&self.db)
}
/// Returns ledger infos reflecting epoch bumps starting with the given epoch. If there are no
/// more than `MAX_NUM_EPOCH_ENDING_LEDGER_INFO` results, this function returns all of them,
/// otherwise the first `MAX_NUM_EPOCH_ENDING_LEDGER_INFO` results are returned and a flag
/// (when true) will be used to indicate the fact that there is more.
fn get_epoch_ending_ledger_infos(
&self,
start_epoch: u64,
end_epoch: u64,
) -> Result<(Vec<LedgerInfoWithSignatures>, bool)> {
self.get_epoch_ending_ledger_infos_impl(
start_epoch,
end_epoch,
MAX_NUM_EPOCH_ENDING_LEDGER_INFO,
)
}
fn get_epoch_ending_ledger_infos_impl(
&self,
start_epoch: u64,
end_epoch: u64,
limit: usize,
) -> Result<(Vec<LedgerInfoWithSignatures>, bool)> {
ensure!(
start_epoch <= end_epoch,
"Bad epoch range [{}, {})",
start_epoch,
end_epoch,
);
// Note that the latest epoch can be the same with the current epoch (in most cases), or
// current_epoch + 1 (when the latest ledger_info carries next validator set)
let latest_epoch = self
.ledger_store
.get_latest_ledger_info()?
.ledger_info()
.next_block_epoch();
ensure!(
end_epoch <= latest_epoch,
"Unable to provide epoch change ledger info for still open epoch. asked upper bound: {}, last sealed epoch: {}",
end_epoch,
latest_epoch - 1, // okay to -1 because genesis LedgerInfo has .next_block_epoch() == 1
);
let (paging_epoch, more) = if end_epoch - start_epoch > limit as u64 {
(start_epoch + limit as u64, true)
} else {
(end_epoch, false)
};
let lis = self
.ledger_store
.get_epoch_ending_ledger_info_iter(start_epoch, paging_epoch)?
.collect::<Result<Vec<_>>>()?;
ensure!(
lis.len() == (paging_epoch - start_epoch) as usize,
"DB corruption: missing epoch ending ledger info for epoch {}",
lis.last()
.map(|li| li.ledger_info().next_block_epoch())
.unwrap_or(start_epoch),
);
Ok((lis, more))
}
fn get_transaction_with_proof(
&self,
version: Version,
ledger_version: Version,
fetch_events: bool,
) -> Result<TransactionWithProof> {
let proof = self
.ledger_store
.get_transaction_info_with_proof(version, ledger_version)?;
let transaction = self.transaction_store.get_transaction(version)?;
// If events were requested, also fetch those.
let events = if fetch_events {
Some(self.event_store.get_events_by_version(version)?)
} else {
None
};
Ok(TransactionWithProof {
version,
transaction,
events,
proof,
})
}
// ================================== Backup APIs ===================================
/// Gets an instance of `BackupHandler` for data backup purpose.
pub fn get_backup_handler(&self) -> BackupHandler {
BackupHandler::new(
Arc::clone(&self.ledger_store),
Arc::clone(&self.transaction_store),
Arc::clone(&self.state_store),
Arc::clone(&self.event_store),
)
}
// ================================== Private APIs ==================================
fn get_events_with_proof_by_event_key(
&self,
event_key: &EventKey,
start_seq_num: u64,
order: Order,
limit: u64,
ledger_version: Version,
) -> Result<Vec<EventWithProof>> {
error_if_too_many_requested(limit, MAX_LIMIT)?;
let get_latest = order == Order::Descending && start_seq_num == u64::max_value();
let cursor = if get_latest {
// Caller wants the latest, figure out the latest seq_num.
// In the case of no events on that path, use 0 and expect empty result below.
self.event_store
.get_latest_sequence_number(ledger_version, event_key)?
.unwrap_or(0)
} else {
start_seq_num
};
// Convert requested range and order to a range in ascending order.
let (first_seq, real_limit) = get_first_seq_num_and_limit(order, cursor, limit)?;
// Query the index.
let mut event_indices = self.event_store.lookup_events_by_key(
event_key,
first_seq,
real_limit,
ledger_version,
)?;
// When descending, it's possible that user is asking for something beyond the latest
// sequence number, in which case we will consider it a bad request and return an empty
// list.
// For example, if the latest sequence number is 100, and the caller is asking for 110 to
// 90, we will get 90 to 100 from the index lookup above. Seeing that the last item
// is 100 instead of 110 tells us 110 is out of bound.
if order == Order::Descending {
if let Some((seq_num, _, _)) = event_indices.last() {
if *seq_num < cursor {
event_indices = Vec::new();
}
}
}
let mut events_with_proof = event_indices
.into_iter()
.map(|(seq, ver, idx)| {
let (event, event_proof) = self
.event_store
.get_event_with_proof_by_version_and_index(ver, idx)?;
ensure!(
seq == event.sequence_number(),
"Index broken, expected seq:{}, actual:{}",
seq,
event.sequence_number()
);
let txn_info_with_proof = self
.ledger_store
.get_transaction_info_with_proof(ver, ledger_version)?;
let proof = EventProof::new(txn_info_with_proof, event_proof);
Ok(EventWithProof::new(ver, idx, event, proof))
})
.collect::<Result<Vec<_>>>()?;
if order == Order::Descending {
events_with_proof.reverse();
}
Ok(events_with_proof)
}
/// Convert a `ChangeSet` to `SealedChangeSet`.
///
/// Specifically, counter increases are added to current counter values and converted to DB
/// alternations.
fn seal_change_set(
&self,
first_version: Version,
num_txns: Version,
mut cs: ChangeSet,
) -> Result<(SealedChangeSet, Option<LedgerCounters>)> {
// Avoid reading base counter values when not necessary.
let counters = if num_txns > 0 {
Some(self.system_store.bump_ledger_counters(
first_version,
first_version + num_txns - 1,
&mut cs,
)?)
} else {
None
};
Ok((SealedChangeSet { batch: cs.batch }, counters))
}
fn save_transactions_impl(
&self,
txns_to_commit: &[TransactionToCommit],
first_version: u64,
mut cs: &mut ChangeSet,
) -> Result<HashValue> {
let last_version = first_version + txns_to_commit.len() as u64 - 1;
// Account state updates. Gather account state root hashes
let account_state_sets = txns_to_commit
.iter()
.map(|txn_to_commit| txn_to_commit.account_states().clone())
.collect::<Vec<_>>();
let node_hashes = txns_to_commit
.iter()
.map(|txn_to_commit| txn_to_commit.jf_node_hashes())
.collect::<Option<Vec<_>>>();
let state_root_hashes = self.state_store.put_account_state_sets(
account_state_sets,
node_hashes,
first_version,
&mut cs,
)?;
// Event updates. Gather event accumulator root hashes.
let event_root_hashes = zip_eq(first_version..=last_version, txns_to_commit)
.map(|(ver, txn_to_commit)| {
self.event_store
.put_events(ver, txn_to_commit.events(), &mut cs)
})
.collect::<Result<Vec<_>>>()?;
// Transaction updates. Gather transaction hashes.
zip_eq(first_version..=last_version, txns_to_commit).try_for_each(
|(ver, txn_to_commit)| {
self.transaction_store
.put_transaction(ver, txn_to_commit.transaction(), &mut cs)
},
)?;
// Transaction accumulator updates. Get result root hash.
let txn_infos = izip!(txns_to_commit, state_root_hashes, event_root_hashes)
.map(|(t, s, e)| {
Ok(TransactionInfo::new(
t.transaction().hash(),
s,
e,
t.gas_used(),
t.status().clone(),
))
})
.collect::<Result<Vec<_>>>()?;
assert_eq!(txn_infos.len(), txns_to_commit.len());
let new_root_hash =
self.ledger_store
.put_transaction_infos(first_version, &txn_infos, &mut cs)?;
Ok(new_root_hash)
}
/// Write the whole schema batch including all data necessary to mutate the ledger
/// state of some transaction by leveraging rocksdb atomicity support. Also committed are the
/// LedgerCounters.
fn commit(&self, sealed_cs: SealedChangeSet) -> Result<()> {
self.db.write_schemas(sealed_cs.batch)?;
Ok(())
}
fn wake_pruner(&self, latest_version: Version) {
if let Some(pruner) = self.pruner.as_ref() {
pruner.wake(latest_version)
}
}
}
impl DbReader for DiemDB {
fn get_epoch_ending_ledger_infos(
&self,
start_epoch: u64,
end_epoch: u64,
) -> Result<EpochChangeProof> {
gauged_api("get_epoch_ending_ledger_infos", || {
let (ledger_info_with_sigs, more) =
Self::get_epoch_ending_ledger_infos(self, start_epoch, end_epoch)?;
Ok(EpochChangeProof::new(ledger_info_with_sigs, more))
})
}
fn get_latest_account_state(
&self,
address: AccountAddress,
) -> Result<Option<AccountStateBlob>> {
gauged_api("get_latest_account_state", || {
let ledger_info_with_sigs = self.ledger_store.get_latest_ledger_info()?;
let version = ledger_info_with_sigs.ledger_info().version();
let (blob, _proof) = self
.state_store
.get_account_state_with_proof_by_version(address, version)?;
Ok(blob)
})
}
fn get_latest_ledger_info(&self) -> Result<LedgerInfoWithSignatures> {
gauged_api("get_latest_ledger_info", || {
self.ledger_store.get_latest_ledger_info()
})
}
fn get_account_transaction(
&self,
address: AccountAddress,
seq_num: u64,
include_events: bool,
ledger_version: Version,
) -> Result<Option<TransactionWithProof>> {
gauged_api("get_account_transaction", || {
self.transaction_store
.get_account_transaction_version(address, seq_num, ledger_version)?
.map(|txn_version| {
self.get_transaction_with_proof(txn_version, ledger_version, include_events)
})
.transpose()
})
}
fn get_account_transactions(
&self,
address: AccountAddress,
start_seq_num: u64,
limit: u64,
include_events: bool,
ledger_version: Version,
) -> Result<AccountTransactionsWithProof> {
gauged_api("get_account_transactions", || {
error_if_too_many_requested(limit, MAX_LIMIT)?;
let txns_with_proofs = self
.transaction_store
.get_account_transaction_version_iter(
address,
start_seq_num,
limit,
ledger_version,
)?
.map(|result| {
let (_seq_num, txn_version) = result?;
self.get_transaction_with_proof(txn_version, ledger_version, include_events)
})
.collect::<Result<Vec<_>>>()?;
Ok(AccountTransactionsWithProof::new(txns_with_proofs))
})
}
// ======================= State Synchronizer Internal APIs ===================================
/// Gets a batch of transactions for the purpose of synchronizing state to another node.
///
/// This is used by the State Synchronizer module internally.
fn get_transactions(
&self,
start_version: Version,
limit: u64,
ledger_version: Version,
fetch_events: bool,
) -> Result<TransactionListWithProof> {
gauged_api("get_transactions", || {
error_if_too_many_requested(limit, MAX_LIMIT)?;
if start_version > ledger_version || limit == 0 {
return Ok(TransactionListWithProof::new_empty());
}
let limit = std::cmp::min(limit, ledger_version - start_version + 1);
let txns = (start_version..start_version + limit)
.map(|version| self.transaction_store.get_transaction(version))
.collect::<Result<Vec<_>>>()?;
let txn_infos = (start_version..start_version + limit)
.map(|version| self.ledger_store.get_transaction_info(version))
.collect::<Result<Vec<_>>>()?;
let events = if fetch_events {
Some(
(start_version..start_version + limit)
.map(|version| self.event_store.get_events_by_version(version))
.collect::<Result<Vec<_>>>()?,
)
} else {
None
};
let proof = TransactionInfoListWithProof::new(
self.ledger_store.get_transaction_range_proof(
Some(start_version),
limit,
ledger_version,
)?,
txn_infos,
);
Ok(TransactionListWithProof::new(
txns,
events,
Some(start_version),
proof,
))
})
}
fn get_events(
&self,
event_key: &EventKey,
start: u64,
order: Order,
limit: u64,
) -> Result<Vec<(u64, ContractEvent)>> {
gauged_api("get_events", || {
let events_with_proofs =
self.get_events_with_proofs(event_key, start, order, limit, None)?;
let events = events_with_proofs
.into_iter()
.map(|e| (e.transaction_version, e.event))
.collect();
Ok(events)
})
}
fn get_events_with_proofs(
&self,
event_key: &EventKey,
start: u64,
order: Order,
limit: u64,
known_version: Option<u64>,
) -> Result<Vec<EventWithProof>> {
gauged_api("get_events_with_proofs", || {
let version = match known_version {
Some(version) => version,
None => self.get_latest_version()?,
};
let events =
self.get_events_with_proof_by_event_key(event_key, start, order, limit, version)?;
Ok(events)
})
}
/// Gets ledger info at specified version and ensures it's an epoch ending.
fn get_epoch_ending_ledger_info(&self, version: u64) -> Result<LedgerInfoWithSignatures> {
gauged_api("get_epoch_ending_ledger_info", || {
self.ledger_store.get_epoch_ending_ledger_info(version)
})
}
fn get_state_proof_with_ledger_info(
&self,
known_version: u64,
ledger_info_with_sigs: LedgerInfoWithSignatures,
) -> Result<StateProof> {
gauged_api("get_state_proof_with_ledger_info", || {
let ledger_info = ledger_info_with_sigs.ledger_info();
ensure!(
known_version <= ledger_info.version(),
"Client known_version {} larger than ledger version {}.",
known_version,
ledger_info.version(),
);
let known_epoch = self.ledger_store.get_epoch(known_version)?;
let end_epoch = ledger_info.next_block_epoch();
let epoch_change_proof = if known_epoch < end_epoch {
let (ledger_infos_with_sigs, more) =
self.get_epoch_ending_ledger_infos(known_epoch, end_epoch)?;
EpochChangeProof::new(ledger_infos_with_sigs, more)
} else {
EpochChangeProof::new(vec![], /* more = */ false)
};
// Only return a consistency proof up to the verifiable end LI. If a
// client still needs to sync more epoch change LI's, then they cannot
// verify the latest LI nor verify a consistency proof up to the latest
// LI. If the client needs more epochs, we just return the consistency
// proof up to the last epoch change LI.
let verifiable_li = if epoch_change_proof.more {
epoch_change_proof
.ledger_info_with_sigs
.last()
.ok_or_else(|| format_err!(
"No epoch changes despite claiming the client needs to sync more epochs: known_epoch={}, end_epoch={}",
known_epoch, end_epoch,
))?
.ledger_info()
} else {
ledger_info
};
let consistency_proof = self
.ledger_store
.get_consistency_proof(Some(known_version), verifiable_li.version())?;
Ok(StateProof::new(
ledger_info_with_sigs,
epoch_change_proof,
consistency_proof,
))
})
}
fn get_state_proof(&self, known_version: u64) -> Result<StateProof> {
gauged_api("get_state_proof", || {
let ledger_info_with_sigs = self.ledger_store.get_latest_ledger_info()?;
self.get_state_proof_with_ledger_info(known_version, ledger_info_with_sigs)
})
}
fn get_account_state_with_proof(
&self,
address: AccountAddress,
version: Version,
ledger_version: Version,
) -> Result<AccountStateWithProof> {
gauged_api("get_account_state_with_proof", || {
ensure!(
version <= ledger_version,
"The queried version {} should be equal to or older than ledger version {}.",
version,
ledger_version
);
{
let latest_version = self.get_latest_version()?;
ensure!(
ledger_version <= latest_version,
"ledger_version specified {} is greater than committed version {}.",
ledger_version,
latest_version
);
}
let txn_info_with_proof = self
.ledger_store
.get_transaction_info_with_proof(version, ledger_version)?;
let (account_state_blob, sparse_merkle_proof) = self
.state_store
.get_account_state_with_proof_by_version(address, version)?;
Ok(AccountStateWithProof::new(
version,
account_state_blob,
AccountStateProof::new(txn_info_with_proof, sparse_merkle_proof),
))
})
}
fn get_startup_info(&self) -> Result<Option<StartupInfo>> {
gauged_api("get_startup_info", || self.ledger_store.get_startup_info())
}
fn get_account_state_with_proof_by_version(
&self,
address: AccountAddress,
version: Version,
) -> Result<(
Option<AccountStateBlob>,
SparseMerkleProof<AccountStateBlob>,
)> {
gauged_api("get_account_state_with_proof_by_version", || {
self.state_store
.get_account_state_with_proof_by_version(address, version)
})
}
fn get_latest_state_root(&self) -> Result<(Version, HashValue)> {
gauged_api("get_latest_state_root", || {
let (version, txn_info) = self.ledger_store.get_latest_transaction_info()?;
Ok((version, txn_info.state_root_hash()))
})
}
fn get_latest_tree_state(&self) -> Result<TreeState> {
gauged_api("get_latest_tree_state", || {
let tree_state = match self.ledger_store.get_latest_transaction_info_option()? {
Some((version, txn_info)) => {
self.ledger_store.get_tree_state(version + 1, txn_info)?
}
None => TreeState::new(
0,
vec![],
self.state_store
.get_root_hash_option(PRE_GENESIS_VERSION)?
.unwrap_or(*SPARSE_MERKLE_PLACEHOLDER_HASH),
),
};
info!(
num_transactions = tree_state.num_transactions,
state_root_hash = %tree_state.account_state_root_hash,
description = tree_state.describe(),
"Got latest TreeState."
);
Ok(tree_state)
})
}
fn get_block_timestamp(&self, version: u64) -> Result<u64> {
gauged_api("get_block_timestamp", || {
let ts = match self.transaction_store.get_block_metadata(version)? {
Some((_v, block_meta)) => block_meta.into_inner().1,
// genesis timestamp is 0
None => 0,
};
Ok(ts)
})
}
fn get_event_by_version_with_proof(
&self,
event_key: &EventKey,
event_version: u64,
proof_version: u64,
) -> Result<EventByVersionWithProof> {
gauged_api("get_event_by_version_with_proof", || {
let latest_version = self.get_latest_version()?;
ensure!(
proof_version <= latest_version,
"cannot construct proofs for a version that doesn't exist yet: proof_version: {}, latest_version: {}",
proof_version, latest_version,
);
ensure!(
event_version <= proof_version,
"event_version {} must be <= proof_version {}",
event_version,
proof_version,
);
// Get the latest sequence number of an event at or before the
// requested event_version.
let maybe_seq_num = self
.event_store
.get_latest_sequence_number(event_version, event_key)?;
let (lower_bound_incl, upper_bound_excl) = if let Some(seq_num) = maybe_seq_num {
// We need to request the surrounding events (surrounding
// as in E_i.version <= event_version < E_{i+1}.version) in order
// to prove that there are no intermediate events, i.e.,
// E_j, where E_i.version < E_j.version <= event_version.
//
// This limit also works for the case where `event_version` is
// after the latest event, since the upper bound will just be None.
let limit = 2;
let events = self.get_events_with_proof_by_event_key(
event_key,
seq_num,
Order::Ascending,
limit,
proof_version,
)?;
let mut events_iter = events.into_iter();
let lower_bound_incl = events_iter.next();
let upper_bound_excl = events_iter.next();
assert_eq!(events_iter.len(), 0);
(lower_bound_incl, upper_bound_excl)
} else {
// Since there is no event at or before `event_version`, we need to
// show that either (1.) there are no events or (2.) events start
// at some later version.
let seq_num = 0;
let limit = 1;
let events = self.get_events_with_proof_by_event_key(
event_key,
seq_num,
Order::Ascending,
limit,
proof_version,
)?;
let mut events_iter = events.into_iter();
let upper_bound_excl = events_iter.next();
assert_eq!(events_iter.len(), 0);
(None, upper_bound_excl)
};
Ok(EventByVersionWithProof::new(
lower_bound_incl,
upper_bound_excl,
))
})
}
fn get_last_version_before_timestamp(
&self,
timestamp: u64,
ledger_version: Version,
) -> Result<Version> {
gauged_api("get_last_version_before_timestamp", || {
self.event_store
.get_last_version_before_timestamp(timestamp, ledger_version)
})
}
fn get_latest_transaction_info_option(&self) -> Result<Option<(Version, TransactionInfo)>> {
gauged_api("get_latest_transaction_info_option", || {
self.ledger_store.get_latest_transaction_info_option()
})
}
fn get_accumulator_root_hash(&self, version: Version) -> Result<HashValue> {
gauged_api("get_accumulator_root_hash", || {
self.ledger_store.get_root_hash(version)
})
}
fn get_accumulator_consistency_proof(
&self,
client_known_version: Option<Version>,
ledger_version: Version,
) -> Result<AccumulatorConsistencyProof> {
gauged_api("get_accumulator_consistency_proof", || {
self.ledger_store
.get_consistency_proof(client_known_version, ledger_version)
})
}
}
impl ModuleResolver for DiemDB {
type Error = anyhow::Error;
fn get_module(&self, module_id: &ModuleId) -> Result<Option<Vec<u8>>> {
let (account_state_with_proof, _) = self.get_account_state_with_proof_by_version(
*module_id.address(),
self.get_latest_version()?,
)?;
if let Some(account_state_blob) = account_state_with_proof {
let account_state = AccountState::try_from(&account_state_blob)?;
Ok(account_state.get(&module_id.access_vector()).cloned())
} else {
Ok(None)
}
}
}
impl ResourceResolver for DiemDB {
type Error = anyhow::Error;
fn get_resource(&self, address: &AccountAddress, tag: &StructTag) -> Result<Option<Vec<u8>>> {
let (account_state_with_proof, _) =
self.get_account_state_with_proof_by_version(*address, self.get_latest_version()?)?;
if let Some(account_state_blob) = account_state_with_proof {
let account_state = AccountState::try_from(&account_state_blob)?;
Ok(account_state.get(&tag.access_vector()).cloned())
} else {
Ok(None)
}
}
}
impl MoveDbReader for DiemDB {}
impl DbWriter for DiemDB {
/// `first_version` is the version of the first transaction in `txns_to_commit`.
/// When `ledger_info_with_sigs` is provided, verify that the transaction accumulator root hash
/// it carries is generated after the `txns_to_commit` are applied.
/// Note that even if `txns_to_commit` is empty, `frist_version` is checked to be
/// `ledger_info_with_sigs.ledger_info.version + 1` if `ledger_info_with_sigs` is not `None`.
fn save_transactions(
&self,
txns_to_commit: &[TransactionToCommit],
first_version: Version,
ledger_info_with_sigs: Option<&LedgerInfoWithSignatures>,
) -> Result<()> {
gauged_api("save_transactions", || {
let num_txns = txns_to_commit.len() as u64;
// ledger_info_with_sigs could be None if we are doing state synchronization. In this case
// txns_to_commit should not be empty. Otherwise it is okay to commit empty blocks.
ensure!(
ledger_info_with_sigs.is_some() || num_txns > 0,
"txns_to_commit is empty while ledger_info_with_sigs is None.",
);
if let Some(x) = ledger_info_with_sigs {
let claimed_last_version = x.ledger_info().version();
ensure!(
claimed_last_version + 1 == first_version + num_txns,
"Transaction batch not applicable: first_version {}, num_txns {}, last_version {}",
first_version,
num_txns,
claimed_last_version,
);
}
// Gather db mutations to `batch`.
let mut cs = ChangeSet::new();
let new_root_hash =
self.save_transactions_impl(txns_to_commit, first_version, &mut cs)?;
// If expected ledger info is provided, verify result root hash and save the ledger info.
if let Some(x) = ledger_info_with_sigs {
let expected_root_hash = x.ledger_info().transaction_accumulator_hash();
ensure!(
new_root_hash == expected_root_hash,
"Root hash calculated doesn't match expected. {:?} vs {:?}",
new_root_hash,
expected_root_hash,
);
self.ledger_store.put_ledger_info(x, &mut cs)?;
}
// Persist.
let (sealed_cs, counters) = self.seal_change_set(first_version, num_txns, cs)?;
{
let _timer = DIEM_STORAGE_OTHER_TIMERS_SECONDS
.with_label_values(&["save_transactions_commit"])
.start_timer();
self.commit(sealed_cs)?;
}
// Once everything is successfully persisted, update the latest in-memory ledger info.
if let Some(x) = ledger_info_with_sigs {
self.ledger_store.set_latest_ledger_info(x.clone());
DIEM_STORAGE_LEDGER_VERSION.set(x.ledger_info().version() as i64);
DIEM_STORAGE_NEXT_BLOCK_EPOCH.set(x.ledger_info().next_block_epoch() as i64);
}
// Only increment counter if commit succeeds and there are at least one transaction written
// to the storage. That's also when we'd inform the pruner thread to work.
if num_txns > 0 {
let last_version = first_version + num_txns - 1;
DIEM_STORAGE_COMMITTED_TXNS.inc_by(num_txns);
DIEM_STORAGE_LATEST_TXN_VERSION.set(last_version as i64);
counters
.expect("Counters should be bumped with transactions being saved.")
.bump_op_counters();
self.wake_pruner(last_version);
}
Ok(())
})
}
}
// Convert requested range and order to a range in ascending order.
fn get_first_seq_num_and_limit(order: Order, cursor: u64, limit: u64) -> Result<(u64, u64)> {
ensure!(limit > 0, "limit should > 0, got {}", limit);
Ok(if order == Order::Ascending {
(cursor, limit)
} else if limit <= cursor {
(cursor - limit + 1, limit)
} else {
(0, cursor + 1)
})
}
pub trait GetRestoreHandler {
/// Gets an instance of `RestoreHandler` for data restore purpose.
fn get_restore_handler(&self) -> RestoreHandler;
}
impl GetRestoreHandler for Arc<DiemDB> {
fn get_restore_handler(&self) -> RestoreHandler {
RestoreHandler::new(
Arc::clone(&self.db),
Arc::clone(self),
Arc::clone(&self.ledger_store),
Arc::clone(&self.transaction_store),
Arc::clone(&self.state_store),
Arc::clone(&self.event_store),
)
}
}
fn gauged_api<T, F>(api_name: &'static str, api_impl: F) -> Result<T>
where
F: FnOnce() -> Result<T>,
{
let timer = Instant::now();
let res = api_impl();
let res_type = match &res {
Ok(_) => "Ok",
Err(e) => {
warn!(
api_name = api_name,
error = ?e,
"DiemDB API returned error."
);
"Err"
}
};
DIEM_STORAGE_API_LATENCY_SECONDS
.with_label_values(&[api_name, res_type])
.observe(timer.elapsed().as_secs_f64());
res
}
| 35.37399 | 127 | 0.574224 |
ef8dafee5f8ab49604e7d2675d3eb28794ba13d0 | 19,233 | use dox::{mem, Option};
pub type c_char = i8;
pub type wchar_t = i32;
pub type off_t = i64;
pub type useconds_t = u32;
pub type blkcnt_t = i64;
pub type socklen_t = u32;
pub type sa_family_t = u8;
pub type pthread_t = ::uintptr_t;
pub type nfds_t = ::c_uint;
s! {
pub struct sockaddr {
pub sa_len: u8,
pub sa_family: sa_family_t,
pub sa_data: [::c_char; 14],
}
pub struct sockaddr_in6 {
pub sin6_len: u8,
pub sin6_family: sa_family_t,
pub sin6_port: ::in_port_t,
pub sin6_flowinfo: u32,
pub sin6_addr: ::in6_addr,
pub sin6_scope_id: u32,
}
pub struct sockaddr_un {
pub sun_len: u8,
pub sun_family: sa_family_t,
pub sun_path: [c_char; 104]
}
pub struct passwd {
pub pw_name: *mut ::c_char,
pub pw_passwd: *mut ::c_char,
pub pw_uid: ::uid_t,
pub pw_gid: ::gid_t,
pub pw_change: ::time_t,
pub pw_class: *mut ::c_char,
pub pw_gecos: *mut ::c_char,
pub pw_dir: *mut ::c_char,
pub pw_shell: *mut ::c_char,
pub pw_expire: ::time_t,
#[cfg(not(any(target_os = "macos",
target_os = "ios",
target_os = "netbsd",
target_os = "openbsd")))]
pub pw_fields: ::c_int,
}
pub struct ifaddrs {
pub ifa_next: *mut ifaddrs,
pub ifa_name: *mut ::c_char,
pub ifa_flags: ::c_uint,
pub ifa_addr: *mut ::sockaddr,
pub ifa_netmask: *mut ::sockaddr,
pub ifa_dstaddr: *mut ::sockaddr,
pub ifa_data: *mut ::c_void
}
pub struct fd_set {
#[cfg(all(target_pointer_width = "64",
any(target_os = "freebsd", target_os = "dragonfly")))]
fds_bits: [i64; FD_SETSIZE / 64],
#[cfg(not(all(target_pointer_width = "64",
any(target_os = "freebsd", target_os = "dragonfly"))))]
fds_bits: [i32; FD_SETSIZE / 32],
}
pub struct tm {
pub tm_sec: ::c_int,
pub tm_min: ::c_int,
pub tm_hour: ::c_int,
pub tm_mday: ::c_int,
pub tm_mon: ::c_int,
pub tm_year: ::c_int,
pub tm_wday: ::c_int,
pub tm_yday: ::c_int,
pub tm_isdst: ::c_int,
pub tm_gmtoff: ::c_long,
pub tm_zone: *mut ::c_char,
}
pub struct utsname {
#[cfg(not(target_os = "dragonfly"))]
pub sysname: [::c_char; 256],
#[cfg(target_os = "dragonfly")]
pub sysname: [::c_char; 32],
#[cfg(not(target_os = "dragonfly"))]
pub nodename: [::c_char; 256],
#[cfg(target_os = "dragonfly")]
pub nodename: [::c_char; 32],
#[cfg(not(target_os = "dragonfly"))]
pub release: [::c_char; 256],
#[cfg(target_os = "dragonfly")]
pub release: [::c_char; 32],
#[cfg(not(target_os = "dragonfly"))]
pub version: [::c_char; 256],
#[cfg(target_os = "dragonfly")]
pub version: [::c_char; 32],
#[cfg(not(target_os = "dragonfly"))]
pub machine: [::c_char; 256],
#[cfg(target_os = "dragonfly")]
pub machine: [::c_char; 32],
}
pub struct msghdr {
pub msg_name: *mut ::c_void,
pub msg_namelen: ::socklen_t,
pub msg_iov: *mut ::iovec,
pub msg_iovlen: ::c_int,
pub msg_control: *mut ::c_void,
pub msg_controllen: ::socklen_t,
pub msg_flags: ::c_int,
}
pub struct cmsghdr {
pub cmsg_len: ::socklen_t,
pub cmsg_level: ::c_int,
pub cmsg_type: ::c_int,
}
pub struct fsid_t {
__fsid_val: [::int32_t; 2],
}
pub struct if_nameindex {
pub if_index: ::c_uint,
pub if_name: *mut ::c_char,
}
}
pub const LC_ALL: ::c_int = 0;
pub const LC_COLLATE: ::c_int = 1;
pub const LC_CTYPE: ::c_int = 2;
pub const LC_MONETARY: ::c_int = 3;
pub const LC_NUMERIC: ::c_int = 4;
pub const LC_TIME: ::c_int = 5;
pub const LC_MESSAGES: ::c_int = 6;
pub const FIOCLEX: ::c_ulong = 0x20006601;
pub const FIONBIO: ::c_ulong = 0x8004667e;
pub const PATH_MAX: ::c_int = 1024;
pub const SA_ONSTACK: ::c_int = 0x0001;
pub const SA_SIGINFO: ::c_int = 0x0040;
pub const SA_RESTART: ::c_int = 0x0002;
pub const SA_RESETHAND: ::c_int = 0x0004;
pub const SA_NOCLDSTOP: ::c_int = 0x0008;
pub const SA_NODEFER: ::c_int = 0x0010;
pub const SA_NOCLDWAIT: ::c_int = 0x0020;
pub const SS_ONSTACK: ::c_int = 1;
pub const SS_DISABLE: ::c_int = 4;
pub const SIGCHLD: ::c_int = 20;
pub const SIGBUS: ::c_int = 10;
pub const SIGUSR1: ::c_int = 30;
pub const SIGUSR2: ::c_int = 31;
pub const SIGCONT: ::c_int = 19;
pub const SIGSTOP: ::c_int = 17;
pub const SIGTSTP: ::c_int = 18;
pub const SIGURG: ::c_int = 16;
pub const SIGIO: ::c_int = 23;
pub const SIGSYS: ::c_int = 12;
pub const SIGTTIN: ::c_int = 21;
pub const SIGTTOU: ::c_int = 22;
pub const SIGXCPU: ::c_int = 24;
pub const SIGXFSZ: ::c_int = 25;
pub const SIGVTALRM: ::c_int = 26;
pub const SIGPROF: ::c_int = 27;
pub const SIGWINCH: ::c_int = 28;
pub const SIGINFO: ::c_int = 29;
pub const SIG_SETMASK: ::c_int = 3;
pub const SIG_BLOCK: ::c_int = 0x1;
pub const SIG_UNBLOCK: ::c_int = 0x2;
pub const IP_MULTICAST_IF: ::c_int = 9;
pub const IP_MULTICAST_TTL: ::c_int = 10;
pub const IP_MULTICAST_LOOP: ::c_int = 11;
pub const IPV6_MULTICAST_LOOP: ::c_int = 11;
pub const IPV6_V6ONLY: ::c_int = 27;
pub const ST_RDONLY: ::c_ulong = 1;
pub const SCM_RIGHTS: ::c_int = 0x01;
pub const NCCS: usize = 20;
pub const O_ACCMODE: ::c_int = 0x3;
pub const O_RDONLY: ::c_int = 0;
pub const O_WRONLY: ::c_int = 1;
pub const O_RDWR: ::c_int = 2;
pub const O_APPEND: ::c_int = 8;
pub const O_CREAT: ::c_int = 512;
pub const O_TRUNC: ::c_int = 1024;
pub const O_EXCL: ::c_int = 2048;
pub const O_ASYNC: ::c_int = 0x40;
pub const O_SYNC: ::c_int = 0x80;
pub const O_NONBLOCK: ::c_int = 0x4;
pub const O_NOFOLLOW: ::c_int = 0x100;
pub const O_SHLOCK: ::c_int = 0x10;
pub const O_EXLOCK: ::c_int = 0x20;
pub const O_FSYNC: ::c_int = O_SYNC;
pub const O_NDELAY: ::c_int = O_NONBLOCK;
pub const F_GETOWN: ::c_int = 5;
pub const F_SETOWN: ::c_int = 6;
pub const MNT_FORCE: ::c_int = 0x80000;
pub const Q_SYNC: ::c_int = 0x600;
pub const Q_QUOTAON: ::c_int = 0x100;
pub const Q_QUOTAOFF: ::c_int = 0x200;
pub const TCIOFF: ::c_int = 3;
pub const TCION: ::c_int = 4;
pub const TCOOFF: ::c_int = 1;
pub const TCOON: ::c_int = 2;
pub const TCIFLUSH: ::c_int = 1;
pub const TCOFLUSH: ::c_int = 2;
pub const TCIOFLUSH: ::c_int = 3;
pub const TCSANOW: ::c_int = 0;
pub const TCSADRAIN: ::c_int = 1;
pub const TCSAFLUSH: ::c_int = 2;
pub const VEOF: usize = 0;
pub const VEOL: usize = 1;
pub const VEOL2: usize = 2;
pub const VERASE: usize = 3;
pub const VWERASE: usize = 4;
pub const VKILL: usize = 5;
pub const VREPRINT: usize = 6;
pub const VINTR: usize = 8;
pub const VQUIT: usize = 9;
pub const VSUSP: usize = 10;
pub const VDSUSP: usize = 11;
pub const VSTART: usize = 12;
pub const VSTOP: usize = 13;
pub const VLNEXT: usize = 14;
pub const VDISCARD: usize = 15;
pub const VMIN: usize = 16;
pub const VTIME: usize = 17;
pub const VSTATUS: usize = 18;
pub const _POSIX_VDISABLE: ::cc_t = 0xff;
pub const IGNBRK: ::tcflag_t = 0x00000001;
pub const BRKINT: ::tcflag_t = 0x00000002;
pub const IGNPAR: ::tcflag_t = 0x00000004;
pub const PARMRK: ::tcflag_t = 0x00000008;
pub const INPCK: ::tcflag_t = 0x00000010;
pub const ISTRIP: ::tcflag_t = 0x00000020;
pub const INLCR: ::tcflag_t = 0x00000040;
pub const IGNCR: ::tcflag_t = 0x00000080;
pub const ICRNL: ::tcflag_t = 0x00000100;
pub const IXON: ::tcflag_t = 0x00000200;
pub const IXOFF: ::tcflag_t = 0x00000400;
pub const IXANY: ::tcflag_t = 0x00000800;
pub const IMAXBEL: ::tcflag_t = 0x00002000;
pub const OPOST: ::tcflag_t = 0x1;
pub const ONLCR: ::tcflag_t = 0x2;
pub const OXTABS: ::tcflag_t = 0x4;
pub const ONOEOT: ::tcflag_t = 0x8;
pub const CIGNORE: ::tcflag_t = 0x00000001;
pub const CSIZE: ::tcflag_t = 0x00000300;
pub const CS5: ::tcflag_t = 0x00000000;
pub const CS6: ::tcflag_t = 0x00000100;
pub const CS7: ::tcflag_t = 0x00000200;
pub const CS8: ::tcflag_t = 0x00000300;
pub const CSTOPB: ::tcflag_t = 0x00000400;
pub const CREAD: ::tcflag_t = 0x00000800;
pub const PARENB: ::tcflag_t = 0x00001000;
pub const PARODD: ::tcflag_t = 0x00002000;
pub const HUPCL: ::tcflag_t = 0x00004000;
pub const CLOCAL: ::tcflag_t = 0x00008000;
pub const ECHOKE: ::tcflag_t = 0x00000001;
pub const ECHOE: ::tcflag_t = 0x00000002;
pub const ECHOK: ::tcflag_t = 0x00000004;
pub const ECHO: ::tcflag_t = 0x00000008;
pub const ECHONL: ::tcflag_t = 0x00000010;
pub const ECHOPRT: ::tcflag_t = 0x00000020;
pub const ECHOCTL: ::tcflag_t = 0x00000040;
pub const ISIG: ::tcflag_t = 0x00000080;
pub const ICANON: ::tcflag_t = 0x00000100;
pub const ALTWERASE: ::tcflag_t = 0x00000200;
pub const IEXTEN: ::tcflag_t = 0x00000400;
pub const EXTPROC: ::tcflag_t = 0x00000800;
pub const TOSTOP: ::tcflag_t = 0x00400000;
pub const FLUSHO: ::tcflag_t = 0x00800000;
pub const NOKERNINFO: ::tcflag_t = 0x02000000;
pub const PENDIN: ::tcflag_t = 0x20000000;
pub const NOFLSH: ::tcflag_t = 0x80000000;
pub const MDMBUF: ::tcflag_t = 0x00100000;
pub const WNOHANG: ::c_int = 0x00000001;
pub const WUNTRACED: ::c_int = 0x00000002;
pub const RTLD_NOW: ::c_int = 0x2;
pub const RTLD_NEXT: *mut ::c_void = -1isize as *mut ::c_void;
pub const RTLD_DEFAULT: *mut ::c_void = -2isize as *mut ::c_void;
pub const RTLD_SELF: *mut ::c_void = -3isize as *mut ::c_void;
pub const LOG_CRON: ::c_int = 9 << 3;
pub const LOG_AUTHPRIV: ::c_int = 10 << 3;
pub const LOG_FTP: ::c_int = 11 << 3;
pub const LOG_PERROR: ::c_int = 0x20;
pub const TCP_MAXSEG: ::c_int = 2;
pub const PIPE_BUF: usize = 512;
pub const POLLRDNORM: ::c_short = 0x040;
pub const POLLWRNORM: ::c_short = 0x004;
pub const POLLRDBAND: ::c_short = 0x080;
pub const POLLWRBAND: ::c_short = 0x100;
f! {
pub fn FD_CLR(fd: ::c_int, set: *mut fd_set) -> () {
let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8;
let fd = fd as usize;
(*set).fds_bits[fd / bits] &= !(1 << (fd % bits));
return
}
pub fn FD_ISSET(fd: ::c_int, set: *mut fd_set) -> bool {
let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8;
let fd = fd as usize;
return ((*set).fds_bits[fd / bits] & (1 << (fd % bits))) != 0
}
pub fn FD_SET(fd: ::c_int, set: *mut fd_set) -> () {
let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8;
let fd = fd as usize;
(*set).fds_bits[fd / bits] |= 1 << (fd % bits);
return
}
pub fn FD_ZERO(set: *mut fd_set) -> () {
for slot in (*set).fds_bits.iter_mut() {
*slot = 0;
}
}
pub fn WTERMSIG(status: ::c_int) -> ::c_int {
status & 0o177
}
pub fn WIFEXITED(status: ::c_int) -> bool {
(status & 0o177) == 0
}
pub fn WEXITSTATUS(status: ::c_int) -> ::c_int {
status >> 8
}
pub fn WCOREDUMP(status: ::c_int) -> bool {
(status & 0o200) != 0
}
pub fn QCMD(cmd: ::c_int, type_: ::c_int) -> ::c_int {
(cmd << 8) | (type_ & 0x00ff)
}
}
extern {
pub fn getifaddrs(ifap: *mut *mut ::ifaddrs) -> ::c_int;
pub fn freeifaddrs(ifa: *mut ::ifaddrs);
pub fn setgroups(ngroups: ::c_int,
ptr: *const ::gid_t) -> ::c_int;
pub fn ioctl(fd: ::c_int, request: ::c_ulong, ...) -> ::c_int;
pub fn kqueue() -> ::c_int;
pub fn unmount(target: *const ::c_char, arg: ::c_int) -> ::c_int;
pub fn syscall(num: ::c_int, ...) -> ::c_int;
#[cfg_attr(target_os = "netbsd", link_name = "__getpwent50")]
pub fn getpwent() -> *mut passwd;
pub fn setpwent();
pub fn endpwent();
pub fn getprogname() -> *const ::c_char;
pub fn setprogname(name: *const ::c_char);
pub fn getloadavg(loadavg: *mut ::c_double, nelem: ::c_int) -> ::c_int;
pub fn if_nameindex() -> *mut if_nameindex;
pub fn if_freenameindex(ptr: *mut if_nameindex);
pub fn getpeereid(socket: ::c_int,
euid: *mut ::uid_t,
egid: *mut ::gid_t) -> ::c_int;
#[cfg_attr(target_os = "macos", link_name = "glob$INODE64")]
#[cfg_attr(target_os = "netbsd", link_name = "__glob30")]
pub fn glob(pattern: *const ::c_char,
flags: ::c_int,
errfunc: Option<extern fn(epath: *const ::c_char,
errno: ::c_int) -> ::c_int>,
pglob: *mut ::glob_t) -> ::c_int;
#[cfg_attr(target_os = "netbsd", link_name = "__globfree30")]
pub fn globfree(pglob: *mut ::glob_t);
pub fn posix_madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int)
-> ::c_int;
pub fn shm_unlink(name: *const ::c_char) -> ::c_int;
#[cfg_attr(all(target_os = "macos", target_arch = "x86_64"),
link_name = "seekdir$INODE64")]
#[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "seekdir$INODE64$UNIX2003")]
pub fn seekdir(dirp: *mut ::DIR, loc: ::c_long);
#[cfg_attr(all(target_os = "macos", target_arch = "x86_64"),
link_name = "telldir$INODE64")]
#[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "telldir$INODE64$UNIX2003")]
pub fn telldir(dirp: *mut ::DIR) -> ::c_long;
pub fn madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int)
-> ::c_int;
#[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "msync$UNIX2003")]
#[cfg_attr(target_os = "netbsd", link_name = "__msync13")]
pub fn msync(addr: *mut ::c_void, len: ::size_t, flags: ::c_int) -> ::c_int;
#[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "recvfrom$UNIX2003")]
pub fn recvfrom(socket: ::c_int, buf: *mut ::c_void, len: ::size_t,
flags: ::c_int, addr: *mut ::sockaddr,
addrlen: *mut ::socklen_t) -> ::ssize_t;
pub fn mkstemps(template: *mut ::c_char, suffixlen: ::c_int) -> ::c_int;
pub fn futimes(fd: ::c_int, times: *const ::timeval) -> ::c_int;
pub fn nl_langinfo(item: ::nl_item) -> *mut ::c_char;
#[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "bind$UNIX2003")]
pub fn bind(socket: ::c_int, address: *const ::sockaddr,
address_len: ::socklen_t) -> ::c_int;
#[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "writev$UNIX2003")]
pub fn writev(fd: ::c_int,
iov: *const ::iovec,
iovcnt: ::c_int) -> ::ssize_t;
#[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "readv$UNIX2003")]
pub fn readv(fd: ::c_int,
iov: *const ::iovec,
iovcnt: ::c_int) -> ::ssize_t;
#[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "sendmsg$UNIX2003")]
pub fn sendmsg(fd: ::c_int,
msg: *const ::msghdr,
flags: ::c_int) -> ::ssize_t;
#[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "recvmsg$UNIX2003")]
pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int)
-> ::ssize_t;
pub fn sync();
#[cfg_attr(target_os = "solaris", link_name = "__posix_getgrgid_r")]
pub fn getgrgid_r(uid: ::uid_t,
grp: *mut ::group,
buf: *mut ::c_char,
buflen: ::size_t,
result: *mut *mut ::group) -> ::c_int;
#[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "sigaltstack$UNIX2003")]
#[cfg_attr(target_os = "netbsd", link_name = "__sigaltstack14")]
pub fn sigaltstack(ss: *const stack_t,
oss: *mut stack_t) -> ::c_int;
pub fn sem_close(sem: *mut sem_t) -> ::c_int;
pub fn getdtablesize() -> ::c_int;
#[cfg_attr(target_os = "solaris", link_name = "__posix_getgrnam_r")]
pub fn getgrnam_r(name: *const ::c_char,
grp: *mut ::group,
buf: *mut ::c_char,
buflen: ::size_t,
result: *mut *mut ::group) -> ::c_int;
#[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "pthread_sigmask$UNIX2003")]
pub fn pthread_sigmask(how: ::c_int, set: *const sigset_t,
oldset: *mut sigset_t) -> ::c_int;
pub fn sem_open(name: *const ::c_char, oflag: ::c_int, ...) -> *mut sem_t;
pub fn getgrnam(name: *const ::c_char) -> *mut ::group;
pub fn pthread_kill(thread: ::pthread_t, sig: ::c_int) -> ::c_int;
pub fn sem_unlink(name: *const ::c_char) -> ::c_int;
pub fn daemon(nochdir: ::c_int, noclose: ::c_int) -> ::c_int;
#[cfg_attr(target_os = "netbsd", link_name = "__getpwnam_r50")]
#[cfg_attr(target_os = "solaris", link_name = "__posix_getpwnam_r")]
pub fn getpwnam_r(name: *const ::c_char,
pwd: *mut passwd,
buf: *mut ::c_char,
buflen: ::size_t,
result: *mut *mut passwd) -> ::c_int;
#[cfg_attr(target_os = "netbsd", link_name = "__getpwuid_r50")]
#[cfg_attr(target_os = "solaris", link_name = "__posix_getpwuid_r")]
pub fn getpwuid_r(uid: ::uid_t,
pwd: *mut passwd,
buf: *mut ::c_char,
buflen: ::size_t,
result: *mut *mut passwd) -> ::c_int;
#[cfg_attr(all(target_os = "macos", target_arch ="x86"),
link_name = "sigwait$UNIX2003")]
#[cfg_attr(target_os = "solaris", link_name = "__posix_sigwait")]
pub fn sigwait(set: *const sigset_t,
sig: *mut ::c_int) -> ::c_int;
pub fn pthread_atfork(prepare: Option<unsafe extern fn()>,
parent: Option<unsafe extern fn()>,
child: Option<unsafe extern fn()>) -> ::c_int;
pub fn getgrgid(gid: ::gid_t) -> *mut ::group;
#[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "popen$UNIX2003")]
pub fn popen(command: *const c_char,
mode: *const c_char) -> *mut ::FILE;
pub fn faccessat(dirfd: ::c_int, pathname: *const ::c_char,
mode: ::c_int, flags: ::c_int) -> ::c_int;
pub fn pthread_create(native: *mut ::pthread_t,
attr: *const ::pthread_attr_t,
f: extern fn(*mut ::c_void) -> *mut ::c_void,
value: *mut ::c_void) -> ::c_int;
}
cfg_if! {
if #[cfg(any(target_os = "macos", target_os = "ios"))] {
mod apple;
pub use self::apple::*;
} else if #[cfg(any(target_os = "openbsd", target_os = "netbsd",
target_os = "bitrig"))] {
mod netbsdlike;
pub use self::netbsdlike::*;
} else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] {
mod freebsdlike;
pub use self::freebsdlike::*;
} else {
// Unknown target_os
}
}
| 35.616667 | 80 | 0.584516 |
6a3f756abfd041b289588eeaa47da581e82da878 | 2,606 | #![allow(dead_code)]
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
use inflector::Inflector;
use rapier_testbed3d::{Testbed, TestbedApp};
use std::cmp::Ordering;
mod balls3;
mod boxes3;
mod capsules3;
mod ccd3;
mod compound3;
mod convex_polyhedron3;
mod heightfield3;
mod joint_ball3;
mod joint_fixed3;
mod joint_prismatic3;
mod joint_revolute3;
mod keva3;
mod pyramid3;
mod stacks3;
mod trimesh3;
enum Command {
Run(String),
List,
RunAll,
}
fn parse_command_line() -> Command {
let mut args = std::env::args();
while let Some(arg) = args.next() {
if &arg[..] == "--example" {
return Command::Run(args.next().unwrap_or(String::new()));
} else if &arg[..] == "--list" {
return Command::List;
}
}
Command::RunAll
}
pub fn main() {
let command = parse_command_line();
let mut builders: Vec<(_, fn(&mut Testbed))> = vec![
("Balls", balls3::init_world),
("Boxes", boxes3::init_world),
("Capsules", capsules3::init_world),
("CCD", ccd3::init_world),
("Compound", compound3::init_world),
("Convex polyhedron", convex_polyhedron3::init_world),
("Heightfield", heightfield3::init_world),
("Stacks", stacks3::init_world),
("Pyramid", pyramid3::init_world),
("Trimesh", trimesh3::init_world),
("ImpulseJoint ball", joint_ball3::init_world),
("ImpulseJoint fixed", joint_fixed3::init_world),
("ImpulseJoint revolute", joint_revolute3::init_world),
("ImpulseJoint prismatic", joint_prismatic3::init_world),
("Keva tower", keva3::init_world),
];
// Lexicographic sort, with stress tests moved at the end of the list.
builders.sort_by(|a, b| match (a.0.starts_with("("), b.0.starts_with("(")) {
(true, true) | (false, false) => a.0.cmp(b.0),
(true, false) => Ordering::Greater,
(false, true) => Ordering::Less,
});
match command {
Command::Run(demo) => {
if let Some(i) = builders
.iter()
.position(|builder| builder.0.to_camel_case().as_str() == demo.as_str())
{
TestbedApp::from_builders(0, vec![builders[i]]).run()
} else {
eprintln!("Invalid example to run provided: '{}'", demo);
}
}
Command::RunAll => TestbedApp::from_builders(0, builders).run(),
Command::List => {
for builder in &builders {
println!("{}", builder.0.to_camel_case())
}
}
}
}
| 27.723404 | 88 | 0.57713 |
e50ac0b09227ba70ea8c6f87c356a44898c1ea39 | 498 | extern crate powerline;
use powerline::{modules::*, theme::SimpleTheme};
fn main() -> powerline::R<()> {
let mut prompt = powerline::Powerline::new();
prompt.add_module(User::<SimpleTheme>::new())?;
prompt.add_module(Host::<SimpleTheme>::new())?;
prompt.add_module(Cwd::<SimpleTheme>::new(45, 4, false))?;
prompt.add_module(Git::<SimpleTheme>::new())?;
prompt.add_module(ReadOnly::<SimpleTheme>::new())?;
prompt.add_module(Cmd::<SimpleTheme>::new())?;
println!("{}", prompt);
Ok(())
}
| 27.666667 | 59 | 0.666667 |
ebcff041a6444cc20535e61da46a7f70057d2169 | 45,431 | use crate::core_arch::arm_shared::neon::*;
use crate::core_arch::simd::{f32x4, i32x4, u32x4};
use crate::core_arch::simd_llvm::*;
use crate::mem::{align_of, transmute};
#[cfg(test)]
use stdarch_test::assert_instr;
#[allow(non_camel_case_types)]
pub(crate) type p8 = u8;
#[allow(non_camel_case_types)]
pub(crate) type p16 = u16;
#[allow(improper_ctypes)]
extern "unadjusted" {
#[link_name = "llvm.arm.neon.vbsl.v8i8"]
fn vbsl_s8_(a: int8x8_t, b: int8x8_t, c: int8x8_t) -> int8x8_t;
#[link_name = "llvm.arm.neon.vbsl.v16i8"]
fn vbslq_s8_(a: int8x16_t, b: int8x16_t, c: int8x16_t) -> int8x16_t;
#[link_name = "llvm.arm.neon.vpadals.v4i16.v8i8"]
pub(crate) fn vpadal_s8_(a: int16x4_t, b: int8x8_t) -> int16x4_t;
#[link_name = "llvm.arm.neon.vpadals.v2i32.v4i16"]
pub(crate) fn vpadal_s16_(a: int32x2_t, b: int16x4_t) -> int32x2_t;
#[link_name = "llvm.arm.neon.vpadals.v1i64.v2i32"]
pub(crate) fn vpadal_s32_(a: int64x1_t, b: int32x2_t) -> int64x1_t;
#[link_name = "llvm.arm.neon.vpadals.v8i16.v16i8"]
pub(crate) fn vpadalq_s8_(a: int16x8_t, b: int8x16_t) -> int16x8_t;
#[link_name = "llvm.arm.neon.vpadals.v4i32.v8i16"]
pub(crate) fn vpadalq_s16_(a: int32x4_t, b: int16x8_t) -> int32x4_t;
#[link_name = "llvm.arm.neon.vpadals.v2i64.v4i32"]
pub(crate) fn vpadalq_s32_(a: int64x2_t, b: int32x4_t) -> int64x2_t;
#[link_name = "llvm.arm.neon.vpadalu.v4i16.v8i8"]
pub(crate) fn vpadal_u8_(a: uint16x4_t, b: uint8x8_t) -> uint16x4_t;
#[link_name = "llvm.arm.neon.vpadalu.v2i32.v4i16"]
pub(crate) fn vpadal_u16_(a: uint32x2_t, b: uint16x4_t) -> uint32x2_t;
#[link_name = "llvm.arm.neon.vpadalu.v1i64.v2i32"]
pub(crate) fn vpadal_u32_(a: uint64x1_t, b: uint32x2_t) -> uint64x1_t;
#[link_name = "llvm.arm.neon.vpadalu.v8i16.v16i8"]
pub(crate) fn vpadalq_u8_(a: uint16x8_t, b: uint8x16_t) -> uint16x8_t;
#[link_name = "llvm.arm.neon.vpadalu.v4i32.v8i16"]
pub(crate) fn vpadalq_u16_(a: uint32x4_t, b: uint16x8_t) -> uint32x4_t;
#[link_name = "llvm.arm.neon.vpadalu.v2i64.v4i32"]
pub(crate) fn vpadalq_u32_(a: uint64x2_t, b: uint32x4_t) -> uint64x2_t;
#[link_name = "llvm.arm.neon.vtbl1"]
fn vtbl1(a: int8x8_t, b: int8x8_t) -> int8x8_t;
#[link_name = "llvm.arm.neon.vtbl2"]
fn vtbl2(a: int8x8_t, b: int8x8_t, b: int8x8_t) -> int8x8_t;
#[link_name = "llvm.arm.neon.vtbl3"]
fn vtbl3(a: int8x8_t, b: int8x8_t, b: int8x8_t, c: int8x8_t) -> int8x8_t;
#[link_name = "llvm.arm.neon.vtbl4"]
fn vtbl4(a: int8x8_t, b: int8x8_t, b: int8x8_t, c: int8x8_t, d: int8x8_t) -> int8x8_t;
#[link_name = "llvm.arm.neon.vtbx1"]
fn vtbx1(a: int8x8_t, b: int8x8_t, b: int8x8_t) -> int8x8_t;
#[link_name = "llvm.arm.neon.vtbx2"]
fn vtbx2(a: int8x8_t, b: int8x8_t, b: int8x8_t, c: int8x8_t) -> int8x8_t;
#[link_name = "llvm.arm.neon.vtbx3"]
fn vtbx3(a: int8x8_t, b: int8x8_t, b: int8x8_t, c: int8x8_t, d: int8x8_t) -> int8x8_t;
#[link_name = "llvm.arm.neon.vtbx4"]
fn vtbx4(
a: int8x8_t,
b: int8x8_t,
b: int8x8_t,
c: int8x8_t,
d: int8x8_t,
e: int8x8_t,
) -> int8x8_t;
#[link_name = "llvm.arm.neon.vshiftins.v8i8"]
fn vshiftins_v8i8(a: int8x8_t, b: int8x8_t, shift: int8x8_t) -> int8x8_t;
#[link_name = "llvm.arm.neon.vshiftins.v16i8"]
fn vshiftins_v16i8(a: int8x16_t, b: int8x16_t, shift: int8x16_t) -> int8x16_t;
#[link_name = "llvm.arm.neon.vshiftins.v4i16"]
fn vshiftins_v4i16(a: int16x4_t, b: int16x4_t, shift: int16x4_t) -> int16x4_t;
#[link_name = "llvm.arm.neon.vshiftins.v8i16"]
fn vshiftins_v8i16(a: int16x8_t, b: int16x8_t, shift: int16x8_t) -> int16x8_t;
#[link_name = "llvm.arm.neon.vshiftins.v2i32"]
fn vshiftins_v2i32(a: int32x2_t, b: int32x2_t, shift: int32x2_t) -> int32x2_t;
#[link_name = "llvm.arm.neon.vshiftins.v4i32"]
fn vshiftins_v4i32(a: int32x4_t, b: int32x4_t, shift: int32x4_t) -> int32x4_t;
#[link_name = "llvm.arm.neon.vshiftins.v1i64"]
fn vshiftins_v1i64(a: int64x1_t, b: int64x1_t, shift: int64x1_t) -> int64x1_t;
#[link_name = "llvm.arm.neon.vshiftins.v2i64"]
fn vshiftins_v2i64(a: int64x2_t, b: int64x2_t, shift: int64x2_t) -> int64x2_t;
#[link_name = "llvm.arm.neon.vld1.v8i8.p0i8"]
fn vld1_v8i8(addr: *const i8, align: i32) -> int8x8_t;
#[link_name = "llvm.arm.neon.vld1.v16i8.p0i8"]
fn vld1q_v16i8(addr: *const i8, align: i32) -> int8x16_t;
#[link_name = "llvm.arm.neon.vld1.v4i16.p0i8"]
fn vld1_v4i16(addr: *const i8, align: i32) -> int16x4_t;
#[link_name = "llvm.arm.neon.vld1.v8i16.p0i8"]
fn vld1q_v8i16(addr: *const i8, align: i32) -> int16x8_t;
#[link_name = "llvm.arm.neon.vld1.v2i32.p0i8"]
fn vld1_v2i32(addr: *const i8, align: i32) -> int32x2_t;
#[link_name = "llvm.arm.neon.vld1.v4i32.p0i8"]
fn vld1q_v4i32(addr: *const i8, align: i32) -> int32x4_t;
#[link_name = "llvm.arm.neon.vld1.v1i64.p0i8"]
fn vld1_v1i64(addr: *const i8, align: i32) -> int64x1_t;
#[link_name = "llvm.arm.neon.vld1.v2i64.p0i8"]
fn vld1q_v2i64(addr: *const i8, align: i32) -> int64x2_t;
#[link_name = "llvm.arm.neon.vld1.v2f32.p0i8"]
fn vld1_v2f32(addr: *const i8, align: i32) -> float32x2_t;
#[link_name = "llvm.arm.neon.vld1.v4f32.p0i8"]
fn vld1q_v4f32(addr: *const i8, align: i32) -> float32x4_t;
#[link_name = "llvm.arm.neon.vst1.p0i8.v8i8"]
fn vst1_v8i8(addr: *const i8, val: int8x8_t, align: i32);
#[link_name = "llvm.arm.neon.vst1.p0i8.v16i8"]
fn vst1q_v16i8(addr: *const i8, val: int8x16_t, align: i32);
#[link_name = "llvm.arm.neon.vst1.p0i8.v4i16"]
fn vst1_v4i16(addr: *const i8, val: int16x4_t, align: i32);
#[link_name = "llvm.arm.neon.vst1.p0i8.v8i16"]
fn vst1q_v8i16(addr: *const i8, val: int16x8_t, align: i32);
#[link_name = "llvm.arm.neon.vst1.p0i8.v2i32"]
fn vst1_v2i32(addr: *const i8, val: int32x2_t, align: i32);
#[link_name = "llvm.arm.neon.vst1.p0i8.v4i32"]
fn vst1q_v4i32(addr: *const i8, val: int32x4_t, align: i32);
#[link_name = "llvm.arm.neon.vst1.p0i8.v1i64"]
fn vst1_v1i64(addr: *const i8, val: int64x1_t, align: i32);
#[link_name = "llvm.arm.neon.vst1.p0i8.v2i64"]
fn vst1q_v2i64(addr: *const i8, val: int64x2_t, align: i32);
#[link_name = "llvm.arm.neon.vst1.p0i8.v2f32"]
fn vst1_v2f32(addr: *const i8, val: float32x2_t, align: i32);
#[link_name = "llvm.arm.neon.vst1.p0i8.v4f32"]
fn vst1q_v4f32(addr: *const i8, val: float32x4_t, align: i32);
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vld1.8"))]
pub unsafe fn vld1_s8(ptr: *const i8) -> int8x8_t {
vld1_v8i8(ptr as *const i8, align_of::<i8>() as i32)
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vld1.8"))]
pub unsafe fn vld1q_s8(ptr: *const i8) -> int8x16_t {
vld1q_v16i8(ptr as *const i8, align_of::<i8>() as i32)
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vld1.16"))]
pub unsafe fn vld1_s16(ptr: *const i16) -> int16x4_t {
vld1_v4i16(ptr as *const i8, align_of::<i16>() as i32)
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vld1.16"))]
pub unsafe fn vld1q_s16(ptr: *const i16) -> int16x8_t {
vld1q_v8i16(ptr as *const i8, align_of::<i16>() as i32)
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vldr))]
pub unsafe fn vld1_s32(ptr: *const i32) -> int32x2_t {
vld1_v2i32(ptr as *const i8, align_of::<i32>() as i32)
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vld1.32"))]
pub unsafe fn vld1q_s32(ptr: *const i32) -> int32x4_t {
vld1q_v4i32(ptr as *const i8, align_of::<i32>() as i32)
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vldr))]
pub unsafe fn vld1_s64(ptr: *const i64) -> int64x1_t {
vld1_v1i64(ptr as *const i8, align_of::<i64>() as i32)
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vld1.64"))]
pub unsafe fn vld1q_s64(ptr: *const i64) -> int64x2_t {
vld1q_v2i64(ptr as *const i8, align_of::<i64>() as i32)
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vld1.8"))]
pub unsafe fn vld1_u8(ptr: *const u8) -> uint8x8_t {
transmute(vld1_v8i8(ptr as *const i8, align_of::<u8>() as i32))
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vld1.8"))]
pub unsafe fn vld1q_u8(ptr: *const u8) -> uint8x16_t {
transmute(vld1q_v16i8(ptr as *const i8, align_of::<u8>() as i32))
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vld1.16"))]
pub unsafe fn vld1_u16(ptr: *const u16) -> uint16x4_t {
transmute(vld1_v4i16(ptr as *const i8, align_of::<u16>() as i32))
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vld1.16"))]
pub unsafe fn vld1q_u16(ptr: *const u16) -> uint16x8_t {
transmute(vld1q_v8i16(ptr as *const i8, align_of::<u16>() as i32))
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vldr))]
pub unsafe fn vld1_u32(ptr: *const u32) -> uint32x2_t {
transmute(vld1_v2i32(ptr as *const i8, align_of::<u32>() as i32))
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vld1.32"))]
pub unsafe fn vld1q_u32(ptr: *const u32) -> uint32x4_t {
transmute(vld1q_v4i32(ptr as *const i8, align_of::<u32>() as i32))
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vldr))]
pub unsafe fn vld1_u64(ptr: *const u64) -> uint64x1_t {
transmute(vld1_v1i64(ptr as *const i8, align_of::<u64>() as i32))
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vld1.64"))]
pub unsafe fn vld1q_u64(ptr: *const u64) -> uint64x2_t {
transmute(vld1q_v2i64(ptr as *const i8, align_of::<u64>() as i32))
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vld1.8"))]
pub unsafe fn vld1_p8(ptr: *const p8) -> poly8x8_t {
transmute(vld1_v8i8(ptr as *const i8, align_of::<p8>() as i32))
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vld1.8"))]
pub unsafe fn vld1q_p8(ptr: *const p8) -> poly8x16_t {
transmute(vld1q_v16i8(ptr as *const i8, align_of::<p8>() as i32))
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vld1.16"))]
pub unsafe fn vld1_p16(ptr: *const p16) -> poly16x4_t {
transmute(vld1_v4i16(ptr as *const i8, align_of::<p16>() as i32))
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vld1.16"))]
pub unsafe fn vld1q_p16(ptr: *const p16) -> poly16x8_t {
transmute(vld1q_v8i16(ptr as *const i8, align_of::<p16>() as i32))
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,aes")]
#[cfg_attr(test, assert_instr(vldr))]
pub unsafe fn vld1_p64(ptr: *const p64) -> poly64x1_t {
transmute(vld1_v1i64(ptr as *const i8, align_of::<p64>() as i32))
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,aes")]
#[cfg_attr(test, assert_instr("vld1.64"))]
pub unsafe fn vld1q_p64(ptr: *const p64) -> poly64x2_t {
transmute(vld1q_v2i64(ptr as *const i8, align_of::<p64>() as i32))
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vldr))]
pub unsafe fn vld1_f32(ptr: *const f32) -> float32x2_t {
vld1_v2f32(ptr as *const i8, align_of::<f32>() as i32)
}
/// Load multiple single-element structures to one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vld1.32"))]
pub unsafe fn vld1q_f32(ptr: *const f32) -> float32x4_t {
vld1q_v4f32(ptr as *const i8, align_of::<f32>() as i32)
}
/// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.8"))]
pub unsafe fn vst1_s8(ptr: *mut i8, a: int8x8_t) {
vst1_v8i8(ptr as *const i8, a, align_of::<i8>() as i32)
}
/// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.8"))]
pub unsafe fn vst1q_s8(ptr: *mut i8, a: int8x16_t) {
vst1q_v16i8(ptr as *const i8, a, align_of::<i8>() as i32)
}
/// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.16"))]
pub unsafe fn vst1_s16(ptr: *mut i16, a: int16x4_t) {
vst1_v4i16(ptr as *const i8, a, align_of::<i16>() as i32)
}
/// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.16"))]
pub unsafe fn vst1q_s16(ptr: *mut i16, a: int16x8_t) {
vst1q_v8i16(ptr as *const i8, a, align_of::<i16>() as i32)
}
/// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.32"))]
pub unsafe fn vst1_s32(ptr: *mut i32, a: int32x2_t) {
vst1_v2i32(ptr as *const i8, a, align_of::<i32>() as i32)
}
/// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.32"))]
pub unsafe fn vst1q_s32(ptr: *mut i32, a: int32x4_t) {
vst1q_v4i32(ptr as *const i8, a, align_of::<i32>() as i32)
}
/// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.64"))]
pub unsafe fn vst1_s64(ptr: *mut i64, a: int64x1_t) {
vst1_v1i64(ptr as *const i8, a, align_of::<i64>() as i32)
}
/// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.64"))]
pub unsafe fn vst1q_s64(ptr: *mut i64, a: int64x2_t) {
vst1q_v2i64(ptr as *const i8, a, align_of::<i64>() as i32)
}
/// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.8"))]
pub unsafe fn vst1_u8(ptr: *mut u8, a: uint8x8_t) {
vst1_v8i8(ptr as *const i8, transmute(a), align_of::<u8>() as i32)
}
/// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.8"))]
pub unsafe fn vst1q_u8(ptr: *mut u8, a: uint8x16_t) {
vst1q_v16i8(ptr as *const i8, transmute(a), align_of::<u8>() as i32)
}
/// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.16"))]
pub unsafe fn vst1_u16(ptr: *mut u16, a: uint16x4_t) {
vst1_v4i16(ptr as *const i8, transmute(a), align_of::<u16>() as i32)
}
/// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.16"))]
pub unsafe fn vst1q_u16(ptr: *mut u16, a: uint16x8_t) {
vst1q_v8i16(ptr as *const i8, transmute(a), align_of::<u16>() as i32)
}
/// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.32"))]
pub unsafe fn vst1_u32(ptr: *mut u32, a: uint32x2_t) {
vst1_v2i32(ptr as *const i8, transmute(a), align_of::<u32>() as i32)
}
/// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.32"))]
pub unsafe fn vst1q_u32(ptr: *mut u32, a: uint32x4_t) {
vst1q_v4i32(ptr as *const i8, transmute(a), align_of::<u32>() as i32)
}
/// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.64"))]
pub unsafe fn vst1_u64(ptr: *mut u64, a: uint64x1_t) {
vst1_v1i64(ptr as *const i8, transmute(a), align_of::<u64>() as i32)
}
/// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.64"))]
pub unsafe fn vst1q_u64(ptr: *mut u64, a: uint64x2_t) {
vst1q_v2i64(ptr as *const i8, transmute(a), align_of::<u64>() as i32)
}
/// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.8"))]
pub unsafe fn vst1_p8(ptr: *mut p8, a: poly8x8_t) {
vst1_v8i8(ptr as *const i8, transmute(a), align_of::<p8>() as i32)
}
/// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.8"))]
pub unsafe fn vst1q_p8(ptr: *mut p8, a: poly8x16_t) {
vst1q_v16i8(ptr as *const i8, transmute(a), align_of::<p8>() as i32)
}
/// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.16"))]
pub unsafe fn vst1_p16(ptr: *mut p16, a: poly16x4_t) {
vst1_v4i16(ptr as *const i8, transmute(a), align_of::<p16>() as i32)
}
/// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.16"))]
pub unsafe fn vst1q_p16(ptr: *mut p16, a: poly16x8_t) {
vst1q_v8i16(ptr as *const i8, transmute(a), align_of::<p8>() as i32)
}
// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.32"))]
pub unsafe fn vst1_f32(ptr: *mut f32, a: float32x2_t) {
vst1_v2f32(ptr as *const i8, a, align_of::<f32>() as i32)
}
// Store multiple single-element structures from one, two, three, or four registers.
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vst1.32"))]
pub unsafe fn vst1q_f32(ptr: *mut f32, a: float32x4_t) {
vst1q_v4f32(ptr as *const i8, a, align_of::<f32>() as i32)
}
/// Table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl1_s8(a: int8x8_t, b: int8x8_t) -> int8x8_t {
vtbl1(a, b)
}
/// Table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl1_u8(a: uint8x8_t, b: uint8x8_t) -> uint8x8_t {
transmute(vtbl1(transmute(a), transmute(b)))
}
/// Table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl1_p8(a: poly8x8_t, b: uint8x8_t) -> poly8x8_t {
transmute(vtbl1(transmute(a), transmute(b)))
}
/// Table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl2_s8(a: int8x8x2_t, b: int8x8_t) -> int8x8_t {
vtbl2(a.0, a.1, b)
}
/// Table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl2_u8(a: uint8x8x2_t, b: uint8x8_t) -> uint8x8_t {
transmute(vtbl2(transmute(a.0), transmute(a.1), transmute(b)))
}
/// Table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl2_p8(a: poly8x8x2_t, b: uint8x8_t) -> poly8x8_t {
transmute(vtbl2(transmute(a.0), transmute(a.1), transmute(b)))
}
/// Table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl3_s8(a: int8x8x3_t, b: int8x8_t) -> int8x8_t {
vtbl3(a.0, a.1, a.2, b)
}
/// Table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl3_u8(a: uint8x8x3_t, b: uint8x8_t) -> uint8x8_t {
transmute(vtbl3(
transmute(a.0),
transmute(a.1),
transmute(a.2),
transmute(b),
))
}
/// Table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl3_p8(a: poly8x8x3_t, b: uint8x8_t) -> poly8x8_t {
transmute(vtbl3(
transmute(a.0),
transmute(a.1),
transmute(a.2),
transmute(b),
))
}
/// Table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl4_s8(a: int8x8x4_t, b: int8x8_t) -> int8x8_t {
vtbl4(a.0, a.1, a.2, a.3, b)
}
/// Table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl4_u8(a: uint8x8x4_t, b: uint8x8_t) -> uint8x8_t {
transmute(vtbl4(
transmute(a.0),
transmute(a.1),
transmute(a.2),
transmute(a.3),
transmute(b),
))
}
/// Table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl4_p8(a: poly8x8x4_t, b: uint8x8_t) -> poly8x8_t {
transmute(vtbl4(
transmute(a.0),
transmute(a.1),
transmute(a.2),
transmute(a.3),
transmute(b),
))
}
/// Extended table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx1_s8(a: int8x8_t, b: int8x8_t, c: int8x8_t) -> int8x8_t {
vtbx1(a, b, c)
}
/// Extended table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx1_u8(a: uint8x8_t, b: uint8x8_t, c: uint8x8_t) -> uint8x8_t {
transmute(vtbx1(transmute(a), transmute(b), transmute(c)))
}
/// Extended table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx1_p8(a: poly8x8_t, b: poly8x8_t, c: uint8x8_t) -> poly8x8_t {
transmute(vtbx1(transmute(a), transmute(b), transmute(c)))
}
/// Extended table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx2_s8(a: int8x8_t, b: int8x8x2_t, c: int8x8_t) -> int8x8_t {
vtbx2(a, b.0, b.1, c)
}
/// Extended table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx2_u8(a: uint8x8_t, b: uint8x8x2_t, c: uint8x8_t) -> uint8x8_t {
transmute(vtbx2(
transmute(a),
transmute(b.0),
transmute(b.1),
transmute(c),
))
}
/// Extended table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx2_p8(a: poly8x8_t, b: poly8x8x2_t, c: uint8x8_t) -> poly8x8_t {
transmute(vtbx2(
transmute(a),
transmute(b.0),
transmute(b.1),
transmute(c),
))
}
/// Extended table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx3_s8(a: int8x8_t, b: int8x8x3_t, c: int8x8_t) -> int8x8_t {
vtbx3(a, b.0, b.1, b.2, c)
}
/// Extended table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx3_u8(a: uint8x8_t, b: uint8x8x3_t, c: uint8x8_t) -> uint8x8_t {
transmute(vtbx3(
transmute(a),
transmute(b.0),
transmute(b.1),
transmute(b.2),
transmute(c),
))
}
/// Extended table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx3_p8(a: poly8x8_t, b: poly8x8x3_t, c: uint8x8_t) -> poly8x8_t {
transmute(vtbx3(
transmute(a),
transmute(b.0),
transmute(b.1),
transmute(b.2),
transmute(c),
))
}
/// Extended table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx4_s8(a: int8x8_t, b: int8x8x4_t, c: int8x8_t) -> int8x8_t {
vtbx4(a, b.0, b.1, b.2, b.3, c)
}
/// Extended table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx4_u8(a: uint8x8_t, b: uint8x8x4_t, c: uint8x8_t) -> uint8x8_t {
transmute(vtbx4(
transmute(a),
transmute(b.0),
transmute(b.1),
transmute(b.2),
transmute(b.3),
transmute(c),
))
}
/// Extended table look-up
#[inline]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx4_p8(a: poly8x8_t, b: poly8x8x4_t, c: uint8x8_t) -> poly8x8_t {
transmute(vtbx4(
transmute(a),
transmute(b.0),
transmute(b.1),
transmute(b.2),
transmute(b.3),
transmute(c),
))
}
// These float-to-int implementations have undefined behaviour when `a` overflows
// the destination type. Clang has the same problem: https://llvm.org/PR47510
/// Floating-point Convert to Signed fixed-point, rounding toward Zero (vector)
#[inline]
#[target_feature(enable = "neon")]
#[target_feature(enable = "v7")]
#[cfg_attr(test, assert_instr("vcvt.s32.f32"))]
pub unsafe fn vcvtq_s32_f32(a: float32x4_t) -> int32x4_t {
transmute(simd_cast::<_, i32x4>(transmute::<_, f32x4>(a)))
}
/// Floating-point Convert to Unsigned fixed-point, rounding toward Zero (vector)
#[inline]
#[target_feature(enable = "neon")]
#[target_feature(enable = "v7")]
#[cfg_attr(test, assert_instr("vcvt.u32.f32"))]
pub unsafe fn vcvtq_u32_f32(a: float32x4_t) -> uint32x4_t {
transmute(simd_cast::<_, u32x4>(transmute::<_, f32x4>(a)))
}
/// Shift Left and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsli.8", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsli_n_s8<const N: i32>(a: int8x8_t, b: int8x8_t) -> int8x8_t {
static_assert_imm3!(N);
let n = N as i8;
vshiftins_v8i8(a, b, int8x8_t(n, n, n, n, n, n, n, n))
}
/// Shift Left and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsli.8", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsliq_n_s8<const N: i32>(a: int8x16_t, b: int8x16_t) -> int8x16_t {
static_assert_imm3!(N);
let n = N as i8;
vshiftins_v16i8(
a,
b,
int8x16_t(n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n),
)
}
/// Shift Left and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsli.16", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsli_n_s16<const N: i32>(a: int16x4_t, b: int16x4_t) -> int16x4_t {
static_assert_imm4!(N);
let n = N as i16;
vshiftins_v4i16(a, b, int16x4_t(n, n, n, n))
}
/// Shift Left and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsli.16", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsliq_n_s16<const N: i32>(a: int16x8_t, b: int16x8_t) -> int16x8_t {
static_assert_imm4!(N);
let n = N as i16;
vshiftins_v8i16(a, b, int16x8_t(n, n, n, n, n, n, n, n))
}
/// Shift Left and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsli.32", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsli_n_s32<const N: i32>(a: int32x2_t, b: int32x2_t) -> int32x2_t {
static_assert!(N: i32 where N >= 0 && N <= 31);
vshiftins_v2i32(a, b, int32x2_t(N, N))
}
/// Shift Left and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsli.32", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsliq_n_s32<const N: i32>(a: int32x4_t, b: int32x4_t) -> int32x4_t {
static_assert!(N: i32 where N >= 0 && N <= 31);
vshiftins_v4i32(a, b, int32x4_t(N, N, N, N))
}
/// Shift Left and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsli.64", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsli_n_s64<const N: i32>(a: int64x1_t, b: int64x1_t) -> int64x1_t {
static_assert!(N : i32 where 0 <= N && N <= 63);
vshiftins_v1i64(a, b, int64x1_t(N as i64))
}
/// Shift Left and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsli.64", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsliq_n_s64<const N: i32>(a: int64x2_t, b: int64x2_t) -> int64x2_t {
static_assert!(N : i32 where 0 <= N && N <= 63);
vshiftins_v2i64(a, b, int64x2_t(N as i64, N as i64))
}
/// Shift Left and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsli.8", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsli_n_u8<const N: i32>(a: uint8x8_t, b: uint8x8_t) -> uint8x8_t {
static_assert_imm3!(N);
let n = N as i8;
transmute(vshiftins_v8i8(
transmute(a),
transmute(b),
int8x8_t(n, n, n, n, n, n, n, n),
))
}
/// Shift Left and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsli.8", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsliq_n_u8<const N: i32>(a: uint8x16_t, b: uint8x16_t) -> uint8x16_t {
static_assert_imm3!(N);
let n = N as i8;
transmute(vshiftins_v16i8(
transmute(a),
transmute(b),
int8x16_t(n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n),
))
}
/// Shift Left and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsli.16", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsli_n_u16<const N: i32>(a: uint16x4_t, b: uint16x4_t) -> uint16x4_t {
static_assert_imm4!(N);
let n = N as i16;
transmute(vshiftins_v4i16(
transmute(a),
transmute(b),
int16x4_t(n, n, n, n),
))
}
/// Shift Left and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsli.16", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsliq_n_u16<const N: i32>(a: uint16x8_t, b: uint16x8_t) -> uint16x8_t {
static_assert_imm4!(N);
let n = N as i16;
transmute(vshiftins_v8i16(
transmute(a),
transmute(b),
int16x8_t(n, n, n, n, n, n, n, n),
))
}
/// Shift Left and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsli.32", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsli_n_u32<const N: i32>(a: uint32x2_t, b: uint32x2_t) -> uint32x2_t {
static_assert!(N: i32 where N >= 0 && N <= 31);
transmute(vshiftins_v2i32(transmute(a), transmute(b), int32x2_t(N, N)))
}
/// Shift Left and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsli.32", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsliq_n_u32<const N: i32>(a: uint32x4_t, b: uint32x4_t) -> uint32x4_t {
static_assert!(N: i32 where N >= 0 && N <= 31);
transmute(vshiftins_v4i32(
transmute(a),
transmute(b),
int32x4_t(N, N, N, N),
))
}
/// Shift Left and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsli.64", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsli_n_u64<const N: i32>(a: uint64x1_t, b: uint64x1_t) -> uint64x1_t {
static_assert!(N : i32 where 0 <= N && N <= 63);
transmute(vshiftins_v1i64(
transmute(a),
transmute(b),
int64x1_t(N as i64),
))
}
/// Shift Left and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsli.64", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsliq_n_u64<const N: i32>(a: uint64x2_t, b: uint64x2_t) -> uint64x2_t {
static_assert!(N : i32 where 0 <= N && N <= 63);
transmute(vshiftins_v2i64(
transmute(a),
transmute(b),
int64x2_t(N as i64, N as i64),
))
}
/// Shift Left and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsli.8", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsli_n_p8<const N: i32>(a: poly8x8_t, b: poly8x8_t) -> poly8x8_t {
static_assert_imm3!(N);
let n = N as i8;
transmute(vshiftins_v8i8(
transmute(a),
transmute(b),
int8x8_t(n, n, n, n, n, n, n, n),
))
}
/// Shift Left and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsli.8", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsliq_n_p8<const N: i32>(a: poly8x16_t, b: poly8x16_t) -> poly8x16_t {
static_assert_imm3!(N);
let n = N as i8;
transmute(vshiftins_v16i8(
transmute(a),
transmute(b),
int8x16_t(n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n),
))
}
/// Shift Left and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsli.16", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsli_n_p16<const N: i32>(a: poly16x4_t, b: poly16x4_t) -> poly16x4_t {
static_assert_imm4!(N);
let n = N as i16;
transmute(vshiftins_v4i16(
transmute(a),
transmute(b),
int16x4_t(n, n, n, n),
))
}
/// Shift Left and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsli.16", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsliq_n_p16<const N: i32>(a: poly16x8_t, b: poly16x8_t) -> poly16x8_t {
static_assert_imm4!(N);
let n = N as i16;
transmute(vshiftins_v8i16(
transmute(a),
transmute(b),
int16x8_t(n, n, n, n, n, n, n, n),
))
}
/// Shift Right and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsri.8", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsri_n_s8<const N: i32>(a: int8x8_t, b: int8x8_t) -> int8x8_t {
static_assert!(N : i32 where 1 <= N && N <= 8);
let n = -N as i8;
vshiftins_v8i8(a, b, int8x8_t(n, n, n, n, n, n, n, n))
}
/// Shift Right and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsri.8", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsriq_n_s8<const N: i32>(a: int8x16_t, b: int8x16_t) -> int8x16_t {
static_assert!(N : i32 where 1 <= N && N <= 8);
let n = -N as i8;
vshiftins_v16i8(
a,
b,
int8x16_t(n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n),
)
}
/// Shift Right and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsri.16", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsri_n_s16<const N: i32>(a: int16x4_t, b: int16x4_t) -> int16x4_t {
static_assert!(N : i32 where 1 <= N && N <= 16);
let n = -N as i16;
vshiftins_v4i16(a, b, int16x4_t(n, n, n, n))
}
/// Shift Right and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsri.16", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsriq_n_s16<const N: i32>(a: int16x8_t, b: int16x8_t) -> int16x8_t {
static_assert!(N : i32 where 1 <= N && N <= 16);
let n = -N as i16;
vshiftins_v8i16(a, b, int16x8_t(n, n, n, n, n, n, n, n))
}
/// Shift Right and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsri.32", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsri_n_s32<const N: i32>(a: int32x2_t, b: int32x2_t) -> int32x2_t {
static_assert!(N : i32 where 1 <= N && N <= 32);
vshiftins_v2i32(a, b, int32x2_t(-N, -N))
}
/// Shift Right and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsri.32", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsriq_n_s32<const N: i32>(a: int32x4_t, b: int32x4_t) -> int32x4_t {
static_assert!(N : i32 where 1 <= N && N <= 32);
vshiftins_v4i32(a, b, int32x4_t(-N, -N, -N, -N))
}
/// Shift Right and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsri.64", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsri_n_s64<const N: i32>(a: int64x1_t, b: int64x1_t) -> int64x1_t {
static_assert!(N : i32 where 1 <= N && N <= 64);
vshiftins_v1i64(a, b, int64x1_t(-N as i64))
}
/// Shift Right and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsri.64", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsriq_n_s64<const N: i32>(a: int64x2_t, b: int64x2_t) -> int64x2_t {
static_assert!(N : i32 where 1 <= N && N <= 64);
vshiftins_v2i64(a, b, int64x2_t(-N as i64, -N as i64))
}
/// Shift Right and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsri.8", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsri_n_u8<const N: i32>(a: uint8x8_t, b: uint8x8_t) -> uint8x8_t {
static_assert!(N : i32 where 1 <= N && N <= 8);
let n = -N as i8;
transmute(vshiftins_v8i8(
transmute(a),
transmute(b),
int8x8_t(n, n, n, n, n, n, n, n),
))
}
/// Shift Right and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsri.8", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsriq_n_u8<const N: i32>(a: uint8x16_t, b: uint8x16_t) -> uint8x16_t {
static_assert!(N : i32 where 1 <= N && N <= 8);
let n = -N as i8;
transmute(vshiftins_v16i8(
transmute(a),
transmute(b),
int8x16_t(n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n),
))
}
/// Shift Right and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsri.16", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsri_n_u16<const N: i32>(a: uint16x4_t, b: uint16x4_t) -> uint16x4_t {
static_assert!(N : i32 where 1 <= N && N <= 16);
let n = -N as i16;
transmute(vshiftins_v4i16(
transmute(a),
transmute(b),
int16x4_t(n, n, n, n),
))
}
/// Shift Right and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsri.16", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsriq_n_u16<const N: i32>(a: uint16x8_t, b: uint16x8_t) -> uint16x8_t {
static_assert!(N : i32 where 1 <= N && N <= 16);
let n = -N as i16;
transmute(vshiftins_v8i16(
transmute(a),
transmute(b),
int16x8_t(n, n, n, n, n, n, n, n),
))
}
/// Shift Right and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsri.32", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsri_n_u32<const N: i32>(a: uint32x2_t, b: uint32x2_t) -> uint32x2_t {
static_assert!(N : i32 where 1 <= N && N <= 32);
transmute(vshiftins_v2i32(
transmute(a),
transmute(b),
int32x2_t(-N, -N),
))
}
/// Shift Right and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsri.32", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsriq_n_u32<const N: i32>(a: uint32x4_t, b: uint32x4_t) -> uint32x4_t {
static_assert!(N : i32 where 1 <= N && N <= 32);
transmute(vshiftins_v4i32(
transmute(a),
transmute(b),
int32x4_t(-N, -N, -N, -N),
))
}
/// Shift Right and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsri.64", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsri_n_u64<const N: i32>(a: uint64x1_t, b: uint64x1_t) -> uint64x1_t {
static_assert!(N : i32 where 1 <= N && N <= 64);
transmute(vshiftins_v1i64(
transmute(a),
transmute(b),
int64x1_t(-N as i64),
))
}
/// Shift Right and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsri.64", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsriq_n_u64<const N: i32>(a: uint64x2_t, b: uint64x2_t) -> uint64x2_t {
static_assert!(N : i32 where 1 <= N && N <= 64);
transmute(vshiftins_v2i64(
transmute(a),
transmute(b),
int64x2_t(-N as i64, -N as i64),
))
}
/// Shift Right and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsri.8", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsri_n_p8<const N: i32>(a: poly8x8_t, b: poly8x8_t) -> poly8x8_t {
static_assert!(N : i32 where 1 <= N && N <= 8);
let n = -N as i8;
transmute(vshiftins_v8i8(
transmute(a),
transmute(b),
int8x8_t(n, n, n, n, n, n, n, n),
))
}
/// Shift Right and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsri.8", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsriq_n_p8<const N: i32>(a: poly8x16_t, b: poly8x16_t) -> poly8x16_t {
static_assert!(N : i32 where 1 <= N && N <= 8);
let n = -N as i8;
transmute(vshiftins_v16i8(
transmute(a),
transmute(b),
int8x16_t(n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n),
))
}
/// Shift Right and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsri.16", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsri_n_p16<const N: i32>(a: poly16x4_t, b: poly16x4_t) -> poly16x4_t {
static_assert!(N : i32 where 1 <= N && N <= 16);
let n = -N as i16;
transmute(vshiftins_v4i16(
transmute(a),
transmute(b),
int16x4_t(n, n, n, n),
))
}
/// Shift Right and Insert (immediate)
#[inline]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr("vsri.16", N = 1))]
#[rustc_legacy_const_generics(2)]
pub unsafe fn vsriq_n_p16<const N: i32>(a: poly16x8_t, b: poly16x8_t) -> poly16x8_t {
static_assert!(N : i32 where 1 <= N && N <= 16);
let n = -N as i16;
transmute(vshiftins_v8i16(
transmute(a),
transmute(b),
int16x8_t(n, n, n, n, n, n, n, n),
))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core_arch::{arm::*, simd::*};
use crate::mem::transmute;
use stdarch_test::simd_test;
#[simd_test(enable = "neon")]
unsafe fn test_vcvtq_s32_f32() {
let f = f32x4::new(-1., 2., 3., 4.);
let e = i32x4::new(-1, 2, 3, 4);
let r: i32x4 = transmute(vcvtq_s32_f32(transmute(f)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vcvtq_u32_f32() {
let f = f32x4::new(1., 2., 3., 4.);
let e = u32x4::new(1, 2, 3, 4);
let r: u32x4 = transmute(vcvtq_u32_f32(transmute(f)));
assert_eq!(r, e);
}
}
| 34.866462 | 90 | 0.657459 |
6298975fcf55406564aac158701dd2808a94ba60 | 268 | use std::env;
extern crate dosbox_lib;
use dosbox_lib::DOSBox;
fn main() -> Result<(), String> {
let args: Vec<String> = env::args().skip(1).collect();
DOSBox::new()
.find_dosbox()?
.cwd(&args[0])
.command(&args[1])
.run()
}
| 17.866667 | 58 | 0.541045 |
29e384bfa4bfda795da1cba138ac902fa74483af | 29,915 | #![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageSyncError {
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<StorageSyncApiError>,
#[serde(skip_serializing_if = "Option::is_none")]
pub innererror: Option<StorageSyncApiError>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageSyncApiError {
#[serde(skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub details: Option<StorageSyncErrorDetails>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageSyncErrorDetails {
#[serde(skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SubscriptionState {
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<subscription_state::State>,
#[serde(skip_serializing)]
pub istransitioning: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<SubscriptionStateProperties>,
}
pub mod subscription_state {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum State {
Registered,
Unregistered,
Warned,
Suspended,
Deleted,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageSyncService {
#[serde(flatten)]
pub tracked_resource: TrackedResource,
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<StorageSyncServiceProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SyncGroup {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<SyncGroupProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CloudEndpoint {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<CloudEndpointProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RecallActionParameters {
#[serde(skip_serializing_if = "Option::is_none")]
pub pattern: Option<String>,
#[serde(rename = "recallPath", skip_serializing_if = "Option::is_none")]
pub recall_path: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageSyncServiceCreateParameters {
pub location: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SyncGroupCreateParameters {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<SyncGroupCreateParametersProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SyncGroupCreateParametersProperties {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CloudEndpointCreateParameters {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<CloudEndpointCreateParametersProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CloudEndpointCreateParametersProperties {
#[serde(rename = "storageAccountResourceId", skip_serializing_if = "Option::is_none")]
pub storage_account_resource_id: Option<String>,
#[serde(rename = "azureFileShareName", skip_serializing_if = "Option::is_none")]
pub azure_file_share_name: Option<String>,
#[serde(rename = "storageAccountTenantId", skip_serializing_if = "Option::is_none")]
pub storage_account_tenant_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerEndpointCreateParameters {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<ServerEndpointCreateParametersProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerEndpointCreateParametersProperties {
#[serde(rename = "serverLocalPath", skip_serializing_if = "Option::is_none")]
pub server_local_path: Option<PhysicalPath>,
#[serde(rename = "cloudTiering", skip_serializing_if = "Option::is_none")]
pub cloud_tiering: Option<FeatureStatus>,
#[serde(rename = "volumeFreeSpacePercent", skip_serializing_if = "Option::is_none")]
pub volume_free_space_percent: Option<i64>,
#[serde(rename = "tierFilesOlderThanDays", skip_serializing_if = "Option::is_none")]
pub tier_files_older_than_days: Option<i64>,
#[serde(rename = "friendlyName", skip_serializing_if = "Option::is_none")]
pub friendly_name: Option<String>,
#[serde(rename = "serverResourceId", skip_serializing_if = "Option::is_none")]
pub server_resource_id: Option<ResourceId>,
#[serde(rename = "offlineDataTransfer", skip_serializing_if = "Option::is_none")]
pub offline_data_transfer: Option<FeatureStatus>,
#[serde(rename = "offlineDataTransferShareName", skip_serializing_if = "Option::is_none")]
pub offline_data_transfer_share_name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TriggerRolloverRequest {
#[serde(rename = "serverCertificate", skip_serializing_if = "Option::is_none")]
pub server_certificate: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RegisteredServerCreateParameters {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<RegisteredServerCreateParametersProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RegisteredServerCreateParametersProperties {
#[serde(rename = "serverCertificate", skip_serializing_if = "Option::is_none")]
pub server_certificate: Option<String>,
#[serde(rename = "agentVersion", skip_serializing_if = "Option::is_none")]
pub agent_version: Option<String>,
#[serde(rename = "serverOSVersion", skip_serializing_if = "Option::is_none")]
pub server_os_version: Option<String>,
#[serde(rename = "lastHeartBeat", skip_serializing_if = "Option::is_none")]
pub last_heart_beat: Option<String>,
#[serde(rename = "serverRole", skip_serializing_if = "Option::is_none")]
pub server_role: Option<String>,
#[serde(rename = "clusterId", skip_serializing_if = "Option::is_none")]
pub cluster_id: Option<String>,
#[serde(rename = "clusterName", skip_serializing_if = "Option::is_none")]
pub cluster_name: Option<String>,
#[serde(rename = "serverId", skip_serializing_if = "Option::is_none")]
pub server_id: Option<String>,
#[serde(rename = "friendlyName", skip_serializing_if = "Option::is_none")]
pub friendly_name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerEndpointUpdateParameters {
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<ServerEndpointUpdateProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerEndpoint {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<ServerEndpointProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RegisteredServer {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<RegisteredServerProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourcesMoveInfo {
#[serde(rename = "targetResourceGroup", skip_serializing_if = "Option::is_none")]
pub target_resource_group: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub resources: Vec<ResourceId>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Workflow {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<WorkflowProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationEntityListResult {
#[serde(rename = "nextLink", skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub value: Vec<OperationEntity>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationEntity {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub display: Option<OperationDisplayInfo>,
#[serde(skip_serializing_if = "Option::is_none")]
pub origin: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationDisplayInfo {
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationDisplayResource {
#[serde(skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CheckNameAvailabilityParameters {
pub name: String,
#[serde(rename = "type")]
pub type_: check_name_availability_parameters::Type,
}
pub mod check_name_availability_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
#[serde(rename = "Microsoft.StorageSync/storageSyncServices")]
MicrosoftStorageSyncStorageSyncServices,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CheckNameAvailabilityResult {
#[serde(rename = "nameAvailable", skip_serializing)]
pub name_available: Option<bool>,
#[serde(skip_serializing)]
pub reason: Option<check_name_availability_result::Reason>,
#[serde(skip_serializing)]
pub message: Option<String>,
}
pub mod check_name_availability_result {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Reason {
Invalid,
AlreadyExists,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PostRestoreRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub partition: Option<String>,
#[serde(rename = "replicaGroup", skip_serializing_if = "Option::is_none")]
pub replica_group: Option<String>,
#[serde(rename = "requestId", skip_serializing_if = "Option::is_none")]
pub request_id: Option<String>,
#[serde(rename = "azureFileShareUri", skip_serializing_if = "Option::is_none")]
pub azure_file_share_uri: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
#[serde(rename = "sourceAzureFileShareUri", skip_serializing_if = "Option::is_none")]
pub source_azure_file_share_uri: Option<String>,
#[serde(rename = "failedFileList", skip_serializing_if = "Option::is_none")]
pub failed_file_list: Option<String>,
#[serde(rename = "restoreFileSpec", skip_serializing_if = "Vec::is_empty")]
pub restore_file_spec: Vec<RestoreFileSpec>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PreRestoreRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub partition: Option<String>,
#[serde(rename = "replicaGroup", skip_serializing_if = "Option::is_none")]
pub replica_group: Option<String>,
#[serde(rename = "requestId", skip_serializing_if = "Option::is_none")]
pub request_id: Option<String>,
#[serde(rename = "azureFileShareUri", skip_serializing_if = "Option::is_none")]
pub azure_file_share_uri: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
#[serde(rename = "sourceAzureFileShareUri", skip_serializing_if = "Option::is_none")]
pub source_azure_file_share_uri: Option<String>,
#[serde(rename = "backupMetadataPropertyBag", skip_serializing_if = "Option::is_none")]
pub backup_metadata_property_bag: Option<String>,
#[serde(rename = "restoreFileSpec", skip_serializing_if = "Vec::is_empty")]
pub restore_file_spec: Vec<RestoreFileSpec>,
#[serde(rename = "pauseWaitForSyncDrainTimePeriodInSeconds", skip_serializing_if = "Option::is_none")]
pub pause_wait_for_sync_drain_time_period_in_seconds: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BackupRequest {
#[serde(rename = "azureFileShare", skip_serializing_if = "Option::is_none")]
pub azure_file_share: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PostBackupResponse {
#[serde(rename = "backupMetadata", skip_serializing_if = "Option::is_none")]
pub backup_metadata: Option<PostBackupResponseProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RestoreFileSpec {
#[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
#[serde(skip_serializing)]
pub isdir: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageSyncServiceArray {
#[serde(skip_serializing_if = "Vec::is_empty")]
pub value: Vec<StorageSyncService>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SyncGroupArray {
#[serde(skip_serializing_if = "Vec::is_empty")]
pub value: Vec<SyncGroup>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CloudEndpointArray {
#[serde(skip_serializing_if = "Vec::is_empty")]
pub value: Vec<CloudEndpoint>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerEndpointArray {
#[serde(skip_serializing_if = "Vec::is_empty")]
pub value: Vec<ServerEndpoint>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RegisteredServerArray {
#[serde(skip_serializing_if = "Vec::is_empty")]
pub value: Vec<RegisteredServer>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WorkflowArray {
#[serde(skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Workflow>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SubscriptionStateProperties {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PostBackupResponseProperties {
#[serde(rename = "cloudEndpointName", skip_serializing)]
pub cloud_endpoint_name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageSyncServiceUpdateParameters {
#[serde(skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<StorageSyncServiceUpdateProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageSyncServiceUpdateProperties {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageSyncServiceProperties {
#[serde(rename = "storageSyncServiceStatus", skip_serializing)]
pub storage_sync_service_status: Option<i64>,
#[serde(rename = "storageSyncServiceUid", skip_serializing)]
pub storage_sync_service_uid: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WorkflowProperties {
#[serde(rename = "lastStepName", skip_serializing_if = "Option::is_none")]
pub last_step_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub status: Option<WorkflowStatus>,
#[serde(skip_serializing_if = "Option::is_none")]
pub operation: Option<OperationDirection>,
#[serde(skip_serializing_if = "Option::is_none")]
pub steps: Option<String>,
#[serde(rename = "lastOperationId", skip_serializing_if = "Option::is_none")]
pub last_operation_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SyncGroupProperties {
#[serde(rename = "uniqueId", skip_serializing_if = "Option::is_none")]
pub unique_id: Option<String>,
#[serde(rename = "syncGroupStatus", skip_serializing)]
pub sync_group_status: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RegisteredServerProperties {
#[serde(rename = "serverCertificate", skip_serializing_if = "Option::is_none")]
pub server_certificate: Option<String>,
#[serde(rename = "agentVersion", skip_serializing_if = "Option::is_none")]
pub agent_version: Option<String>,
#[serde(rename = "serverOSVersion", skip_serializing_if = "Option::is_none")]
pub server_os_version: Option<String>,
#[serde(rename = "serverManagementErrorCode", skip_serializing_if = "Option::is_none")]
pub server_management_error_code: Option<i64>,
#[serde(rename = "lastHeartBeat", skip_serializing_if = "Option::is_none")]
pub last_heart_beat: Option<String>,
#[serde(rename = "provisioningState", skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
#[serde(rename = "serverRole", skip_serializing_if = "Option::is_none")]
pub server_role: Option<String>,
#[serde(rename = "clusterId", skip_serializing_if = "Option::is_none")]
pub cluster_id: Option<String>,
#[serde(rename = "clusterName", skip_serializing_if = "Option::is_none")]
pub cluster_name: Option<String>,
#[serde(rename = "serverId", skip_serializing_if = "Option::is_none")]
pub server_id: Option<String>,
#[serde(rename = "storageSyncServiceUid", skip_serializing_if = "Option::is_none")]
pub storage_sync_service_uid: Option<String>,
#[serde(rename = "lastWorkflowId", skip_serializing_if = "Option::is_none")]
pub last_workflow_id: Option<String>,
#[serde(rename = "lastOperationName", skip_serializing_if = "Option::is_none")]
pub last_operation_name: Option<String>,
#[serde(rename = "discoveryEndpointUri", skip_serializing_if = "Option::is_none")]
pub discovery_endpoint_uri: Option<String>,
#[serde(rename = "resourceLocation", skip_serializing_if = "Option::is_none")]
pub resource_location: Option<String>,
#[serde(rename = "serviceLocation", skip_serializing_if = "Option::is_none")]
pub service_location: Option<String>,
#[serde(rename = "friendlyName", skip_serializing_if = "Option::is_none")]
pub friendly_name: Option<String>,
#[serde(rename = "managementEndpointUri", skip_serializing_if = "Option::is_none")]
pub management_endpoint_uri: Option<String>,
#[serde(rename = "monitoringConfiguration", skip_serializing_if = "Option::is_none")]
pub monitoring_configuration: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CloudEndpointProperties {
#[serde(rename = "storageAccountResourceId", skip_serializing_if = "Option::is_none")]
pub storage_account_resource_id: Option<String>,
#[serde(rename = "azureFileShareName", skip_serializing_if = "Option::is_none")]
pub azure_file_share_name: Option<String>,
#[serde(rename = "storageAccountTenantId", skip_serializing_if = "Option::is_none")]
pub storage_account_tenant_id: Option<String>,
#[serde(rename = "partnershipId", skip_serializing_if = "Option::is_none")]
pub partnership_id: Option<String>,
#[serde(rename = "friendlyName", skip_serializing_if = "Option::is_none")]
pub friendly_name: Option<String>,
#[serde(rename = "backupEnabled", skip_serializing)]
pub backup_enabled: Option<String>,
#[serde(rename = "provisioningState", skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
#[serde(rename = "lastWorkflowId", skip_serializing_if = "Option::is_none")]
pub last_workflow_id: Option<String>,
#[serde(rename = "lastOperationName", skip_serializing_if = "Option::is_none")]
pub last_operation_name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerEndpointUpdateProperties {
#[serde(rename = "cloudTiering", skip_serializing_if = "Option::is_none")]
pub cloud_tiering: Option<FeatureStatus>,
#[serde(rename = "volumeFreeSpacePercent", skip_serializing_if = "Option::is_none")]
pub volume_free_space_percent: Option<i64>,
#[serde(rename = "tierFilesOlderThanDays", skip_serializing_if = "Option::is_none")]
pub tier_files_older_than_days: Option<i64>,
#[serde(rename = "offlineDataTransfer", skip_serializing_if = "Option::is_none")]
pub offline_data_transfer: Option<FeatureStatus>,
#[serde(rename = "offlineDataTransferShareName", skip_serializing_if = "Option::is_none")]
pub offline_data_transfer_share_name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerEndpointProperties {
#[serde(rename = "serverLocalPath", skip_serializing_if = "Option::is_none")]
pub server_local_path: Option<PhysicalPath>,
#[serde(rename = "cloudTiering", skip_serializing_if = "Option::is_none")]
pub cloud_tiering: Option<FeatureStatus>,
#[serde(rename = "volumeFreeSpacePercent", skip_serializing_if = "Option::is_none")]
pub volume_free_space_percent: Option<i64>,
#[serde(rename = "tierFilesOlderThanDays", skip_serializing_if = "Option::is_none")]
pub tier_files_older_than_days: Option<i64>,
#[serde(rename = "friendlyName", skip_serializing_if = "Option::is_none")]
pub friendly_name: Option<String>,
#[serde(rename = "serverResourceId", skip_serializing_if = "Option::is_none")]
pub server_resource_id: Option<ResourceId>,
#[serde(rename = "provisioningState", skip_serializing)]
pub provisioning_state: Option<String>,
#[serde(rename = "lastWorkflowId", skip_serializing)]
pub last_workflow_id: Option<String>,
#[serde(rename = "lastOperationName", skip_serializing)]
pub last_operation_name: Option<String>,
#[serde(rename = "syncStatus", skip_serializing_if = "Option::is_none")]
pub sync_status: Option<ServerEndpointSyncStatus>,
#[serde(rename = "offlineDataTransfer", skip_serializing_if = "Option::is_none")]
pub offline_data_transfer: Option<FeatureStatus>,
#[serde(rename = "offlineDataTransferStorageAccountResourceId", skip_serializing)]
pub offline_data_transfer_storage_account_resource_id: Option<String>,
#[serde(rename = "offlineDataTransferStorageAccountTenantId", skip_serializing)]
pub offline_data_transfer_storage_account_tenant_id: Option<String>,
#[serde(rename = "offlineDataTransferShareName", skip_serializing_if = "Option::is_none")]
pub offline_data_transfer_share_name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerEndpointSyncStatus {
#[serde(rename = "downloadHealth", skip_serializing_if = "Option::is_none")]
pub download_health: Option<HealthState>,
#[serde(rename = "uploadHealth", skip_serializing_if = "Option::is_none")]
pub upload_health: Option<HealthState>,
#[serde(rename = "combinedHealth", skip_serializing_if = "Option::is_none")]
pub combined_health: Option<HealthState>,
#[serde(rename = "syncActivity", skip_serializing_if = "Option::is_none")]
pub sync_activity: Option<SyncActivityState>,
#[serde(rename = "totalPersistentFilesNotSyncingCount", skip_serializing)]
pub total_persistent_files_not_syncing_count: Option<i64>,
#[serde(rename = "lastUpdatedTimestamp", skip_serializing)]
pub last_updated_timestamp: Option<String>,
#[serde(rename = "uploadStatus", skip_serializing_if = "Option::is_none")]
pub upload_status: Option<SyncSessionStatus>,
#[serde(rename = "downloadStatus", skip_serializing_if = "Option::is_none")]
pub download_status: Option<SyncSessionStatus>,
#[serde(rename = "uploadActivity", skip_serializing_if = "Option::is_none")]
pub upload_activity: Option<SyncActivityStatus>,
#[serde(rename = "downloadActivity", skip_serializing_if = "Option::is_none")]
pub download_activity: Option<SyncActivityStatus>,
#[serde(rename = "offlineDataTransferStatus", skip_serializing_if = "Option::is_none")]
pub offline_data_transfer_status: Option<OfflineDataTransferState>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SyncSessionStatus {
#[serde(rename = "lastSyncResult", skip_serializing)]
pub last_sync_result: Option<i32>,
#[serde(rename = "lastSyncTimestamp", skip_serializing)]
pub last_sync_timestamp: Option<String>,
#[serde(rename = "lastSyncSuccessTimestamp", skip_serializing)]
pub last_sync_success_timestamp: Option<String>,
#[serde(rename = "lastSyncPerItemErrorCount", skip_serializing)]
pub last_sync_per_item_error_count: Option<i64>,
#[serde(rename = "persistentFilesNotSyncingCount", skip_serializing)]
pub persistent_files_not_syncing_count: Option<i64>,
#[serde(rename = "transientFilesNotSyncingCount", skip_serializing)]
pub transient_files_not_syncing_count: Option<i64>,
#[serde(rename = "filesNotSyncingErrors", skip_serializing)]
pub files_not_syncing_errors: Vec<FilesNotSyncingError>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SyncActivityStatus {
#[serde(skip_serializing)]
pub timestamp: Option<String>,
#[serde(rename = "perItemErrorCount", skip_serializing)]
pub per_item_error_count: Option<i64>,
#[serde(rename = "appliedItemCount", skip_serializing)]
pub applied_item_count: Option<i64>,
#[serde(rename = "totalItemCount", skip_serializing)]
pub total_item_count: Option<i64>,
#[serde(rename = "appliedBytes", skip_serializing)]
pub applied_bytes: Option<i64>,
#[serde(rename = "totalBytes", skip_serializing)]
pub total_bytes: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FilesNotSyncingError {
#[serde(rename = "errorCode", skip_serializing)]
pub error_code: Option<i32>,
#[serde(rename = "persistentCount", skip_serializing)]
pub persistent_count: Option<i64>,
#[serde(rename = "transientCount", skip_serializing)]
pub transient_count: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PhysicalPath {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceId {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TagsObject {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum FeatureStatus {
#[serde(rename = "on")]
On,
#[serde(rename = "off")]
Off,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum HealthState {
Healthy,
Error,
SyncBlockedForRestore,
SyncBlockedForChangeDetectionPostRestore,
NoActivity,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SyncActivityState {
Upload,
Download,
UploadAndDownload,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum OfflineDataTransferState {
InProgress,
Stopping,
NotRunning,
Complete,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum WorkflowStatus {
#[serde(rename = "active")]
Active,
#[serde(rename = "expired")]
Expired,
#[serde(rename = "succeeded")]
Succeeded,
#[serde(rename = "aborted")]
Aborted,
#[serde(rename = "failed")]
Failed,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum OperationDirection {
#[serde(rename = "do")]
Do,
#[serde(rename = "undo")]
Undo,
#[serde(rename = "cancel")]
Cancel,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProgressType {
#[serde(rename = "none")]
None,
#[serde(rename = "initialize")]
Initialize,
#[serde(rename = "download")]
Download,
#[serde(rename = "upload")]
Upload,
#[serde(rename = "recall")]
Recall,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TrackedResource {
#[serde(flatten)]
pub resource: Resource,
#[serde(skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
pub location: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(skip_serializing)]
pub id: Option<String>,
#[serde(skip_serializing)]
pub name: Option<String>,
#[serde(rename = "type", skip_serializing)]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProxyResource {
#[serde(flatten)]
pub resource: Resource,
}
| 44.850075 | 106 | 0.728899 |
efa85324fcc1386e0646f77fa92cd7dfca4ca8f7 | 1,820 | // Copyright 2022 RisingLight Project Authors. Licensed under Apache-2.0.
use std::fmt;
use itertools::Itertools;
use super::*;
use crate::catalog::ColumnCatalog;
use crate::types::{DatabaseId, SchemaId};
/// The logical plan of `CREATE TABLE`.
#[derive(Debug, Clone)]
pub struct LogicalCreateTable {
database_id: DatabaseId,
schema_id: SchemaId,
table_name: String,
columns: Vec<ColumnCatalog>,
}
impl LogicalCreateTable {
pub fn new(
database_id: DatabaseId,
schema_id: SchemaId,
table_name: String,
columns: Vec<ColumnCatalog>,
) -> Self {
Self {
database_id,
schema_id,
table_name,
columns,
}
}
/// Get a reference to the logical create table's database id.
pub fn database_id(&self) -> u32 {
self.database_id
}
/// Get a reference to the logical create table's schema id.
pub fn schema_id(&self) -> u32 {
self.schema_id
}
/// Get a reference to the logical create table's table name.
pub fn table_name(&self) -> &str {
self.table_name.as_ref()
}
/// Get a reference to the logical create table's columns.
pub fn columns(&self) -> &[ColumnCatalog] {
self.columns.as_ref()
}
}
impl PlanTreeNodeLeaf for LogicalCreateTable {}
impl_plan_tree_node_for_leaf!(LogicalCreateTable);
impl PlanNode for LogicalCreateTable {}
impl fmt::Display for LogicalCreateTable {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(
f,
"PhysicalCreateTable: table {}, columns [{}]",
self.table_name,
self.columns
.iter()
.map(|x| format!("{}:{:?}", x.name(), x.datatype()))
.join(", ")
)
}
}
| 25.277778 | 73 | 0.594505 |
feb3d4c7bf62316a84d1c4fea47676af692c2903 | 88,220 | use lib::*;
use de::{Deserialize, DeserializeSeed, Deserializer, Error, IntoDeserializer, Visitor};
#[cfg(any(feature = "std", feature = "alloc"))]
use de::{MapAccess, Unexpected};
#[cfg(any(feature = "std", feature = "alloc"))]
pub use self::content::{
Content, ContentDeserializer, ContentRefDeserializer, EnumDeserializer,
InternallyTaggedUnitVisitor, TagContentOtherField, TagContentOtherFieldVisitor,
TagOrContentField, TagOrContentFieldVisitor, TaggedContentVisitor, UntaggedUnitVisitor,
};
/// If the missing field is of type `Option<T>` then treat is as `None`,
/// otherwise it is an error.
pub fn missing_field<'de, V, E>(field: &'static str) -> Result<V, E>
where
V: Deserialize<'de>,
E: Error,
{
struct MissingFieldDeserializer<E>(&'static str, PhantomData<E>);
impl<'de, E> Deserializer<'de> for MissingFieldDeserializer<E>
where
E: Error,
{
type Error = E;
fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, E>
where
V: Visitor<'de>,
{
Err(Error::missing_field(self.0))
}
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, E>
where
V: Visitor<'de>,
{
visitor.visit_none()
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
bytes byte_buf unit unit_struct newtype_struct seq tuple
tuple_struct map struct enum identifier ignored_any
}
}
let deserializer = MissingFieldDeserializer(field, PhantomData);
Deserialize::deserialize(deserializer)
}
#[cfg(any(feature = "std", feature = "alloc"))]
pub fn borrow_cow_str<'de: 'a, 'a, D>(deserializer: D) -> Result<Cow<'a, str>, D::Error>
where
D: Deserializer<'de>,
{
struct CowStrVisitor;
impl<'a> Visitor<'a> for CowStrVisitor {
type Value = Cow<'a, str>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a string")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Owned(v.to_owned()))
}
fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Borrowed(v))
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Owned(v))
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
match str::from_utf8(v) {
Ok(s) => Ok(Cow::Owned(s.to_owned())),
Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
}
}
fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
where
E: Error,
{
match str::from_utf8(v) {
Ok(s) => Ok(Cow::Borrowed(s)),
Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
}
}
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
where
E: Error,
{
match String::from_utf8(v) {
Ok(s) => Ok(Cow::Owned(s)),
Err(e) => Err(Error::invalid_value(
Unexpected::Bytes(&e.into_bytes()),
&self,
)),
}
}
}
deserializer.deserialize_str(CowStrVisitor)
}
#[cfg(any(feature = "std", feature = "alloc"))]
pub fn borrow_cow_bytes<'de: 'a, 'a, D>(deserializer: D) -> Result<Cow<'a, [u8]>, D::Error>
where
D: Deserializer<'de>,
{
struct CowBytesVisitor;
impl<'a> Visitor<'a> for CowBytesVisitor {
type Value = Cow<'a, [u8]>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a byte array")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Owned(v.as_bytes().to_vec()))
}
fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Borrowed(v.as_bytes()))
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Owned(v.into_bytes()))
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Owned(v.to_vec()))
}
fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Borrowed(v))
}
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Owned(v))
}
}
deserializer.deserialize_bytes(CowBytesVisitor)
}
pub mod size_hint {
use lib::*;
pub fn from_bounds<I>(iter: &I) -> Option<usize>
where
I: Iterator,
{
helper(iter.size_hint())
}
#[inline]
pub fn cautious(hint: Option<usize>) -> usize {
cmp::min(hint.unwrap_or(0), 4096)
}
fn helper(bounds: (usize, Option<usize>)) -> Option<usize> {
match bounds {
(lower, Some(upper)) if lower == upper => Some(upper),
_ => None,
}
}
}
#[cfg(any(feature = "std", feature = "alloc"))]
mod content {
// This module is private and nothing here should be used outside of
// generated code.
//
// We will iterate on the implementation for a few releases and only have to
// worry about backward compatibility for the `untagged` and `tag` attributes
// rather than for this entire mechanism.
//
// This issue is tracking making some of this stuff public:
// https://github.com/serde-rs/serde/issues/741
use lib::*;
use super::size_hint;
use de::{
self, Deserialize, DeserializeSeed, Deserializer, EnumAccess, Expected, IgnoredAny,
MapAccess, SeqAccess, Unexpected, Visitor,
};
/// Used from generated code to buffer the contents of the Deserializer when
/// deserializing untagged enums and internally tagged enums.
///
/// Not public API. Use serde-value instead.
#[derive(Debug)]
pub enum Content<'de> {
Bool(bool),
U8(u8),
U16(u16),
U32(u32),
U64(u64),
I8(i8),
I16(i16),
I32(i32),
I64(i64),
F32(f32),
F64(f64),
Char(char),
String(String),
Str(&'de str),
ByteBuf(Vec<u8>),
Bytes(&'de [u8]),
None,
Some(Box<Content<'de>>),
Unit,
Newtype(Box<Content<'de>>),
Seq(Vec<Content<'de>>),
Map(Vec<(Content<'de>, Content<'de>)>),
}
impl<'de> Content<'de> {
pub fn as_str(&self) -> Option<&str> {
match *self {
Content::Str(x) => Some(x),
Content::String(ref x) => Some(x),
Content::Bytes(x) => str::from_utf8(x).ok(),
Content::ByteBuf(ref x) => str::from_utf8(x).ok(),
_ => None,
}
}
#[cold]
fn unexpected(&self) -> Unexpected {
match *self {
Content::Bool(b) => Unexpected::Bool(b),
Content::U8(n) => Unexpected::Unsigned(n as u64),
Content::U16(n) => Unexpected::Unsigned(n as u64),
Content::U32(n) => Unexpected::Unsigned(n as u64),
Content::U64(n) => Unexpected::Unsigned(n),
Content::I8(n) => Unexpected::Signed(n as i64),
Content::I16(n) => Unexpected::Signed(n as i64),
Content::I32(n) => Unexpected::Signed(n as i64),
Content::I64(n) => Unexpected::Signed(n),
Content::F32(f) => Unexpected::Float(f as f64),
Content::F64(f) => Unexpected::Float(f),
Content::Char(c) => Unexpected::Char(c),
Content::String(ref s) => Unexpected::Str(s),
Content::Str(s) => Unexpected::Str(s),
Content::ByteBuf(ref b) => Unexpected::Bytes(b),
Content::Bytes(b) => Unexpected::Bytes(b),
Content::None | Content::Some(_) => Unexpected::Option,
Content::Unit => Unexpected::Unit,
Content::Newtype(_) => Unexpected::NewtypeStruct,
Content::Seq(_) => Unexpected::Seq,
Content::Map(_) => Unexpected::Map,
}
}
}
impl<'de> Deserialize<'de> for Content<'de> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
// Untagged and internally tagged enums are only supported in
// self-describing formats.
let visitor = ContentVisitor { value: PhantomData };
deserializer.deserialize_any(visitor)
}
}
struct ContentVisitor<'de> {
value: PhantomData<Content<'de>>,
}
impl<'de> ContentVisitor<'de> {
fn new() -> Self {
ContentVisitor { value: PhantomData }
}
}
impl<'de> Visitor<'de> for ContentVisitor<'de> {
type Value = Content<'de>;
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("any value")
}
fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F>
where
F: de::Error,
{
Ok(Content::Bool(value))
}
fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F>
where
F: de::Error,
{
Ok(Content::I8(value))
}
fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F>
where
F: de::Error,
{
Ok(Content::I16(value))
}
fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F>
where
F: de::Error,
{
Ok(Content::I32(value))
}
fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F>
where
F: de::Error,
{
Ok(Content::I64(value))
}
fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F>
where
F: de::Error,
{
Ok(Content::U8(value))
}
fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F>
where
F: de::Error,
{
Ok(Content::U16(value))
}
fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F>
where
F: de::Error,
{
Ok(Content::U32(value))
}
fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F>
where
F: de::Error,
{
Ok(Content::U64(value))
}
fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F>
where
F: de::Error,
{
Ok(Content::F32(value))
}
fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F>
where
F: de::Error,
{
Ok(Content::F64(value))
}
fn visit_char<F>(self, value: char) -> Result<Self::Value, F>
where
F: de::Error,
{
Ok(Content::Char(value))
}
fn visit_str<F>(self, value: &str) -> Result<Self::Value, F>
where
F: de::Error,
{
Ok(Content::String(value.into()))
}
fn visit_borrowed_str<F>(self, value: &'de str) -> Result<Self::Value, F>
where
F: de::Error,
{
Ok(Content::Str(value))
}
fn visit_string<F>(self, value: String) -> Result<Self::Value, F>
where
F: de::Error,
{
Ok(Content::String(value))
}
fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F>
where
F: de::Error,
{
Ok(Content::ByteBuf(value.into()))
}
fn visit_borrowed_bytes<F>(self, value: &'de [u8]) -> Result<Self::Value, F>
where
F: de::Error,
{
Ok(Content::Bytes(value))
}
fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F>
where
F: de::Error,
{
Ok(Content::ByteBuf(value))
}
fn visit_unit<F>(self) -> Result<Self::Value, F>
where
F: de::Error,
{
Ok(Content::Unit)
}
fn visit_none<F>(self) -> Result<Self::Value, F>
where
F: de::Error,
{
Ok(Content::None)
}
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
Deserialize::deserialize(deserializer).map(|v| Content::Some(Box::new(v)))
}
fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
Deserialize::deserialize(deserializer).map(|v| Content::Newtype(Box::new(v)))
}
fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
where
V: SeqAccess<'de>,
{
let mut vec = Vec::with_capacity(size_hint::cautious(visitor.size_hint()));
while let Some(e) = try!(visitor.next_element()) {
vec.push(e);
}
Ok(Content::Seq(vec))
}
fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
where
V: MapAccess<'de>,
{
let mut vec = Vec::with_capacity(size_hint::cautious(visitor.size_hint()));
while let Some(kv) = try!(visitor.next_entry()) {
vec.push(kv);
}
Ok(Content::Map(vec))
}
fn visit_enum<V>(self, _visitor: V) -> Result<Self::Value, V::Error>
where
V: EnumAccess<'de>,
{
Err(de::Error::custom(
"untagged and internally tagged enums do not support enum input",
))
}
}
/// This is the type of the map keys in an internally tagged enum.
///
/// Not public API.
pub enum TagOrContent<'de> {
Tag,
Content(Content<'de>),
}
struct TagOrContentVisitor<'de> {
name: &'static str,
value: PhantomData<TagOrContent<'de>>,
}
impl<'de> TagOrContentVisitor<'de> {
fn new(name: &'static str) -> Self {
TagOrContentVisitor {
name: name,
value: PhantomData,
}
}
}
impl<'de> DeserializeSeed<'de> for TagOrContentVisitor<'de> {
type Value = TagOrContent<'de>;
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
// Internally tagged enums are only supported in self-describing
// formats.
deserializer.deserialize_any(self)
}
}
impl<'de> Visitor<'de> for TagOrContentVisitor<'de> {
type Value = TagOrContent<'de>;
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "a type tag `{}` or any other value", self.name)
}
fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F>
where
F: de::Error,
{
ContentVisitor::new()
.visit_bool(value)
.map(TagOrContent::Content)
}
fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F>
where
F: de::Error,
{
ContentVisitor::new()
.visit_i8(value)
.map(TagOrContent::Content)
}
fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F>
where
F: de::Error,
{
ContentVisitor::new()
.visit_i16(value)
.map(TagOrContent::Content)
}
fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F>
where
F: de::Error,
{
ContentVisitor::new()
.visit_i32(value)
.map(TagOrContent::Content)
}
fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F>
where
F: de::Error,
{
ContentVisitor::new()
.visit_i64(value)
.map(TagOrContent::Content)
}
fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F>
where
F: de::Error,
{
ContentVisitor::new()
.visit_u8(value)
.map(TagOrContent::Content)
}
fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F>
where
F: de::Error,
{
ContentVisitor::new()
.visit_u16(value)
.map(TagOrContent::Content)
}
fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F>
where
F: de::Error,
{
ContentVisitor::new()
.visit_u32(value)
.map(TagOrContent::Content)
}
fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F>
where
F: de::Error,
{
ContentVisitor::new()
.visit_u64(value)
.map(TagOrContent::Content)
}
fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F>
where
F: de::Error,
{
ContentVisitor::new()
.visit_f32(value)
.map(TagOrContent::Content)
}
fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F>
where
F: de::Error,
{
ContentVisitor::new()
.visit_f64(value)
.map(TagOrContent::Content)
}
fn visit_char<F>(self, value: char) -> Result<Self::Value, F>
where
F: de::Error,
{
ContentVisitor::new()
.visit_char(value)
.map(TagOrContent::Content)
}
fn visit_str<F>(self, value: &str) -> Result<Self::Value, F>
where
F: de::Error,
{
if value == self.name {
Ok(TagOrContent::Tag)
} else {
ContentVisitor::new()
.visit_str(value)
.map(TagOrContent::Content)
}
}
fn visit_borrowed_str<F>(self, value: &'de str) -> Result<Self::Value, F>
where
F: de::Error,
{
if value == self.name {
Ok(TagOrContent::Tag)
} else {
ContentVisitor::new()
.visit_borrowed_str(value)
.map(TagOrContent::Content)
}
}
fn visit_string<F>(self, value: String) -> Result<Self::Value, F>
where
F: de::Error,
{
if value == self.name {
Ok(TagOrContent::Tag)
} else {
ContentVisitor::new()
.visit_string(value)
.map(TagOrContent::Content)
}
}
fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F>
where
F: de::Error,
{
if value == self.name.as_bytes() {
Ok(TagOrContent::Tag)
} else {
ContentVisitor::new()
.visit_bytes(value)
.map(TagOrContent::Content)
}
}
fn visit_borrowed_bytes<F>(self, value: &'de [u8]) -> Result<Self::Value, F>
where
F: de::Error,
{
if value == self.name.as_bytes() {
Ok(TagOrContent::Tag)
} else {
ContentVisitor::new()
.visit_borrowed_bytes(value)
.map(TagOrContent::Content)
}
}
fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F>
where
F: de::Error,
{
if value == self.name.as_bytes() {
Ok(TagOrContent::Tag)
} else {
ContentVisitor::new()
.visit_byte_buf(value)
.map(TagOrContent::Content)
}
}
fn visit_unit<F>(self) -> Result<Self::Value, F>
where
F: de::Error,
{
ContentVisitor::new()
.visit_unit()
.map(TagOrContent::Content)
}
fn visit_none<F>(self) -> Result<Self::Value, F>
where
F: de::Error,
{
ContentVisitor::new()
.visit_none()
.map(TagOrContent::Content)
}
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
ContentVisitor::new()
.visit_some(deserializer)
.map(TagOrContent::Content)
}
fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
ContentVisitor::new()
.visit_newtype_struct(deserializer)
.map(TagOrContent::Content)
}
fn visit_seq<V>(self, visitor: V) -> Result<Self::Value, V::Error>
where
V: SeqAccess<'de>,
{
ContentVisitor::new()
.visit_seq(visitor)
.map(TagOrContent::Content)
}
fn visit_map<V>(self, visitor: V) -> Result<Self::Value, V::Error>
where
V: MapAccess<'de>,
{
ContentVisitor::new()
.visit_map(visitor)
.map(TagOrContent::Content)
}
fn visit_enum<V>(self, visitor: V) -> Result<Self::Value, V::Error>
where
V: EnumAccess<'de>,
{
ContentVisitor::new()
.visit_enum(visitor)
.map(TagOrContent::Content)
}
}
/// Used by generated code to deserialize an internally tagged enum.
///
/// Not public API.
pub struct TaggedContent<'de, T> {
pub tag: T,
pub content: Content<'de>,
}
/// Not public API.
pub struct TaggedContentVisitor<'de, T> {
tag_name: &'static str,
value: PhantomData<TaggedContent<'de, T>>,
}
impl<'de, T> TaggedContentVisitor<'de, T> {
/// Visitor for the content of an internally tagged enum with the given
/// tag name.
pub fn new(name: &'static str) -> Self {
TaggedContentVisitor {
tag_name: name,
value: PhantomData,
}
}
}
impl<'de, T> DeserializeSeed<'de> for TaggedContentVisitor<'de, T>
where
T: Deserialize<'de>,
{
type Value = TaggedContent<'de, T>;
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
// Internally tagged enums are only supported in self-describing
// formats.
deserializer.deserialize_any(self)
}
}
impl<'de, T> Visitor<'de> for TaggedContentVisitor<'de, T>
where
T: Deserialize<'de>,
{
type Value = TaggedContent<'de, T>;
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("internally tagged enum")
}
fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
where
S: SeqAccess<'de>,
{
let tag = match try!(seq.next_element()) {
Some(tag) => tag,
None => {
return Err(de::Error::missing_field(self.tag_name));
}
};
let rest = de::value::SeqAccessDeserializer::new(seq);
Ok(TaggedContent {
tag: tag,
content: try!(Content::deserialize(rest)),
})
}
fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
where
M: MapAccess<'de>,
{
let mut tag = None;
let mut vec = Vec::with_capacity(size_hint::cautious(map.size_hint()));
while let Some(k) = try!(map.next_key_seed(TagOrContentVisitor::new(self.tag_name))) {
match k {
TagOrContent::Tag => {
if tag.is_some() {
return Err(de::Error::duplicate_field(self.tag_name));
}
tag = Some(try!(map.next_value()));
}
TagOrContent::Content(k) => {
let v = try!(map.next_value());
vec.push((k, v));
}
}
}
match tag {
None => Err(de::Error::missing_field(self.tag_name)),
Some(tag) => Ok(TaggedContent {
tag: tag,
content: Content::Map(vec),
}),
}
}
}
/// Used by generated code to deserialize an adjacently tagged enum.
///
/// Not public API.
pub enum TagOrContentField {
Tag,
Content,
}
/// Not public API.
pub struct TagOrContentFieldVisitor {
pub tag: &'static str,
pub content: &'static str,
}
impl<'de> DeserializeSeed<'de> for TagOrContentFieldVisitor {
type Value = TagOrContentField;
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(self)
}
}
impl<'de> Visitor<'de> for TagOrContentFieldVisitor {
type Value = TagOrContentField;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "{:?} or {:?}", self.tag, self.content)
}
fn visit_str<E>(self, field: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
if field == self.tag {
Ok(TagOrContentField::Tag)
} else if field == self.content {
Ok(TagOrContentField::Content)
} else {
Err(de::Error::invalid_value(Unexpected::Str(field), &self))
}
}
}
/// Used by generated code to deserialize an adjacently tagged enum when
/// ignoring unrelated fields is allowed.
///
/// Not public API.
pub enum TagContentOtherField {
Tag,
Content,
Other,
}
/// Not public API.
pub struct TagContentOtherFieldVisitor {
pub tag: &'static str,
pub content: &'static str,
}
impl<'de> DeserializeSeed<'de> for TagContentOtherFieldVisitor {
type Value = TagContentOtherField;
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(self)
}
}
impl<'de> Visitor<'de> for TagContentOtherFieldVisitor {
type Value = TagContentOtherField;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(
formatter,
"{:?}, {:?}, or other ignored fields",
self.tag, self.content
)
}
fn visit_str<E>(self, field: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
if field == self.tag {
Ok(TagContentOtherField::Tag)
} else if field == self.content {
Ok(TagContentOtherField::Content)
} else {
Ok(TagContentOtherField::Other)
}
}
}
/// Not public API
pub struct ContentDeserializer<'de, E> {
content: Content<'de>,
err: PhantomData<E>,
}
impl<'de, E> ContentDeserializer<'de, E>
where
E: de::Error,
{
#[cold]
fn invalid_type(self, exp: &Expected) -> E {
de::Error::invalid_type(self.content.unexpected(), exp)
}
fn deserialize_integer<V>(self, visitor: V) -> Result<V::Value, E>
where
V: Visitor<'de>,
{
match self.content {
Content::U8(v) => visitor.visit_u8(v),
Content::U16(v) => visitor.visit_u16(v),
Content::U32(v) => visitor.visit_u32(v),
Content::U64(v) => visitor.visit_u64(v),
Content::I8(v) => visitor.visit_i8(v),
Content::I16(v) => visitor.visit_i16(v),
Content::I32(v) => visitor.visit_i32(v),
Content::I64(v) => visitor.visit_i64(v),
_ => Err(self.invalid_type(&visitor)),
}
}
}
fn visit_content_seq<'de, V, E>(content: Vec<Content<'de>>, visitor: V) -> Result<V::Value, E>
where
V: Visitor<'de>,
E: de::Error,
{
let seq = content.into_iter().map(ContentDeserializer::new);
let mut seq_visitor = de::value::SeqDeserializer::new(seq);
let value = try!(visitor.visit_seq(&mut seq_visitor));
try!(seq_visitor.end());
Ok(value)
}
fn visit_content_map<'de, V, E>(
content: Vec<(Content<'de>, Content<'de>)>,
visitor: V,
) -> Result<V::Value, E>
where
V: Visitor<'de>,
E: de::Error,
{
let map = content
.into_iter()
.map(|(k, v)| (ContentDeserializer::new(k), ContentDeserializer::new(v)));
let mut map_visitor = de::value::MapDeserializer::new(map);
let value = try!(visitor.visit_map(&mut map_visitor));
try!(map_visitor.end());
Ok(value)
}
/// Used when deserializing an internally tagged enum because the content
/// will be used exactly once.
impl<'de, E> Deserializer<'de> for ContentDeserializer<'de, E>
where
E: de::Error,
{
type Error = E;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match self.content {
Content::Bool(v) => visitor.visit_bool(v),
Content::U8(v) => visitor.visit_u8(v),
Content::U16(v) => visitor.visit_u16(v),
Content::U32(v) => visitor.visit_u32(v),
Content::U64(v) => visitor.visit_u64(v),
Content::I8(v) => visitor.visit_i8(v),
Content::I16(v) => visitor.visit_i16(v),
Content::I32(v) => visitor.visit_i32(v),
Content::I64(v) => visitor.visit_i64(v),
Content::F32(v) => visitor.visit_f32(v),
Content::F64(v) => visitor.visit_f64(v),
Content::Char(v) => visitor.visit_char(v),
Content::String(v) => visitor.visit_string(v),
Content::Str(v) => visitor.visit_borrowed_str(v),
Content::ByteBuf(v) => visitor.visit_byte_buf(v),
Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
Content::Unit => visitor.visit_unit(),
Content::None => visitor.visit_none(),
Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)),
Content::Newtype(v) => visitor.visit_newtype_struct(ContentDeserializer::new(*v)),
Content::Seq(v) => visit_content_seq(v, visitor),
Content::Map(v) => visit_content_map(v, visitor),
}
}
fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match self.content {
Content::Bool(v) => visitor.visit_bool(v),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match self.content {
Content::F32(v) => visitor.visit_f32(v),
Content::F64(v) => visitor.visit_f64(v),
Content::U64(v) => visitor.visit_u64(v),
Content::I64(v) => visitor.visit_i64(v),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match self.content {
Content::F64(v) => visitor.visit_f64(v),
Content::U64(v) => visitor.visit_u64(v),
Content::I64(v) => visitor.visit_i64(v),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match self.content {
Content::Char(v) => visitor.visit_char(v),
Content::String(v) => visitor.visit_string(v),
Content::Str(v) => visitor.visit_borrowed_str(v),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_string(visitor)
}
fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match self.content {
Content::String(v) => visitor.visit_string(v),
Content::Str(v) => visitor.visit_borrowed_str(v),
Content::ByteBuf(v) => visitor.visit_byte_buf(v),
Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_byte_buf(visitor)
}
fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match self.content {
Content::String(v) => visitor.visit_string(v),
Content::Str(v) => visitor.visit_borrowed_str(v),
Content::ByteBuf(v) => visitor.visit_byte_buf(v),
Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
Content::Seq(v) => visit_content_seq(v, visitor),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match self.content {
Content::None => visitor.visit_none(),
Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)),
Content::Unit => visitor.visit_unit(),
_ => visitor.visit_some(self),
}
}
fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match self.content {
Content::Unit => visitor.visit_unit(),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_unit_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match self.content {
// As a special case, allow deserializing untagged newtype
// variant containing unit struct.
//
// #[derive(Deserialize)]
// struct Info;
//
// #[derive(Deserialize)]
// #[serde(tag = "topic")]
// enum Message {
// Info(Info),
// }
//
// We want {"topic":"Info"} to deserialize even though
// ordinarily unit structs do not deserialize from empty map.
Content::Map(ref v) if v.is_empty() => visitor.visit_unit(),
_ => self.deserialize_any(visitor),
}
}
fn deserialize_newtype_struct<V>(
self,
_name: &str,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match self.content {
Content::Newtype(v) => visitor.visit_newtype_struct(ContentDeserializer::new(*v)),
_ => visitor.visit_newtype_struct(self),
}
}
fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match self.content {
Content::Seq(v) => visit_content_seq(v, visitor),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_seq(visitor)
}
fn deserialize_tuple_struct<V>(
self,
_name: &'static str,
_len: usize,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_seq(visitor)
}
fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match self.content {
Content::Map(v) => visit_content_map(v, visitor),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_struct<V>(
self,
_name: &'static str,
_fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match self.content {
Content::Seq(v) => visit_content_seq(v, visitor),
Content::Map(v) => visit_content_map(v, visitor),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_enum<V>(
self,
_name: &str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
let (variant, value) = match self.content {
Content::Map(value) => {
let mut iter = value.into_iter();
let (variant, value) = match iter.next() {
Some(v) => v,
None => {
return Err(de::Error::invalid_value(
de::Unexpected::Map,
&"map with a single key",
));
}
};
// enums are encoded in json as maps with a single key:value pair
if iter.next().is_some() {
return Err(de::Error::invalid_value(
de::Unexpected::Map,
&"map with a single key",
));
}
(variant, Some(value))
}
s @ Content::String(_) | s @ Content::Str(_) => (s, None),
other => {
return Err(de::Error::invalid_type(
other.unexpected(),
&"string or map",
));
}
};
visitor.visit_enum(EnumDeserializer::new(variant, value))
}
fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match self.content {
Content::String(v) => visitor.visit_string(v),
Content::Str(v) => visitor.visit_borrowed_str(v),
Content::ByteBuf(v) => visitor.visit_byte_buf(v),
Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
Content::U8(v) => visitor.visit_u8(v),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
drop(self);
visitor.visit_unit()
}
}
impl<'de, E> ContentDeserializer<'de, E> {
/// private API, don't use
pub fn new(content: Content<'de>) -> Self {
ContentDeserializer {
content: content,
err: PhantomData,
}
}
}
pub struct EnumDeserializer<'de, E>
where
E: de::Error,
{
variant: Content<'de>,
value: Option<Content<'de>>,
err: PhantomData<E>,
}
impl<'de, E> EnumDeserializer<'de, E>
where
E: de::Error,
{
pub fn new(variant: Content<'de>, value: Option<Content<'de>>) -> EnumDeserializer<'de, E> {
EnumDeserializer {
variant: variant,
value: value,
err: PhantomData,
}
}
}
impl<'de, E> de::EnumAccess<'de> for EnumDeserializer<'de, E>
where
E: de::Error,
{
type Error = E;
type Variant = VariantDeserializer<'de, Self::Error>;
fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), E>
where
V: de::DeserializeSeed<'de>,
{
let visitor = VariantDeserializer {
value: self.value,
err: PhantomData,
};
seed.deserialize(ContentDeserializer::new(self.variant))
.map(|v| (v, visitor))
}
}
pub struct VariantDeserializer<'de, E>
where
E: de::Error,
{
value: Option<Content<'de>>,
err: PhantomData<E>,
}
impl<'de, E> de::VariantAccess<'de> for VariantDeserializer<'de, E>
where
E: de::Error,
{
type Error = E;
fn unit_variant(self) -> Result<(), E> {
match self.value {
Some(value) => de::Deserialize::deserialize(ContentDeserializer::new(value)),
None => Ok(()),
}
}
fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, E>
where
T: de::DeserializeSeed<'de>,
{
match self.value {
Some(value) => seed.deserialize(ContentDeserializer::new(value)),
None => Err(de::Error::invalid_type(
de::Unexpected::UnitVariant,
&"newtype variant",
)),
}
}
fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
match self.value {
Some(Content::Seq(v)) => {
de::Deserializer::deserialize_any(SeqDeserializer::new(v), visitor)
}
Some(other) => Err(de::Error::invalid_type(
other.unexpected(),
&"tuple variant",
)),
None => Err(de::Error::invalid_type(
de::Unexpected::UnitVariant,
&"tuple variant",
)),
}
}
fn struct_variant<V>(
self,
_fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
match self.value {
Some(Content::Map(v)) => {
de::Deserializer::deserialize_any(MapDeserializer::new(v), visitor)
}
Some(Content::Seq(v)) => {
de::Deserializer::deserialize_any(SeqDeserializer::new(v), visitor)
}
Some(other) => Err(de::Error::invalid_type(
other.unexpected(),
&"struct variant",
)),
_ => Err(de::Error::invalid_type(
de::Unexpected::UnitVariant,
&"struct variant",
)),
}
}
}
struct SeqDeserializer<'de, E>
where
E: de::Error,
{
iter: <Vec<Content<'de>> as IntoIterator>::IntoIter,
err: PhantomData<E>,
}
impl<'de, E> SeqDeserializer<'de, E>
where
E: de::Error,
{
fn new(vec: Vec<Content<'de>>) -> Self {
SeqDeserializer {
iter: vec.into_iter(),
err: PhantomData,
}
}
}
impl<'de, E> de::Deserializer<'de> for SeqDeserializer<'de, E>
where
E: de::Error,
{
type Error = E;
#[inline]
fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
let len = self.iter.len();
if len == 0 {
visitor.visit_unit()
} else {
let ret = try!(visitor.visit_seq(&mut self));
let remaining = self.iter.len();
if remaining == 0 {
Ok(ret)
} else {
Err(de::Error::invalid_length(len, &"fewer elements in array"))
}
}
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
bytes byte_buf option unit unit_struct newtype_struct seq tuple
tuple_struct map struct enum identifier ignored_any
}
}
impl<'de, E> de::SeqAccess<'de> for SeqDeserializer<'de, E>
where
E: de::Error,
{
type Error = E;
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
match self.iter.next() {
Some(value) => seed.deserialize(ContentDeserializer::new(value)).map(Some),
None => Ok(None),
}
}
fn size_hint(&self) -> Option<usize> {
size_hint::from_bounds(&self.iter)
}
}
struct MapDeserializer<'de, E>
where
E: de::Error,
{
iter: <Vec<(Content<'de>, Content<'de>)> as IntoIterator>::IntoIter,
value: Option<Content<'de>>,
err: PhantomData<E>,
}
impl<'de, E> MapDeserializer<'de, E>
where
E: de::Error,
{
fn new(map: Vec<(Content<'de>, Content<'de>)>) -> Self {
MapDeserializer {
iter: map.into_iter(),
value: None,
err: PhantomData,
}
}
}
impl<'de, E> de::MapAccess<'de> for MapDeserializer<'de, E>
where
E: de::Error,
{
type Error = E;
fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
match self.iter.next() {
Some((key, value)) => {
self.value = Some(value);
seed.deserialize(ContentDeserializer::new(key)).map(Some)
}
None => Ok(None),
}
}
fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
match self.value.take() {
Some(value) => seed.deserialize(ContentDeserializer::new(value)),
None => Err(de::Error::custom("value is missing")),
}
}
fn size_hint(&self) -> Option<usize> {
size_hint::from_bounds(&self.iter)
}
}
impl<'de, E> de::Deserializer<'de> for MapDeserializer<'de, E>
where
E: de::Error,
{
type Error = E;
#[inline]
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
visitor.visit_map(self)
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
bytes byte_buf option unit unit_struct newtype_struct seq tuple
tuple_struct map struct enum identifier ignored_any
}
}
/// Not public API.
pub struct ContentRefDeserializer<'a, 'de: 'a, E> {
content: &'a Content<'de>,
err: PhantomData<E>,
}
impl<'a, 'de, E> ContentRefDeserializer<'a, 'de, E>
where
E: de::Error,
{
#[cold]
fn invalid_type(self, exp: &Expected) -> E {
de::Error::invalid_type(self.content.unexpected(), exp)
}
fn deserialize_integer<V>(self, visitor: V) -> Result<V::Value, E>
where
V: Visitor<'de>,
{
match *self.content {
Content::U8(v) => visitor.visit_u8(v),
Content::U16(v) => visitor.visit_u16(v),
Content::U32(v) => visitor.visit_u32(v),
Content::U64(v) => visitor.visit_u64(v),
Content::I8(v) => visitor.visit_i8(v),
Content::I16(v) => visitor.visit_i16(v),
Content::I32(v) => visitor.visit_i32(v),
Content::I64(v) => visitor.visit_i64(v),
_ => Err(self.invalid_type(&visitor)),
}
}
}
fn visit_content_seq_ref<'a, 'de, V, E>(
content: &'a [Content<'de>],
visitor: V,
) -> Result<V::Value, E>
where
V: Visitor<'de>,
E: de::Error,
{
let seq = content.iter().map(ContentRefDeserializer::new);
let mut seq_visitor = de::value::SeqDeserializer::new(seq);
let value = try!(visitor.visit_seq(&mut seq_visitor));
try!(seq_visitor.end());
Ok(value)
}
fn visit_content_map_ref<'a, 'de, V, E>(
content: &'a [(Content<'de>, Content<'de>)],
visitor: V,
) -> Result<V::Value, E>
where
V: Visitor<'de>,
E: de::Error,
{
let map = content.iter().map(|&(ref k, ref v)| {
(
ContentRefDeserializer::new(k),
ContentRefDeserializer::new(v),
)
});
let mut map_visitor = de::value::MapDeserializer::new(map);
let value = try!(visitor.visit_map(&mut map_visitor));
try!(map_visitor.end());
Ok(value)
}
/// Used when deserializing an untagged enum because the content may need
/// to be used more than once.
impl<'de, 'a, E> Deserializer<'de> for ContentRefDeserializer<'a, 'de, E>
where
E: de::Error,
{
type Error = E;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, E>
where
V: Visitor<'de>,
{
match *self.content {
Content::Bool(v) => visitor.visit_bool(v),
Content::U8(v) => visitor.visit_u8(v),
Content::U16(v) => visitor.visit_u16(v),
Content::U32(v) => visitor.visit_u32(v),
Content::U64(v) => visitor.visit_u64(v),
Content::I8(v) => visitor.visit_i8(v),
Content::I16(v) => visitor.visit_i16(v),
Content::I32(v) => visitor.visit_i32(v),
Content::I64(v) => visitor.visit_i64(v),
Content::F32(v) => visitor.visit_f32(v),
Content::F64(v) => visitor.visit_f64(v),
Content::Char(v) => visitor.visit_char(v),
Content::String(ref v) => visitor.visit_str(v),
Content::Str(v) => visitor.visit_borrowed_str(v),
Content::ByteBuf(ref v) => visitor.visit_bytes(v),
Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
Content::Unit => visitor.visit_unit(),
Content::None => visitor.visit_none(),
Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)),
Content::Newtype(ref v) => {
visitor.visit_newtype_struct(ContentRefDeserializer::new(v))
}
Content::Seq(ref v) => visit_content_seq_ref(v, visitor),
Content::Map(ref v) => visit_content_map_ref(v, visitor),
}
}
fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match *self.content {
Content::Bool(v) => visitor.visit_bool(v),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match *self.content {
Content::F32(v) => visitor.visit_f32(v),
Content::F64(v) => visitor.visit_f64(v),
Content::U64(v) => visitor.visit_u64(v),
Content::I64(v) => visitor.visit_i64(v),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match *self.content {
Content::F64(v) => visitor.visit_f64(v),
Content::U64(v) => visitor.visit_u64(v),
Content::I64(v) => visitor.visit_i64(v),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match *self.content {
Content::Char(v) => visitor.visit_char(v),
Content::String(ref v) => visitor.visit_str(v),
Content::Str(v) => visitor.visit_borrowed_str(v),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match *self.content {
Content::String(ref v) => visitor.visit_str(v),
Content::Str(v) => visitor.visit_borrowed_str(v),
Content::ByteBuf(ref v) => visitor.visit_bytes(v),
Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_str(visitor)
}
fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match *self.content {
Content::String(ref v) => visitor.visit_str(v),
Content::Str(v) => visitor.visit_borrowed_str(v),
Content::ByteBuf(ref v) => visitor.visit_bytes(v),
Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
Content::Seq(ref v) => visit_content_seq_ref(v, visitor),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_bytes(visitor)
}
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, E>
where
V: Visitor<'de>,
{
match *self.content {
Content::None => visitor.visit_none(),
Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)),
Content::Unit => visitor.visit_unit(),
_ => visitor.visit_some(self),
}
}
fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match *self.content {
Content::Unit => visitor.visit_unit(),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_unit_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_unit(visitor)
}
fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, E>
where
V: Visitor<'de>,
{
match *self.content {
Content::Newtype(ref v) => {
visitor.visit_newtype_struct(ContentRefDeserializer::new(v))
}
_ => visitor.visit_newtype_struct(self),
}
}
fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match *self.content {
Content::Seq(ref v) => visit_content_seq_ref(v, visitor),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_seq(visitor)
}
fn deserialize_tuple_struct<V>(
self,
_name: &'static str,
_len: usize,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_seq(visitor)
}
fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match *self.content {
Content::Map(ref v) => visit_content_map_ref(v, visitor),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_struct<V>(
self,
_name: &'static str,
_fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match *self.content {
Content::Seq(ref v) => visit_content_seq_ref(v, visitor),
Content::Map(ref v) => visit_content_map_ref(v, visitor),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_enum<V>(
self,
_name: &str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
let (variant, value) = match *self.content {
Content::Map(ref value) => {
let mut iter = value.iter();
let &(ref variant, ref value) = match iter.next() {
Some(v) => v,
None => {
return Err(de::Error::invalid_value(
de::Unexpected::Map,
&"map with a single key",
));
}
};
// enums are encoded in json as maps with a single key:value pair
if iter.next().is_some() {
return Err(de::Error::invalid_value(
de::Unexpected::Map,
&"map with a single key",
));
}
(variant, Some(value))
}
ref s @ Content::String(_) | ref s @ Content::Str(_) => (s, None),
ref other => {
return Err(de::Error::invalid_type(
other.unexpected(),
&"string or map",
));
}
};
visitor.visit_enum(EnumRefDeserializer {
variant: variant,
value: value,
err: PhantomData,
})
}
fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match *self.content {
Content::String(ref v) => visitor.visit_str(v),
Content::Str(v) => visitor.visit_borrowed_str(v),
Content::ByteBuf(ref v) => visitor.visit_bytes(v),
Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
Content::U8(v) => visitor.visit_u8(v),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_unit()
}
}
impl<'a, 'de, E> ContentRefDeserializer<'a, 'de, E> {
/// private API, don't use
pub fn new(content: &'a Content<'de>) -> Self {
ContentRefDeserializer {
content: content,
err: PhantomData,
}
}
}
struct EnumRefDeserializer<'a, 'de: 'a, E>
where
E: de::Error,
{
variant: &'a Content<'de>,
value: Option<&'a Content<'de>>,
err: PhantomData<E>,
}
impl<'de, 'a, E> de::EnumAccess<'de> for EnumRefDeserializer<'a, 'de, E>
where
E: de::Error,
{
type Error = E;
type Variant = VariantRefDeserializer<'a, 'de, Self::Error>;
fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
where
V: de::DeserializeSeed<'de>,
{
let visitor = VariantRefDeserializer {
value: self.value,
err: PhantomData,
};
seed.deserialize(ContentRefDeserializer::new(self.variant))
.map(|v| (v, visitor))
}
}
struct VariantRefDeserializer<'a, 'de: 'a, E>
where
E: de::Error,
{
value: Option<&'a Content<'de>>,
err: PhantomData<E>,
}
impl<'de, 'a, E> de::VariantAccess<'de> for VariantRefDeserializer<'a, 'de, E>
where
E: de::Error,
{
type Error = E;
fn unit_variant(self) -> Result<(), E> {
match self.value {
Some(value) => de::Deserialize::deserialize(ContentRefDeserializer::new(value)),
None => Ok(()),
}
}
fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, E>
where
T: de::DeserializeSeed<'de>,
{
match self.value {
Some(value) => seed.deserialize(ContentRefDeserializer::new(value)),
None => Err(de::Error::invalid_type(
de::Unexpected::UnitVariant,
&"newtype variant",
)),
}
}
fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
match self.value {
Some(&Content::Seq(ref v)) => {
de::Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor)
}
Some(other) => Err(de::Error::invalid_type(
other.unexpected(),
&"tuple variant",
)),
None => Err(de::Error::invalid_type(
de::Unexpected::UnitVariant,
&"tuple variant",
)),
}
}
fn struct_variant<V>(
self,
_fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
match self.value {
Some(&Content::Map(ref v)) => {
de::Deserializer::deserialize_any(MapRefDeserializer::new(v), visitor)
}
Some(&Content::Seq(ref v)) => {
de::Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor)
}
Some(other) => Err(de::Error::invalid_type(
other.unexpected(),
&"struct variant",
)),
_ => Err(de::Error::invalid_type(
de::Unexpected::UnitVariant,
&"struct variant",
)),
}
}
}
struct SeqRefDeserializer<'a, 'de: 'a, E>
where
E: de::Error,
{
iter: <&'a [Content<'de>] as IntoIterator>::IntoIter,
err: PhantomData<E>,
}
impl<'a, 'de, E> SeqRefDeserializer<'a, 'de, E>
where
E: de::Error,
{
fn new(slice: &'a [Content<'de>]) -> Self {
SeqRefDeserializer {
iter: slice.iter(),
err: PhantomData,
}
}
}
impl<'de, 'a, E> de::Deserializer<'de> for SeqRefDeserializer<'a, 'de, E>
where
E: de::Error,
{
type Error = E;
#[inline]
fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
let len = self.iter.len();
if len == 0 {
visitor.visit_unit()
} else {
let ret = try!(visitor.visit_seq(&mut self));
let remaining = self.iter.len();
if remaining == 0 {
Ok(ret)
} else {
Err(de::Error::invalid_length(len, &"fewer elements in array"))
}
}
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
bytes byte_buf option unit unit_struct newtype_struct seq tuple
tuple_struct map struct enum identifier ignored_any
}
}
impl<'de, 'a, E> de::SeqAccess<'de> for SeqRefDeserializer<'a, 'de, E>
where
E: de::Error,
{
type Error = E;
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
match self.iter.next() {
Some(value) => seed
.deserialize(ContentRefDeserializer::new(value))
.map(Some),
None => Ok(None),
}
}
fn size_hint(&self) -> Option<usize> {
size_hint::from_bounds(&self.iter)
}
}
struct MapRefDeserializer<'a, 'de: 'a, E>
where
E: de::Error,
{
iter: <&'a [(Content<'de>, Content<'de>)] as IntoIterator>::IntoIter,
value: Option<&'a Content<'de>>,
err: PhantomData<E>,
}
impl<'a, 'de, E> MapRefDeserializer<'a, 'de, E>
where
E: de::Error,
{
fn new(map: &'a [(Content<'de>, Content<'de>)]) -> Self {
MapRefDeserializer {
iter: map.iter(),
value: None,
err: PhantomData,
}
}
}
impl<'de, 'a, E> de::MapAccess<'de> for MapRefDeserializer<'a, 'de, E>
where
E: de::Error,
{
type Error = E;
fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
match self.iter.next() {
Some(&(ref key, ref value)) => {
self.value = Some(value);
seed.deserialize(ContentRefDeserializer::new(key)).map(Some)
}
None => Ok(None),
}
}
fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
match self.value.take() {
Some(value) => seed.deserialize(ContentRefDeserializer::new(value)),
None => Err(de::Error::custom("value is missing")),
}
}
fn size_hint(&self) -> Option<usize> {
size_hint::from_bounds(&self.iter)
}
}
impl<'de, 'a, E> de::Deserializer<'de> for MapRefDeserializer<'a, 'de, E>
where
E: de::Error,
{
type Error = E;
#[inline]
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
visitor.visit_map(self)
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
bytes byte_buf option unit unit_struct newtype_struct seq tuple
tuple_struct map struct enum identifier ignored_any
}
}
impl<'de, E> de::IntoDeserializer<'de, E> for ContentDeserializer<'de, E>
where
E: de::Error,
{
type Deserializer = Self;
fn into_deserializer(self) -> Self {
self
}
}
impl<'de, 'a, E> de::IntoDeserializer<'de, E> for ContentRefDeserializer<'a, 'de, E>
where
E: de::Error,
{
type Deserializer = Self;
fn into_deserializer(self) -> Self {
self
}
}
/// Visitor for deserializing an internally tagged unit variant.
///
/// Not public API.
pub struct InternallyTaggedUnitVisitor<'a> {
type_name: &'a str,
variant_name: &'a str,
}
impl<'a> InternallyTaggedUnitVisitor<'a> {
/// Not public API.
pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
InternallyTaggedUnitVisitor {
type_name: type_name,
variant_name: variant_name,
}
}
}
impl<'de, 'a> Visitor<'de> for InternallyTaggedUnitVisitor<'a> {
type Value = ();
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(
formatter,
"unit variant {}::{}",
self.type_name, self.variant_name
)
}
fn visit_seq<S>(self, _: S) -> Result<(), S::Error>
where
S: SeqAccess<'de>,
{
Ok(())
}
fn visit_map<M>(self, mut access: M) -> Result<(), M::Error>
where
M: MapAccess<'de>,
{
while let Some(_) = try!(access.next_entry::<IgnoredAny, IgnoredAny>()) {}
Ok(())
}
}
/// Visitor for deserializing an untagged unit variant.
///
/// Not public API.
pub struct UntaggedUnitVisitor<'a> {
type_name: &'a str,
variant_name: &'a str,
}
impl<'a> UntaggedUnitVisitor<'a> {
/// Not public API.
pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
UntaggedUnitVisitor {
type_name: type_name,
variant_name: variant_name,
}
}
}
impl<'de, 'a> Visitor<'de> for UntaggedUnitVisitor<'a> {
type Value = ();
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(
formatter,
"unit variant {}::{}",
self.type_name, self.variant_name
)
}
fn visit_unit<E>(self) -> Result<(), E>
where
E: de::Error,
{
Ok(())
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Like `IntoDeserializer` but also implemented for `&[u8]`. This is used for
// the newtype fallthrough case of `field_identifier`.
//
// #[derive(Deserialize)]
// #[serde(field_identifier)]
// enum F {
// A,
// B,
// Other(String), // deserialized using IdentifierDeserializer
// }
pub trait IdentifierDeserializer<'de, E: Error> {
type Deserializer: Deserializer<'de, Error = E>;
fn from(self) -> Self::Deserializer;
}
impl<'de, E> IdentifierDeserializer<'de, E> for u32
where
E: Error,
{
type Deserializer = <u32 as IntoDeserializer<'de, E>>::Deserializer;
fn from(self) -> Self::Deserializer {
self.into_deserializer()
}
}
pub struct StrDeserializer<'a, E> {
value: &'a str,
marker: PhantomData<E>,
}
impl<'a, E> IdentifierDeserializer<'a, E> for &'a str
where
E: Error,
{
type Deserializer = StrDeserializer<'a, E>;
fn from(self) -> Self::Deserializer {
StrDeserializer {
value: self,
marker: PhantomData,
}
}
}
impl<'de, 'a, E> Deserializer<'de> for StrDeserializer<'a, E>
where
E: Error,
{
type Error = E;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_str(self.value)
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
bytes byte_buf option unit unit_struct newtype_struct seq tuple
tuple_struct map struct enum identifier ignored_any
}
}
pub struct BytesDeserializer<'a, E> {
value: &'a [u8],
marker: PhantomData<E>,
}
impl<'a, E> IdentifierDeserializer<'a, E> for &'a [u8]
where
E: Error,
{
type Deserializer = BytesDeserializer<'a, E>;
fn from(self) -> Self::Deserializer {
BytesDeserializer {
value: self,
marker: PhantomData,
}
}
}
impl<'de, 'a, E> Deserializer<'de> for BytesDeserializer<'a, E>
where
E: Error,
{
type Error = E;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_bytes(self.value)
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
bytes byte_buf option unit unit_struct newtype_struct seq tuple
tuple_struct map struct enum identifier ignored_any
}
}
/// A DeserializeSeed helper for implementing deserialize_in_place Visitors.
///
/// Wraps a mutable reference and calls deserialize_in_place on it.
pub struct InPlaceSeed<'a, T: 'a>(pub &'a mut T);
impl<'a, 'de, T> DeserializeSeed<'de> for InPlaceSeed<'a, T>
where
T: Deserialize<'de>,
{
type Value = ();
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
T::deserialize_in_place(deserializer, self.0)
}
}
#[cfg(any(feature = "std", feature = "alloc"))]
pub struct FlatMapDeserializer<'a, 'de: 'a, E>(
pub &'a mut Vec<Option<(Content<'de>, Content<'de>)>>,
pub PhantomData<E>,
);
#[cfg(any(feature = "std", feature = "alloc"))]
impl<'a, 'de, E> FlatMapDeserializer<'a, 'de, E>
where
E: Error,
{
fn deserialize_other<V>() -> Result<V, E> {
Err(Error::custom("can only flatten structs and maps"))
}
}
#[cfg(any(feature = "std", feature = "alloc"))]
macro_rules! forward_to_deserialize_other {
($($func:ident ( $($arg:ty),* ))*) => {
$(
fn $func<V>(self, $(_: $arg,)* _visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
Self::deserialize_other()
}
)*
}
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<'a, 'de, E> Deserializer<'de> for FlatMapDeserializer<'a, 'de, E>
where
E: Error,
{
type Error = E;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_map(FlatInternallyTaggedAccess {
iter: self.0.iter_mut(),
pending: None,
_marker: PhantomData,
})
}
fn deserialize_enum<V>(
self,
name: &'static str,
variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
for item in self.0.iter_mut() {
// items in the vector are nulled out when used. So we can only use
// an item if it's still filled in and if the field is one we care
// about.
let use_item = match *item {
None => false,
Some((ref c, _)) => c.as_str().map_or(false, |x| variants.contains(&x)),
};
if use_item {
let (key, value) = item.take().unwrap();
return visitor.visit_enum(EnumDeserializer::new(key, Some(value)));
}
}
Err(Error::custom(format_args!(
"no variant of enum {} found in flattened data",
name
)))
}
fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_map(FlatMapAccess::new(self.0.iter()))
}
fn deserialize_struct<V>(
self,
_: &'static str,
fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_map(FlatStructAccess::new(self.0.iter_mut(), fields))
}
fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_newtype_struct(self)
}
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match visitor.__private_visit_untagged_option(self) {
Ok(value) => Ok(value),
Err(()) => Self::deserialize_other(),
}
}
forward_to_deserialize_other! {
deserialize_bool()
deserialize_i8()
deserialize_i16()
deserialize_i32()
deserialize_i64()
deserialize_u8()
deserialize_u16()
deserialize_u32()
deserialize_u64()
deserialize_f32()
deserialize_f64()
deserialize_char()
deserialize_str()
deserialize_string()
deserialize_bytes()
deserialize_byte_buf()
deserialize_unit()
deserialize_unit_struct(&'static str)
deserialize_seq()
deserialize_tuple(usize)
deserialize_tuple_struct(&'static str, usize)
deserialize_identifier()
deserialize_ignored_any()
}
}
#[cfg(any(feature = "std", feature = "alloc"))]
pub struct FlatMapAccess<'a, 'de: 'a, E> {
iter: slice::Iter<'a, Option<(Content<'de>, Content<'de>)>>,
pending_content: Option<&'a Content<'de>>,
_marker: PhantomData<E>,
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<'a, 'de, E> FlatMapAccess<'a, 'de, E> {
fn new(
iter: slice::Iter<'a, Option<(Content<'de>, Content<'de>)>>,
) -> FlatMapAccess<'a, 'de, E> {
FlatMapAccess {
iter: iter,
pending_content: None,
_marker: PhantomData,
}
}
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<'a, 'de, E> MapAccess<'de> for FlatMapAccess<'a, 'de, E>
where
E: Error,
{
type Error = E;
fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: DeserializeSeed<'de>,
{
while let Some(item) = self.iter.next() {
// Items in the vector are nulled out when used by a struct.
if let Some((ref key, ref content)) = *item {
self.pending_content = Some(content);
return seed.deserialize(ContentRefDeserializer::new(key)).map(Some);
}
}
Ok(None)
}
fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
where
T: DeserializeSeed<'de>,
{
match self.pending_content.take() {
Some(value) => seed.deserialize(ContentRefDeserializer::new(value)),
None => Err(Error::custom("value is missing")),
}
}
}
#[cfg(any(feature = "std", feature = "alloc"))]
pub struct FlatStructAccess<'a, 'de: 'a, E> {
iter: slice::IterMut<'a, Option<(Content<'de>, Content<'de>)>>,
pending_content: Option<Content<'de>>,
fields: &'static [&'static str],
_marker: PhantomData<E>,
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<'a, 'de, E> FlatStructAccess<'a, 'de, E> {
fn new(
iter: slice::IterMut<'a, Option<(Content<'de>, Content<'de>)>>,
fields: &'static [&'static str],
) -> FlatStructAccess<'a, 'de, E> {
FlatStructAccess {
iter: iter,
pending_content: None,
fields: fields,
_marker: PhantomData,
}
}
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<'a, 'de, E> MapAccess<'de> for FlatStructAccess<'a, 'de, E>
where
E: Error,
{
type Error = E;
fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: DeserializeSeed<'de>,
{
while let Some(item) = self.iter.next() {
// items in the vector are nulled out when used. So we can only use
// an item if it's still filled in and if the field is one we care
// about. In case we do not know which fields we want, we take them all.
let use_item = match *item {
None => false,
Some((ref c, _)) => c.as_str().map_or(false, |key| self.fields.contains(&key)),
};
if use_item {
let (key, content) = item.take().unwrap();
self.pending_content = Some(content);
return seed.deserialize(ContentDeserializer::new(key)).map(Some);
}
}
Ok(None)
}
fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
where
T: DeserializeSeed<'de>,
{
match self.pending_content.take() {
Some(value) => seed.deserialize(ContentDeserializer::new(value)),
None => Err(Error::custom("value is missing")),
}
}
}
#[cfg(any(feature = "std", feature = "alloc"))]
pub struct FlatInternallyTaggedAccess<'a, 'de: 'a, E> {
iter: slice::IterMut<'a, Option<(Content<'de>, Content<'de>)>>,
pending: Option<&'a Content<'de>>,
_marker: PhantomData<E>,
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<'a, 'de, E> MapAccess<'de> for FlatInternallyTaggedAccess<'a, 'de, E>
where
E: Error,
{
type Error = E;
fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: DeserializeSeed<'de>,
{
while let Some(item) = self.iter.next() {
if let Some((ref key, ref content)) = *item {
// Do not take(), instead borrow this entry. The internally tagged
// enum does its own buffering so we can't tell whether this entry
// is going to be consumed. Borrowing here leaves the entry
// available for later flattened fields.
self.pending = Some(content);
return seed.deserialize(ContentRefDeserializer::new(key)).map(Some);
}
}
Ok(None)
}
fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
where
T: DeserializeSeed<'de>,
{
match self.pending.take() {
Some(value) => seed.deserialize(ContentRefDeserializer::new(value)),
None => panic!("value is missing"),
}
}
}
| 30.047684 | 100 | 0.488846 |
d699be2c0b2ce39b50e5c256b4c88d3dffdd07cd | 11,890 | // Copyright (c) Microsoft. All rights reserved.
#![deny(rust_2018_idioms, warnings)]
#![deny(clippy::all, clippy::pedantic)]
#![allow(
clippy::let_and_return,
clippy::missing_errors_doc,
clippy::must_use_candidate,
clippy::shadow_unrelated,
)]
pub struct Client {
api_version: aziot_key_common_http::ApiVersion,
connector: http_common::Connector,
}
impl Client {
pub fn new(api_version: aziot_key_common_http::ApiVersion, connector: http_common::Connector) -> Self {
Client {
api_version,
connector,
}
}
pub fn create_key_pair_if_not_exists(
&self,
id: &str,
preferred_algorithms: Option<&str>,
) -> std::io::Result<aziot_key_common::KeyHandle> {
let mut stream = self.connector.connect()?;
let body = aziot_key_common_http::create_key_pair_if_not_exists::Request {
id: id.to_owned(),
preferred_algorithms: preferred_algorithms.map(ToOwned::to_owned),
};
let res: aziot_key_common_http::create_key_pair_if_not_exists::Response = request(
&mut stream,
&http::Method::POST,
format_args!("/keypair?api-version={}", self.api_version),
Some(&body),
)?;
Ok(res.handle)
}
pub fn load_key_pair(
&self,
id: &str,
) -> std::io::Result<aziot_key_common::KeyHandle> {
let mut stream = self.connector.connect()?;
let res: aziot_key_common_http::load::Response = request::<_, (), _>(
&mut stream,
&http::Method::GET,
format_args!(
"/keypair/{}?api-version={}",
percent_encoding::percent_encode(id.as_bytes(), http_common::PATH_SEGMENT_ENCODE_SET),
self.api_version,
),
None,
)?;
Ok(res.handle)
}
pub fn get_key_pair_public_parameter(
&self,
handle: &aziot_key_common::KeyHandle,
parameter_name: &str,
) -> std::io::Result<String> {
let mut stream = self.connector.connect()?;
let body = aziot_key_common_http::get_key_pair_public_parameter::Request {
key_handle: handle.clone(),
};
let res: aziot_key_common_http::get_key_pair_public_parameter::Response = request(
&mut stream,
&http::Method::POST,
format_args!(
"/parameters/{}?api-version={}",
percent_encoding::percent_encode(parameter_name.as_bytes(), http_common::PATH_SEGMENT_ENCODE_SET),
self.api_version,
),
Some(&body),
)?;
Ok(res.value)
}
pub fn create_key_if_not_exists(
&self,
id: &str,
value: aziot_key_common::CreateKeyValue,
) -> std::io::Result<aziot_key_common::KeyHandle> {
let mut stream = self.connector.connect()?;
let body = match value {
aziot_key_common::CreateKeyValue::Generate { length } => aziot_key_common_http::create_key_if_not_exists::Request {
id: id.to_owned(),
generate_key_len: Some(length),
import_key_bytes: None,
},
aziot_key_common::CreateKeyValue::Import { bytes } => aziot_key_common_http::create_key_if_not_exists::Request {
id: id.to_owned(),
generate_key_len: None,
import_key_bytes: Some(http_common::ByteString(bytes)),
},
};
let res: aziot_key_common_http::create_key_if_not_exists::Response = request(
&mut stream,
&http::Method::POST,
format_args!("/key?api-version={}", self.api_version),
Some(&body),
)?;
Ok(res.handle)
}
pub fn load_key(
&self,
id: &str,
) -> std::io::Result<aziot_key_common::KeyHandle> {
let mut stream = self.connector.connect()?;
let res: aziot_key_common_http::load::Response = request::<_, (), _>(
&mut stream,
&http::Method::GET,
format_args!(
"/key/{}?api-version={}",
percent_encoding::percent_encode(id.as_bytes(), http_common::PATH_SEGMENT_ENCODE_SET),
self.api_version,
),
None,
)?;
Ok(res.handle)
}
pub fn create_derived_key(
&self,
base_handle: &aziot_key_common::KeyHandle,
derivation_data: &[u8],
) -> std::io::Result<aziot_key_common::KeyHandle> {
let mut stream = self.connector.connect()?;
let body = aziot_key_common_http::create_derived_key::Request {
base_handle: base_handle.clone(),
derivation_data: http_common::ByteString(derivation_data.to_owned()),
};
let res: aziot_key_common_http::create_derived_key::Response = request(
&mut stream,
&http::Method::POST,
format_args!("/derivedkey?api-version={}", self.api_version),
Some(&body),
)?;
Ok(res.handle)
}
pub fn export_derived_key(
&self,
handle: &aziot_key_common::KeyHandle,
) -> std::io::Result<Vec<u8>> {
let mut stream = self.connector.connect()?;
let body = aziot_key_common_http::export_derived_key::Request {
handle: handle.clone(),
};
let res: aziot_key_common_http::export_derived_key::Response = request(
&mut stream,
&http::Method::POST,
format_args!("/derivedkey/export?api-version={}", self.api_version),
Some(&body),
)?;
Ok(res.key.0)
}
pub fn sign(
&self,
handle: &aziot_key_common::KeyHandle,
mechanism: aziot_key_common::SignMechanism,
digest: &[u8],
) -> std::io::Result<Vec<u8>> {
let mut stream = self.connector.connect()?;
let body = aziot_key_common_http::sign::Request {
key_handle: handle.clone(),
parameters: match mechanism {
aziot_key_common::SignMechanism::Ecdsa => aziot_key_common_http::sign::Parameters::Ecdsa {
digest: http_common::ByteString(digest.to_owned()),
},
aziot_key_common::SignMechanism::HmacSha256 => aziot_key_common_http::sign::Parameters::HmacSha256 {
message: http_common::ByteString(digest.to_owned()),
},
},
};
let res: aziot_key_common_http::sign::Response = request(
&mut stream,
&http::Method::POST,
format_args!("/sign?api-version={}", self.api_version),
Some(&body),
)?;
let signature = res.signature.0;
Ok(signature)
}
pub fn encrypt(
&self,
handle: &aziot_key_common::KeyHandle,
mechanism: aziot_key_common::EncryptMechanism,
plaintext: &[u8],
) -> std::io::Result<Vec<u8>> {
let mut stream = self.connector.connect()?;
let body = aziot_key_common_http::encrypt::Request {
key_handle: handle.clone(),
parameters: match mechanism {
aziot_key_common::EncryptMechanism::Aead { iv, aad } => aziot_key_common_http::encrypt::Parameters::Aead {
iv: http_common::ByteString(iv),
aad: http_common::ByteString(aad),
},
aziot_key_common::EncryptMechanism::RsaPkcs1 => aziot_key_common_http::encrypt::Parameters::RsaPkcs1,
aziot_key_common::EncryptMechanism::RsaNoPadding => aziot_key_common_http::encrypt::Parameters::RsaNoPadding,
},
plaintext: http_common::ByteString(plaintext.to_owned()),
};
let res: aziot_key_common_http::encrypt::Response = request(
&mut stream,
&http::Method::POST,
format_args!("/encrypt?api-version={}", self.api_version),
Some(&body),
)?;
let ciphertext = res.ciphertext.0;
Ok(ciphertext)
}
pub fn decrypt(
&self,
handle: &aziot_key_common::KeyHandle,
mechanism: aziot_key_common::EncryptMechanism,
ciphertext: &[u8],
) -> std::io::Result<Vec<u8>> {
let mut stream = self.connector.connect()?;
let body = aziot_key_common_http::decrypt::Request {
key_handle: handle.clone(),
parameters: match mechanism {
aziot_key_common::EncryptMechanism::Aead { iv, aad } => aziot_key_common_http::encrypt::Parameters::Aead {
iv: http_common::ByteString(iv),
aad: http_common::ByteString(aad),
},
aziot_key_common::EncryptMechanism::RsaPkcs1 => aziot_key_common_http::encrypt::Parameters::RsaPkcs1,
aziot_key_common::EncryptMechanism::RsaNoPadding => aziot_key_common_http::encrypt::Parameters::RsaNoPadding,
},
ciphertext: http_common::ByteString(ciphertext.to_owned()),
};
let res: aziot_key_common_http::decrypt::Response = request(
&mut stream,
&http::Method::POST,
format_args!("/decrypt?api-version={}", self.api_version),
Some(&body),
)?;
let plaintext = res.plaintext.0;
Ok(plaintext)
}
}
impl std::fmt::Debug for Client {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Client").finish()
}
}
fn request<TUri, TRequest, TResponse>(
stream: &mut http_common::Stream,
method: &http::Method,
uri: TUri,
body: Option<&TRequest>,
) -> std::io::Result<TResponse>
where
TUri: std::fmt::Display,
TRequest: serde::Serialize,
TResponse: serde::de::DeserializeOwned,
{
use std::io::{Read, Write};
write!(stream, "{method} {uri} HTTP/1.1\r\n", method = method, uri = uri)?;
if let Some(body) = body {
let body = serde_json::to_string(body).expect("serializing request body to JSON cannot fail");
let body_len = body.len();
write!(stream, "\
content-length: {body_len}\r\n\
content-type: application/json\r\n\
\r\n\
{body}
",
body_len = body_len,
body = body,
)?;
}
else {
stream.write_all(b"\r\n")?;
}
// While `connection: close` with a `stream.read_to_end(&mut buf)` ought to be sufficient, hyper sometimes fails to close the connection
// and causes read_to_end to block indefinitely. Verified through strace that hyper sometimes completes a writev() to write to the socket but
// never close()s it.
//
// So parse more robustly by only reading up to the length expected.
let mut buf = vec![0_u8; 512];
let mut read_so_far = 0;
let (res_status_code, body) = loop {
let new_read = loop {
match stream.read(&mut buf[read_so_far..]) {
Ok(new_read) => break new_read,
Err(err) if err.kind() == std::io::ErrorKind::Interrupted => (),
Err(err) => return Err(err),
}
};
read_so_far += new_read;
if let Some((res_status_code, body)) = try_parse_response(&buf[..read_so_far], new_read)? {
break (res_status_code, body);
}
if read_so_far == buf.len() {
buf.resize(buf.len() * 2, 0_u8);
}
};
let res: TResponse = match res_status_code {
Some(200) => {
let res = serde_json::from_slice(body).map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;
res
},
Some(400..=499) | Some(500..=599) => {
let res: http_common::ErrorBody<'static> = serde_json::from_slice(body).map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;
return Err(std::io::Error::new(std::io::ErrorKind::Other, res.message));
},
Some(_) | None => return Err(std::io::Error::new(std::io::ErrorKind::Other, "malformed HTTP response")),
};
Ok(res)
}
fn try_parse_response(buf: &[u8], new_read: usize) -> std::io::Result<Option<(Option<u16>, &[u8])>> {
let mut headers = [httparse::EMPTY_HEADER; 16];
let mut res = httparse::Response::new(&mut headers);
let body_start_pos = match res.parse(&buf) {
Ok(httparse::Status::Complete(body_start_pos)) => body_start_pos,
Ok(httparse::Status::Partial) if new_read == 0 => return Ok(None),
Ok(httparse::Status::Partial) => return Err(std::io::ErrorKind::UnexpectedEof.into()),
Err(err) => return Err(std::io::Error::new(std::io::ErrorKind::Other, err)),
};
let res_status_code = res.code;
let mut content_length = None;
let mut is_json = false;
for header in &headers {
if header.name.eq_ignore_ascii_case("content-length") {
let value = std::str::from_utf8(header.value).map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;
let value: usize = value.parse().map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;
content_length = Some(value);
}
else if header.name.eq_ignore_ascii_case("content-type") {
let value = std::str::from_utf8(header.value).map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;
if value == "application/json" {
is_json = true;
}
}
}
if !is_json {
return Err(std::io::Error::new(std::io::ErrorKind::Other, "malformed HTTP response"));
}
let body = &buf[body_start_pos..];
let body =
if let Some(content_length) = content_length {
if body.len() < content_length {
return Ok(None);
}
else {
&body[..content_length]
}
}
else {
// Without a content-length, read until there's no more to read.
if new_read == 0 {
body
}
else {
return Ok(None);
}
};
Ok(Some((res_status_code, body)))
}
| 28.719807 | 143 | 0.681749 |
dde52e7dc410b7060bb81b6464fac345406cbb06 | 1,698 | use std::rc::Rc;
use crate::{prelude::*, proc_macros::*};
/// The text input occurs if the keyboard registers a text input.
#[derive(Clone, Default, Debug, Event)]
pub struct TextInputEvent {
pub text: String,
}
/// Callback closure to handle text input events.
pub type TextHandler = dyn Fn(&mut StatesContext, &str) -> bool + 'static;
/// Internal struct to manage text input event handlers.
#[derive(IntoHandler)]
pub struct TextInputEventHandler {
handler: Rc<TextHandler>,
}
impl EventHandler for TextInputEventHandler {
fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool {
event
.downcast_ref::<TextInputEvent>()
.ok()
.map_or(false, |event| {
(self.handler)(state_context, event.text.as_str())
})
}
fn handles_event(&self, event: &EventBox) -> bool {
event.is_type::<TextInputEvent>()
}
}
/// Implement this trait for widgets that should handle text input events.
///
/// # Examples
///
/// ```rust
/// widget!(MyWidget: TextInputHandler {});
///
/// MyWidget::new()
/// .on_text_input(|_ctx, text| {
/// println!("{}", text);
/// true
/// }).build(ctx)
/// ```
pub trait TextInputHandler: Sized + Widget {
/// Callback that is called when a text input event reaches the widget.
///
/// If the callback returns `true` the event is marked as handled and will not available to
/// to other widgets.
fn on_text_input<H: Fn(&mut StatesContext, &str) -> bool + 'static>(self, handler: H) -> Self {
self.insert_handler(TextInputEventHandler {
handler: Rc::new(handler),
})
}
}
| 28.779661 | 99 | 0.621908 |
ffc4b50e8659dfbe65ea78e14302102cb4045cd8 | 17,338 | #![allow(
clippy::boxed_local,
clippy::just_underscores_and_digits,
clippy::let_underscore_drop,
clippy::missing_safety_doc,
clippy::must_use_candidate,
clippy::needless_lifetimes,
clippy::needless_pass_by_value,
clippy::ptr_arg,
clippy::trivially_copy_pass_by_ref,
clippy::unnecessary_wraps,
clippy::unused_self
)]
pub mod cast;
pub mod module;
use cxx::{type_id, CxxString, CxxVector, ExternType, SharedPtr, UniquePtr};
use std::fmt::{self, Display};
use std::mem::MaybeUninit;
use std::os::raw::c_char;
#[cxx::bridge(namespace = "tests")]
pub mod ffi {
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Shared {
z: usize,
}
#[derive(PartialEq, PartialOrd)]
struct SharedString {
msg: String,
}
#[derive(Debug, Hash, PartialOrd, Ord)]
enum Enum {
AVal,
BVal = 2020,
#[cxx_name = "CVal"]
LastVal,
}
#[namespace = "A"]
#[derive(Copy, Clone, Default)]
struct AShared {
z: usize,
}
#[namespace = "A"]
enum AEnum {
AAVal,
ABVal = 2020,
ACVal,
}
#[namespace = "A::B"]
enum ABEnum {
ABAVal,
ABBVal = 2020,
ABCVal,
}
#[namespace = "A::B"]
#[derive(Clone)]
struct ABShared {
z: usize,
}
#[namespace = "first"]
struct First {
second: Box<Second>,
}
#[namespace = "second"]
#[derive(Hash)]
struct Second {
i: i32,
e: COwnedEnum,
}
pub struct Array {
a: [i32; 4],
b: Buffer,
}
#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct StructWithLifetime<'a> {
s: &'a str,
}
unsafe extern "C++" {
include!("tests/ffi/tests.h");
type C;
fn c_return_primitive() -> usize;
fn c_return_shared() -> Shared;
fn c_return_box() -> Box<R>;
fn c_return_unique_ptr() -> UniquePtr<C>;
fn c_return_shared_ptr() -> SharedPtr<C>;
fn c_return_ref(shared: &Shared) -> &usize;
fn c_return_mut(shared: &mut Shared) -> &mut usize;
fn c_return_str(shared: &Shared) -> &str;
fn c_return_slice_char(shared: &Shared) -> &[c_char];
fn c_return_mutsliceu8(slice: &mut [u8]) -> &mut [u8];
fn c_return_rust_string() -> String;
fn c_return_rust_string_lossy() -> String;
fn c_return_unique_ptr_string() -> UniquePtr<CxxString>;
fn c_return_unique_ptr_vector_u8() -> UniquePtr<CxxVector<u8>>;
fn c_return_unique_ptr_vector_f64() -> UniquePtr<CxxVector<f64>>;
fn c_return_unique_ptr_vector_string() -> UniquePtr<CxxVector<CxxString>>;
fn c_return_unique_ptr_vector_shared() -> UniquePtr<CxxVector<Shared>>;
fn c_return_unique_ptr_vector_opaque() -> UniquePtr<CxxVector<C>>;
fn c_return_ref_vector(c: &C) -> &CxxVector<u8>;
fn c_return_mut_vector(c: Pin<&mut C>) -> Pin<&mut CxxVector<u8>>;
fn c_return_rust_vec() -> Vec<u8>;
fn c_return_ref_rust_vec(c: &C) -> &Vec<u8>;
fn c_return_mut_rust_vec(c: Pin<&mut C>) -> &mut Vec<u8>;
fn c_return_rust_vec_string() -> Vec<String>;
fn c_return_identity(_: usize) -> usize;
fn c_return_sum(_: usize, _: usize) -> usize;
fn c_return_enum(n: u16) -> Enum;
fn c_return_ns_ref(shared: &AShared) -> &usize;
fn c_return_nested_ns_ref(shared: &ABShared) -> &usize;
fn c_return_ns_enum(n: u16) -> AEnum;
fn c_return_nested_ns_enum(n: u16) -> ABEnum;
fn c_return_const_ptr(n: usize) -> *const C;
fn c_return_mut_ptr(n: usize) -> *mut C;
fn c_take_primitive(n: usize);
fn c_take_shared(shared: Shared);
fn c_take_box(r: Box<R>);
fn c_take_ref_r(r: &R);
fn c_take_ref_c(c: &C);
fn c_take_str(s: &str);
fn c_take_slice_char(s: &[c_char]);
fn c_take_slice_shared(s: &[Shared]);
fn c_take_slice_shared_sort(s: &mut [Shared]);
fn c_take_slice_r(s: &[R]);
fn c_take_slice_r_sort(s: &mut [R]);
fn c_take_rust_string(s: String);
fn c_take_unique_ptr_string(s: UniquePtr<CxxString>);
fn c_take_unique_ptr_vector_u8(v: UniquePtr<CxxVector<u8>>);
fn c_take_unique_ptr_vector_f64(v: UniquePtr<CxxVector<f64>>);
fn c_take_unique_ptr_vector_string(v: UniquePtr<CxxVector<CxxString>>);
fn c_take_unique_ptr_vector_shared(v: UniquePtr<CxxVector<Shared>>);
fn c_take_ref_vector(v: &CxxVector<u8>);
fn c_take_rust_vec(v: Vec<u8>);
fn c_take_rust_vec_shared(v: Vec<Shared>);
fn c_take_rust_vec_string(v: Vec<String>);
fn c_take_rust_vec_index(v: Vec<u8>);
fn c_take_rust_vec_shared_index(v: Vec<Shared>);
fn c_take_rust_vec_shared_push(v: Vec<Shared>);
fn c_take_rust_vec_shared_truncate(v: Vec<Shared>);
fn c_take_rust_vec_shared_clear(v: Vec<Shared>);
fn c_take_rust_vec_shared_forward_iterator(v: Vec<Shared>);
fn c_take_rust_vec_shared_sort(v: Vec<Shared>);
fn c_take_ref_rust_vec(v: &Vec<u8>);
fn c_take_ref_rust_vec_string(v: &Vec<String>);
fn c_take_ref_rust_vec_index(v: &Vec<u8>);
fn c_take_ref_rust_vec_copy(v: &Vec<u8>);
fn c_take_ref_shared_string(s: &SharedString) -> &SharedString;
fn c_take_callback(callback: fn(String) -> usize);
fn c_take_callback_ref(callback: fn(&String));
#[cxx_name = "c_take_callback_ref"]
fn c_take_callback_ref_lifetime<'a>(callback: fn(&'a String));
fn c_take_callback_mut(callback: fn(&mut String));
fn c_take_enum(e: Enum);
fn c_take_ns_enum(e: AEnum);
fn c_take_nested_ns_enum(e: ABEnum);
fn c_take_ns_shared(shared: AShared);
fn c_take_nested_ns_shared(shared: ABShared);
fn c_take_rust_vec_ns_shared(v: Vec<AShared>);
fn c_take_rust_vec_nested_ns_shared(v: Vec<ABShared>);
unsafe fn c_take_const_ptr(c: *const C) -> usize;
unsafe fn c_take_mut_ptr(c: *mut C) -> usize;
fn c_try_return_void() -> Result<()>;
fn c_try_return_primitive() -> Result<usize>;
fn c_fail_return_primitive() -> Result<usize>;
fn c_try_return_box() -> Result<Box<R>>;
fn c_try_return_ref(s: &String) -> Result<&String>;
fn c_try_return_str(s: &str) -> Result<&str>;
fn c_try_return_sliceu8(s: &[u8]) -> Result<&[u8]>;
fn c_try_return_mutsliceu8(s: &mut [u8]) -> Result<&mut [u8]>;
fn c_try_return_rust_string() -> Result<String>;
fn c_try_return_unique_ptr_string() -> Result<UniquePtr<CxxString>>;
fn c_try_return_rust_vec() -> Result<Vec<u8>>;
fn c_try_return_rust_vec_string() -> Result<Vec<String>>;
fn c_try_return_ref_rust_vec(c: &C) -> Result<&Vec<u8>>;
fn get(self: &C) -> usize;
fn set(self: Pin<&mut C>, n: usize) -> usize;
fn get2(&self) -> usize;
fn getRef(self: &C) -> &usize;
fn getMut(self: Pin<&mut C>) -> &mut usize;
fn set_succeed(self: Pin<&mut C>, n: usize) -> Result<usize>;
fn get_fail(self: Pin<&mut C>) -> Result<usize>;
fn c_method_on_shared(self: &Shared) -> usize;
fn c_method_ref_on_shared(self: &Shared) -> &usize;
fn c_method_mut_on_shared(self: &mut Shared) -> &mut usize;
fn c_set_array(self: &mut Array, value: i32);
fn c_get_use_count(weak: &WeakPtr<C>) -> usize;
#[rust_name = "i32_overloaded_method"]
fn cOverloadedMethod(&self, x: i32) -> String;
#[rust_name = "str_overloaded_method"]
fn cOverloadedMethod(&self, x: &str) -> String;
#[rust_name = "i32_overloaded_function"]
fn cOverloadedFunction(x: i32) -> String;
#[rust_name = "str_overloaded_function"]
fn cOverloadedFunction(x: &str) -> String;
#[namespace = "other"]
fn ns_c_take_ns_shared(shared: AShared);
}
extern "C++" {
include!("tests/ffi/module.rs.h");
type COwnedEnum;
type Job = crate::module::ffi::Job;
}
extern "Rust" {
#[derive(ExternType)]
type Reference<'a>;
}
unsafe extern "C++" {
type Borrow<'a>;
fn c_return_borrow<'a>(s: &'a CxxString) -> UniquePtr<Borrow<'a>>;
#[rust_name = "c_return_borrow_elided"]
fn c_return_borrow(s: &CxxString) -> UniquePtr<Borrow>;
fn const_member(self: &Borrow);
fn nonconst_member(self: Pin<&mut Borrow>);
}
#[repr(u32)]
#[derive(Hash)]
enum COwnedEnum {
#[cxx_name = "CVAL1"]
CVal1,
#[cxx_name = "CVAL2"]
CVal2,
}
extern "C++" {
type Buffer = crate::Buffer;
}
extern "Rust" {
type R;
fn r_return_primitive() -> usize;
fn r_return_shared() -> Shared;
fn r_return_box() -> Box<R>;
fn r_return_unique_ptr() -> UniquePtr<C>;
fn r_return_shared_ptr() -> SharedPtr<C>;
fn r_return_ref(shared: &Shared) -> &usize;
fn r_return_mut(shared: &mut Shared) -> &mut usize;
fn r_return_str(shared: &Shared) -> &str;
fn r_return_sliceu8(shared: &Shared) -> &[u8];
fn r_return_mutsliceu8(slice: &mut [u8]) -> &mut [u8];
fn r_return_rust_string() -> String;
fn r_return_unique_ptr_string() -> UniquePtr<CxxString>;
fn r_return_rust_vec() -> Vec<u8>;
fn r_return_rust_vec_string() -> Vec<String>;
fn r_return_rust_vec_extern_struct() -> Vec<Job>;
fn r_return_ref_rust_vec(shared: &Shared) -> &Vec<u8>;
fn r_return_mut_rust_vec(shared: &mut Shared) -> &mut Vec<u8>;
fn r_return_identity(_: usize) -> usize;
fn r_return_sum(_: usize, _: usize) -> usize;
fn r_return_enum(n: u32) -> Enum;
fn r_take_primitive(n: usize);
fn r_take_shared(shared: Shared);
fn r_take_box(r: Box<R>);
fn r_take_unique_ptr(c: UniquePtr<C>);
fn r_take_shared_ptr(c: SharedPtr<C>);
fn r_take_ref_r(r: &R);
fn r_take_ref_c(c: &C);
fn r_take_str(s: &str);
fn r_take_slice_char(s: &[c_char]);
fn r_take_rust_string(s: String);
fn r_take_unique_ptr_string(s: UniquePtr<CxxString>);
fn r_take_ref_vector(v: &CxxVector<u8>);
fn r_take_ref_empty_vector(v: &CxxVector<u64>);
fn r_take_rust_vec(v: Vec<u8>);
fn r_take_rust_vec_string(v: Vec<String>);
fn r_take_ref_rust_vec(v: &Vec<u8>);
fn r_take_ref_rust_vec_string(v: &Vec<String>);
fn r_take_enum(e: Enum);
fn r_try_return_void() -> Result<()>;
fn r_try_return_primitive() -> Result<usize>;
fn r_try_return_box() -> Result<Box<R>>;
fn r_fail_return_primitive() -> Result<usize>;
fn r_try_return_sliceu8(s: &[u8]) -> Result<&[u8]>;
fn r_try_return_mutsliceu8(s: &mut [u8]) -> Result<&mut [u8]>;
fn get(self: &R) -> usize;
fn set(self: &mut R, n: usize) -> usize;
fn r_method_on_shared(self: &Shared) -> String;
fn r_get_array_sum(self: &Array) -> i32;
#[cxx_name = "rAliasedFunction"]
fn r_aliased_function(x: i32) -> String;
}
struct Dag0 {
i: i32,
}
struct Dag1 {
dag2: Dag2,
vec: Vec<Dag3>,
}
struct Dag2 {
dag4: Dag4,
}
struct Dag3 {
dag1: Dag1,
}
struct Dag4 {
dag0: Dag0,
}
impl Box<Shared> {}
impl CxxVector<SharedString> {}
}
mod other {
use cxx::kind::{Opaque, Trivial};
use cxx::{type_id, CxxString, ExternType};
#[repr(C)]
pub struct D {
pub d: u64,
}
#[repr(C)]
pub struct E {
e: u64,
e_str: CxxString,
}
pub mod f {
use cxx::kind::Opaque;
use cxx::{type_id, CxxString, ExternType};
#[repr(C)]
pub struct F {
e: u64,
e_str: CxxString,
}
unsafe impl ExternType for F {
type Id = type_id!("F::F");
type Kind = Opaque;
}
}
#[repr(C)]
pub struct G {
pub g: u64,
}
unsafe impl ExternType for G {
type Id = type_id!("G::G");
type Kind = Trivial;
}
unsafe impl ExternType for D {
type Id = type_id!("tests::D");
type Kind = Trivial;
}
unsafe impl ExternType for E {
type Id = type_id!("tests::E");
type Kind = Opaque;
}
}
#[derive(PartialEq, Debug)]
pub struct R(pub usize);
impl R {
fn get(&self) -> usize {
self.0
}
fn set(&mut self, n: usize) -> usize {
self.0 = n;
n
}
}
pub struct Reference<'a>(&'a String);
impl ffi::Shared {
fn r_method_on_shared(&self) -> String {
"2020".to_owned()
}
}
impl ffi::Array {
pub fn r_get_array_sum(&self) -> i32 {
self.a.iter().sum()
}
}
#[derive(Default)]
#[repr(C)]
pub struct Buffer([c_char; 12]);
unsafe impl ExternType for Buffer {
type Id = type_id!("tests::Buffer");
type Kind = cxx::kind::Trivial;
}
#[derive(Debug)]
struct Error;
impl std::error::Error for Error {}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("rust error")
}
}
fn r_return_primitive() -> usize {
2020
}
fn r_return_shared() -> ffi::Shared {
ffi::Shared { z: 2020 }
}
fn r_return_box() -> Box<R> {
Box::new(R(2020))
}
fn r_return_unique_ptr() -> UniquePtr<ffi::C> {
extern "C" {
fn cxx_test_suite_get_unique_ptr() -> *mut ffi::C;
}
unsafe { UniquePtr::from_raw(cxx_test_suite_get_unique_ptr()) }
}
fn r_return_shared_ptr() -> SharedPtr<ffi::C> {
extern "C" {
fn cxx_test_suite_get_shared_ptr(repr: *mut SharedPtr<ffi::C>);
}
let mut shared_ptr = MaybeUninit::<SharedPtr<ffi::C>>::uninit();
let repr = shared_ptr.as_mut_ptr();
unsafe {
cxx_test_suite_get_shared_ptr(repr);
shared_ptr.assume_init()
}
}
fn r_return_ref(shared: &ffi::Shared) -> &usize {
&shared.z
}
fn r_return_mut(shared: &mut ffi::Shared) -> &mut usize {
&mut shared.z
}
fn r_return_str(shared: &ffi::Shared) -> &str {
let _ = shared;
"2020"
}
fn r_return_sliceu8(shared: &ffi::Shared) -> &[u8] {
let _ = shared;
b"2020"
}
fn r_return_mutsliceu8(slice: &mut [u8]) -> &mut [u8] {
slice
}
fn r_return_rust_string() -> String {
"2020".to_owned()
}
fn r_return_unique_ptr_string() -> UniquePtr<CxxString> {
extern "C" {
fn cxx_test_suite_get_unique_ptr_string() -> *mut CxxString;
}
unsafe { UniquePtr::from_raw(cxx_test_suite_get_unique_ptr_string()) }
}
fn r_return_rust_vec() -> Vec<u8> {
Vec::new()
}
fn r_return_rust_vec_string() -> Vec<String> {
Vec::new()
}
fn r_return_rust_vec_extern_struct() -> Vec<ffi::Job> {
Vec::new()
}
fn r_return_ref_rust_vec(shared: &ffi::Shared) -> &Vec<u8> {
let _ = shared;
unimplemented!()
}
fn r_return_mut_rust_vec(shared: &mut ffi::Shared) -> &mut Vec<u8> {
let _ = shared;
unimplemented!()
}
fn r_return_identity(n: usize) -> usize {
n
}
fn r_return_sum(n1: usize, n2: usize) -> usize {
n1 + n2
}
fn r_return_enum(n: u32) -> ffi::Enum {
if n == 0 {
ffi::Enum::AVal
} else if n <= 2020 {
ffi::Enum::BVal
} else {
ffi::Enum::LastVal
}
}
fn r_take_primitive(n: usize) {
assert_eq!(n, 2020);
}
fn r_take_shared(shared: ffi::Shared) {
assert_eq!(shared.z, 2020);
}
fn r_take_box(r: Box<R>) {
let _ = r;
}
fn r_take_unique_ptr(c: UniquePtr<ffi::C>) {
let _ = c;
}
fn r_take_shared_ptr(c: SharedPtr<ffi::C>) {
let _ = c;
}
fn r_take_ref_r(r: &R) {
let _ = r;
}
fn r_take_ref_c(c: &ffi::C) {
let _ = c;
}
fn r_take_str(s: &str) {
assert_eq!(s, "2020");
}
fn r_take_rust_string(s: String) {
assert_eq!(s, "2020");
}
fn r_take_slice_char(s: &[c_char]) {
assert_eq!(s.len(), 5);
let s = cast::c_char_to_unsigned(s);
assert_eq!(std::str::from_utf8(s).unwrap(), "2020\0");
}
fn r_take_unique_ptr_string(s: UniquePtr<CxxString>) {
assert_eq!(s.as_ref().unwrap().to_str().unwrap(), "2020");
}
fn r_take_ref_vector(v: &CxxVector<u8>) {
let slice = v.as_slice();
assert_eq!(slice, [20, 2, 0]);
}
fn r_take_ref_empty_vector(v: &CxxVector<u64>) {
assert!(v.as_slice().is_empty());
assert!(v.is_empty());
}
fn r_take_rust_vec(v: Vec<u8>) {
let _ = v;
}
fn r_take_rust_vec_string(v: Vec<String>) {
let _ = v;
}
fn r_take_ref_rust_vec(v: &Vec<u8>) {
let _ = v;
}
fn r_take_ref_rust_vec_string(v: &Vec<String>) {
let _ = v;
}
fn r_take_enum(e: ffi::Enum) {
let _ = e;
}
fn r_try_return_void() -> Result<(), Error> {
Ok(())
}
fn r_try_return_primitive() -> Result<usize, Error> {
Ok(2020)
}
fn r_try_return_box() -> Result<Box<R>, Error> {
Ok(Box::new(R(2020)))
}
fn r_fail_return_primitive() -> Result<usize, Error> {
Err(Error)
}
fn r_try_return_sliceu8(slice: &[u8]) -> Result<&[u8], Error> {
Ok(slice)
}
fn r_try_return_mutsliceu8(slice: &mut [u8]) -> Result<&mut [u8], Error> {
Ok(slice)
}
fn r_aliased_function(x: i32) -> String {
x.to_string()
}
| 26.797527 | 82 | 0.594302 |
dd76abf9d878593d0fb9c92b97068b0341545fe5 | 917 | mod utils;
use clap::{App, Arg};
fn get_app() -> App<'static> {
App::new("myprog")
.arg(
Arg::with_name("GLOBAL_ARG")
.long("global-arg")
.about("Specifies something needed by the subcommands")
.global(true)
.takes_value(true)
.default_value("default_value"),
)
.arg(
Arg::with_name("GLOBAL_FLAG")
.long("global-flag")
.about("Specifies something needed by the subcommands")
.multiple(true)
.global(true),
)
.subcommand(App::new("outer").subcommand(App::new("inner")))
}
#[test]
fn issue_1076() {
let mut app = get_app();
let _ = app.try_get_matches_from_mut(vec!["myprog"]);
let _ = app.try_get_matches_from_mut(vec!["myprog"]);
let _ = app.try_get_matches_from_mut(vec!["myprog"]);
}
| 28.65625 | 71 | 0.529989 |
5da378adae557119f11d3f38284230069be0c7cc | 602 | #[cfg(backtrace)]
pub(crate) use std::backtrace::Backtrace;
#[cfg(not(backtrace))]
pub(crate) enum Backtrace {}
#[cfg(backtrace)]
macro_rules! backtrace {
() => {
Some(Backtrace::capture())
};
}
#[cfg(not(backtrace))]
macro_rules! backtrace {
() => {
None
};
}
#[cfg(backtrace)]
macro_rules! backtrace_if_absent {
($err:expr) => {
match $err.backtrace() {
Some(_) => None,
None => Some(Backtrace::capture()),
}
};
}
#[cfg(not(backtrace))]
macro_rules! backtrace_if_absent {
($err:expr) => {
None
};
}
| 16.27027 | 47 | 0.541528 |
3a6c29cefaa57464a98ebbc51dcc67037f7994c4 | 580 | //! Tests auto-converted from "sass-spec/spec/css/plain/error/expression/silent_comment.hrx"
#[allow(unused)]
fn runner() -> crate::TestRunner {
super::runner().mock_file("plain.css", "a {\n b: c // d\n e;\n}\n")
}
#[test]
#[ignore] // missing error
fn test() {
assert_eq!(
runner().err("@import \'plain\'\n"),
"Error: Silent comments aren\'t allowed in plain CSS.\
\n ,\
\n2 | b: c // d\
\n | ^^^^\
\n \'\
\n plain.css 2:8 @import\
\n input.scss 1:9 root stylesheet",
);
}
| 26.363636 | 92 | 0.508621 |
ddf7f40239810445a1cf067f6a83e8acc79b7086 | 28,441 | use std::time::Instant;
use client_gpu::Object;
use egui::{CentralPanel, CtxRef, Window};
use generator::{Control, Generator};
use nalgebra::Isometry;
use network::{value_channel, Connection, Message};
use physics::{character_collider, RigidBodyType};
use protocol::{DynamicUpdate, Entity, Notification, Request, Transform};
use tokio::{spawn, task::JoinHandle};
use util::{handle::HandleFlow, interpolation::InterpolationBuffer};
use vulkan::RenderPass;
use winit::{event::Event, event_loop::EventLoopProxy};
use crate::{
action::Action,
character::{NPC, PC},
game::Game,
region::Region,
session::{Session, SessionState},
world::World,
};
use super::{RootContext, RootFrame, RootSurface};
#[allow(clippy::large_enum_variant)]
pub enum RootState {
Configure,
Connect {
task: Option<JoinHandle<()>>,
},
Connected(Session),
Report {
error: eyre::Error,
},
Generate {
task: Option<JoinHandle<()>>,
control: Control,
generator: Generator,
},
GenerateFinished,
}
impl RootState {
pub fn prepare_render(
&mut self,
context: &mut RootContext,
surface: &RootSurface,
frame: &mut RootFrame,
) -> eyre::Result<()> {
match self {
Self::Connected(session) => session.state.prepare_render(context, surface, frame),
_ => Ok(()),
}
}
pub fn render(
&mut self,
context: &mut RootContext,
render_pass: &RenderPass,
frame: &mut RootFrame,
pre_pass: bool,
) -> Result<(), vulkan::Error> {
if let Self::Connected(session) = self {
session.state.render(context, render_pass, frame, pre_pass)
} else {
Ok(())
}
}
pub async fn shutdown(&mut self) -> eyre::Result<()> {
match self {
Self::Configure => {}
Self::Connect { task } => {
let task = task.take().unwrap();
task.abort();
drop(task.await)
}
Self::Connected(session) => {
session
.context
.connection
.send(Message::from(Request::Disconnect))
.await?;
session.context.task.take().unwrap().await?;
if let Some(server) = session.context.server.as_mut() {
server.stop().await?;
}
}
Self::Report { .. } => {}
Self::Generate {
task,
control,
generator,
} => {
control.cancel();
task.take().unwrap().await?;
drop(generator.join().await)
}
Self::GenerateFinished => {}
}
Ok(())
}
pub fn render_egui(&mut self, ctx: &CtxRef, proxy: &EventLoopProxy<Action>) {
match self {
Self::Connect { .. } => {
CentralPanel::default().show(ctx, |ui| {
ui.label("connecting to server");
});
}
Self::Configure {} => {
CentralPanel::default().show(ctx, |ui| {
if ui.button("create").clicked() {
proxy.send_event(Action::Create).unwrap()
};
});
}
Self::Connected(session) => match &session.state {
SessionState::Lobby { slots } => {
CentralPanel::default().show(ctx, |ui| {
for (slot, id) in slots.iter().cloned().enumerate() {
ui.horizontal(|ui| {
if id != u32::MAX {
ui.label(format!("{}", id));
if ui.button("play").clicked() {
let connection = session.context.connection.clone();
spawn(async move {
connection
.send(Message::from(Request::Enter(slot as u8)))
.await
.unwrap();
});
}
if ui.button("unbind").clicked() {
let proxy = proxy.clone();
let connection = session.context.connection.clone();
spawn(async move {
let (sender, receiver) = value_channel();
connection
.send(Message::from(Request::Delete(
slot as u8, sender,
)))
.await
.unwrap();
receiver.recv().await.unwrap();
proxy
.send_event(Action::UpdateLobbySlot(
slot as u8,
u32::MAX,
))
.unwrap();
});
}
} else {
ui.label("unbound");
if ui.button("bind").clicked() {
let proxy = proxy.clone();
let connection = session.context.connection.clone();
spawn(async move {
let (sender, receiver) = value_channel();
connection
.send(Message::from(Request::Create(
slot as u8, sender,
)))
.await
.unwrap();
let value = receiver.recv().await.unwrap();
proxy
.send_event(Action::UpdateLobbySlot(
slot as u8, value,
))
.unwrap();
});
}
}
});
}
});
}
SessionState::InGame(game) => {
if let Some((entity, toi)) = &game.context.target {
Window::new("Target").title_bar(false).show(ctx, |ui| {
ui.label(format!("Entity: {:?}", entity));
ui.label(format!("Distance: {}", toi));
});
}
}
},
Self::Report { error } => {
CentralPanel::default().show(ctx, |ui| {
ui.label(format!("{}", error));
if ui.button("exit").clicked() {
proxy.send_event(Action::Close).unwrap()
};
});
}
Self::Generate { .. } => {
CentralPanel::default().show(ctx, |ui| {
ui.label("generating world");
});
}
Self::GenerateFinished => {
CentralPanel::default().show(ctx, |ui| {
if ui.button("exit").clicked() {
proxy.send_event(Action::Close).unwrap()
};
});
}
}
}
pub async fn update(&mut self, now: Instant) {
if let Self::Connected(session) = self {
session.state.update(now, &session.context)
}
}
pub fn apply(
&mut self,
root_context: &RootContext,
notification: Notification,
) -> eyre::Result<()> {
match self {
Self::Connected(session) => {
if let Notification::Enter(enter) = notification {
session.state = SessionState::InGame(Game::new(root_context, enter)?);
return Ok(());
}
match &mut session.state {
SessionState::InGame(game) => match notification {
Notification::GlobalSetup(_) => {}
Notification::StaticSetup((region_pos, setup)) => {
game.context.world.regions.insert(
region_pos.into_index(game.context.world.size) as usize,
Region::new(
region_pos,
setup.heights,
setup.region_size,
&mut game.context.world.physics,
&mut game.context.terrain.context,
),
);
}
Notification::StaticTeardown(region_pos) => {
game.context
.world
.regions
.remove_by_id(
region_pos.into_index(game.context.world.size) as usize
)
.unwrap()
.cleanup(
region_pos,
&mut game.context.world.physics,
&mut game.context.terrain.context,
);
}
Notification::GlobalUpdates(updates) => {
for update in updates {
match update {}
}
}
Notification::StaticUpdates((_, updates)) => {
for update in updates {
match update {}
}
}
Notification::DynamicUpdates((region_pos, updates, tick)) => {
let region_index = game.context.world.regions.index
[&(region_pos.into_index(game.context.world.size) as usize)];
for update in updates {
match update {
DynamicUpdate::Enter(entity, from, pos, rotation) => {
match entity {
protocol::Entity::NPC(id) => {
game.context.world.regions.npcs[region_index]
.insert(id);
if let Some(region_pos) = from {
if game
.context
.world
.regions
.index
.contains_key(
&(region_pos
.into_index(game.context.world.size)
as usize),
)
{
continue;
}
}
let transform = Isometry::from_parts(
pos.into(),
rotation.into(),
);
let handle = game.context.world.physics.add_body(
RigidBodyType::KinematicPositionBased,
transform,
character_collider(),
entity.into(),
);
game.context.world.npcs.insert(
id as usize,
NPC {
transform: InterpolationBuffer::new(
Transform(transform),
tick as usize,
),
handle,
object: Object {
transform: transform.into(),
model: game.context.cube_model,
},
},
);
}
protocol::Entity::PC(id) => {
if id == game.context.self_id {
continue;
}
game.context.world.regions.pcs[region_index]
.insert(id);
if let Some(region_pos) = from {
if game
.context
.world
.regions
.index
.contains_key(
&(region_pos
.into_index(game.context.world.size)
as usize),
)
{
continue;
}
}
let transform = Isometry::from_parts(
pos.into(),
rotation.into(),
);
let handle = game.context.world.physics.add_body(
RigidBodyType::KinematicPositionBased,
transform,
character_collider(),
entity.into(),
);
game.context.world.pcs.insert(
id as usize,
PC {
transform: InterpolationBuffer::new(
Transform(transform),
tick as usize,
),
handle,
object: Object {
transform: transform.into(),
model: game.context.cube_model,
},
},
);
}
}
}
DynamicUpdate::Exit(entity, to) => match entity {
protocol::Entity::NPC(id) => {
game.context.world.regions.npcs[region_index]
.remove(&id);
if let Some(region_pos) = to {
if game.context.world.regions.index.contains_key(
&(region_pos.into_index(game.context.world.size)
as usize),
) {
continue;
}
}
let npc = game
.context
.world
.npcs
.remove_by_id(id as usize)
.unwrap();
game.context.world.physics.remove_body(npc.handle);
}
protocol::Entity::PC(id) => {
if id == game.context.self_id {
continue;
}
game.context.world.regions.pcs[region_index]
.remove(&id);
if let Some(region_pos) = to {
if game.context.world.regions.index.contains_key(
&(region_pos.into_index(game.context.world.size)
as usize),
) {
continue;
}
}
let pc = game
.context
.world
.pcs
.remove_by_id(id as usize)
.unwrap();
game.context.world.physics.remove_body(pc.handle);
}
},
DynamicUpdate::Update(entity, pos, rotation) => match entity {
protocol::Entity::NPC(id) => {
let npc_index =
game.context.world.npcs.index[&(id as usize)];
let transform =
Isometry::from_parts(pos.into(), rotation.into());
game.context.world.npcs.transform[npc_index]
.insert(tick as usize, Transform(transform));
}
protocol::Entity::PC(id) => {
if id == game.context.self_id {
continue;
}
if let Some(pc_index) = game
.context
.world
.pcs
.index
.get(&(id as usize))
.cloned()
{
let transform = Isometry::from_parts(
pos.into(),
rotation.into(),
);
game.context.world.pcs.transform[pc_index]
.insert(tick as usize, Transform(transform))
}
}
},
}
}
}
Notification::Enter(_) => panic!(),
Notification::DynamicSetup((region_pos, setup, tick)) => {
let region_index = game.context.world.regions.index
[&(region_pos.into_index(game.context.world.size) as usize)];
for (id, pos, rotation) in setup.npcs {
game.context.world.regions.npcs[region_index].insert(id);
let transform = Isometry::from_parts(pos.into(), rotation.into());
let handle = game.context.world.physics.add_body(
RigidBodyType::KinematicPositionBased,
transform,
character_collider(),
Entity::NPC(id).into(),
);
game.context.world.npcs.insert(
id as usize,
NPC {
transform: InterpolationBuffer::new(
Transform(transform),
tick as usize,
),
handle,
object: Object {
transform: transform.into(),
model: game.context.cube_model,
},
},
);
}
for (id, pos, rotation) in setup.pcs {
if id == game.context.self_id {
continue;
}
game.context.world.regions.pcs[region_index].insert(id);
let transform = Isometry::from_parts(pos.into(), rotation.into());
let handle = game.context.world.physics.add_body(
RigidBodyType::KinematicPositionBased,
transform,
character_collider(),
Entity::PC(id).into(),
);
game.context.world.pcs.insert(
id as usize,
PC {
transform: InterpolationBuffer::new(
Transform(transform),
tick as usize,
),
handle,
object: Object {
transform: transform.into(),
model: game.context.cube_model,
},
},
);
}
}
Notification::DynamicTeardown(region_pos) => {
let region_index = game.context.world.regions.index
[&(region_pos.into_index(game.context.world.size) as usize)];
for id in game.context.world.regions.npcs[region_index].drain() {
let npc =
game.context.world.npcs.remove_by_id(id as usize).unwrap();
game.context.world.physics.remove_body(npc.handle);
}
for id in game.context.world.regions.pcs[region_index].drain() {
let pc = game.context.world.pcs.remove_by_id(id as usize).unwrap();
game.context.world.physics.remove_body(pc.handle);
}
}
},
_ => panic!(),
}
}
_ => panic!(),
}
Ok(())
}
pub fn handle_event(&mut self, event: &Event<()>, grab: bool) -> HandleFlow {
match self {
Self::Connected(session) => session.state.handle_event(event, grab),
_ => HandleFlow::Unhandled,
}
}
pub fn connection(&self) -> Option<&Connection<Request>> {
if let Self::Connected(session) = self {
Some(&session.context.connection)
} else {
None
}
}
pub fn world(&self) -> Option<&World> {
if let Self::Connected(session) = self {
if let SessionState::InGame(game) = &session.state {
return Some(&game.context.world);
}
}
None
}
pub fn world_mut(&mut self) -> Option<&mut World> {
if let Self::Connected(session) = self {
if let SessionState::InGame(game) = &mut session.state {
return Some(&mut game.context.world);
}
}
None
}
pub fn can_grab(&self) -> bool {
if let Self::Connected(session) = self {
if let SessionState::InGame(_) = &session.state {
return true;
}
}
false
}
pub fn game(&self) -> Option<&Game> {
if let Self::Connected(session) = self {
if let SessionState::InGame(game) = &session.state {
return Some(game);
}
}
None
}
}
| 49.722028 | 100 | 0.295067 |
1676aa0f84544965b8daa7113747556ef07cc020 | 476 | // Copyright 2019-2022 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use fvm_ipld_encoding::tuple::{Deserialize_tuple, Serialize_tuple};
use fvm_ipld_encoding::{Cbor, RawBytes};
use crate::error::ExitCode;
/// Result of a state transition from a message
#[derive(Debug, PartialEq, Clone, Serialize_tuple, Deserialize_tuple)]
pub struct Receipt {
pub exit_code: ExitCode,
pub return_data: RawBytes,
pub gas_used: i64,
}
impl Cbor for Receipt {}
| 26.444444 | 70 | 0.752101 |
f52e1e7512788d7828d4bba26d09d6b58c8df422 | 16,852 | //! Fully type-check project and print various stats, like the number of type
//! errors.
use std::{
env,
time::{SystemTime, UNIX_EPOCH},
};
use hir::{
db::{AstDatabase, DefDatabase, HirDatabase},
AssocItem, Crate, Function, HasSource, HirDisplay, ModuleDef,
};
use hir_def::{
body::{BodySourceMap, SyntheticSyntax},
expr::ExprId,
FunctionId,
};
use hir_ty::{TyExt, TypeWalk};
use ide::{Analysis, AnalysisHost, LineCol, RootDatabase};
use ide_db::base_db::{
salsa::{self, debug::DebugQueryTable, ParallelDatabase},
SourceDatabase, SourceDatabaseExt,
};
use itertools::Itertools;
use oorandom::Rand32;
use profile::{Bytes, StopWatch};
use project_model::{CargoConfig, ProjectManifest, ProjectWorkspace};
use rayon::prelude::*;
use rustc_hash::FxHashSet;
use stdx::format_to;
use syntax::{AstNode, SyntaxNode};
use vfs::{AbsPathBuf, Vfs, VfsPath};
use crate::cli::{
flags::{self, OutputFormat},
load_cargo::{load_workspace, LoadCargoConfig},
print_memory_usage,
progress_report::ProgressReport,
report_metric, Result, Verbosity,
};
/// Need to wrap Snapshot to provide `Clone` impl for `map_with`
struct Snap<DB>(DB);
impl<DB: ParallelDatabase> Clone for Snap<salsa::Snapshot<DB>> {
fn clone(&self) -> Snap<salsa::Snapshot<DB>> {
Snap(self.0.snapshot())
}
}
impl flags::AnalysisStats {
pub fn run(self, verbosity: Verbosity) -> Result<()> {
let mut rng = {
let seed = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64;
Rand32::new(seed)
};
let mut cargo_config = CargoConfig::default();
cargo_config.no_sysroot = self.no_sysroot;
let load_cargo_config = LoadCargoConfig {
load_out_dirs_from_check: !self.disable_build_scripts,
with_proc_macro: !self.disable_proc_macros,
prefill_caches: false,
};
let no_progress = &|_| ();
let mut db_load_sw = self.stop_watch();
let path = AbsPathBuf::assert(env::current_dir()?.join(&self.path));
let manifest = ProjectManifest::discover_single(&path)?;
let mut workspace = ProjectWorkspace::load(manifest, &cargo_config, no_progress)?;
let metadata_time = db_load_sw.elapsed();
let build_scripts_time = if self.disable_build_scripts {
None
} else {
let mut build_scripts_sw = self.stop_watch();
let bs = workspace.run_build_scripts(&cargo_config, no_progress)?;
workspace.set_build_scripts(bs);
Some(build_scripts_sw.elapsed())
};
let (host, vfs, _proc_macro) = load_workspace(workspace, &load_cargo_config)?;
let db = host.raw_database();
eprint!("{:<20} {}", "Database loaded:", db_load_sw.elapsed());
eprint!(" (metadata {}", metadata_time);
if let Some(build_scripts_time) = build_scripts_time {
eprint!("; build {}", build_scripts_time);
}
eprintln!(")");
let mut analysis_sw = self.stop_watch();
let mut num_crates = 0;
let mut visited_modules = FxHashSet::default();
let mut visit_queue = Vec::new();
let mut krates = Crate::all(db);
if self.randomize {
shuffle(&mut rng, &mut krates);
}
for krate in krates {
let module = krate.root_module(db);
let file_id = module.definition_source(db).file_id;
let file_id = file_id.original_file(db);
let source_root = db.file_source_root(file_id);
let source_root = db.source_root(source_root);
if !source_root.is_library || self.with_deps {
num_crates += 1;
visit_queue.push(module);
}
}
if self.randomize {
shuffle(&mut rng, &mut visit_queue);
}
eprint!(" crates: {}", num_crates);
let mut num_decls = 0;
let mut funcs = Vec::new();
while let Some(module) = visit_queue.pop() {
if visited_modules.insert(module) {
visit_queue.extend(module.children(db));
for decl in module.declarations(db) {
num_decls += 1;
if let ModuleDef::Function(f) = decl {
funcs.push(f);
}
}
for impl_def in module.impl_defs(db) {
for item in impl_def.items(db) {
num_decls += 1;
if let AssocItem::Function(f) = item {
funcs.push(f);
}
}
}
}
}
eprintln!(", mods: {}, decls: {}, fns: {}", visited_modules.len(), num_decls, funcs.len());
eprintln!("{:<20} {}", "Item Collection:", analysis_sw.elapsed());
if self.randomize {
shuffle(&mut rng, &mut funcs);
}
if !self.skip_inference {
self.run_inference(&host, db, &vfs, &funcs, verbosity);
}
let total_span = analysis_sw.elapsed();
eprintln!("{:<20} {}", "Total:", total_span);
report_metric("total time", total_span.time.as_millis() as u64, "ms");
if let Some(instructions) = total_span.instructions {
report_metric("total instructions", instructions, "#instr");
}
if let Some(memory) = total_span.memory {
report_metric("total memory", memory.allocated.megabytes() as u64, "MB");
}
if env::var("RA_COUNT").is_ok() {
eprintln!("{}", profile::countme::get_all());
}
if self.source_stats {
let mut total_file_size = Bytes::default();
for e in ide_db::base_db::ParseQuery.in_db(db).entries::<Vec<_>>() {
total_file_size += syntax_len(db.parse(e.key).syntax_node())
}
let mut total_macro_file_size = Bytes::default();
for e in hir::db::ParseMacroExpansionQuery.in_db(db).entries::<Vec<_>>() {
if let Some((val, _)) = db.parse_macro_expansion(e.key).value {
total_macro_file_size += syntax_len(val.syntax_node())
}
}
eprintln!("source files: {}, macro files: {}", total_file_size, total_macro_file_size);
}
if self.memory_usage && verbosity.is_verbose() {
print_memory_usage(host, vfs);
}
Ok(())
}
fn run_inference(
&self,
host: &AnalysisHost,
db: &RootDatabase,
vfs: &Vfs,
funcs: &[Function],
verbosity: Verbosity,
) {
let mut bar = match verbosity {
Verbosity::Quiet | Verbosity::Spammy => ProgressReport::hidden(),
_ if self.parallel || self.output.is_some() => ProgressReport::hidden(),
_ => ProgressReport::new(funcs.len() as u64),
};
if self.parallel {
let mut inference_sw = self.stop_watch();
let snap = Snap(db.snapshot());
funcs
.par_iter()
.map_with(snap, |snap, &f| {
let f_id = FunctionId::from(f);
snap.0.body(f_id.into());
snap.0.infer(f_id.into());
})
.count();
eprintln!("{:<20} {}", "Parallel Inference:", inference_sw.elapsed());
}
let mut inference_sw = self.stop_watch();
bar.tick();
let mut num_exprs = 0;
let mut num_exprs_unknown = 0;
let mut num_exprs_partially_unknown = 0;
let mut num_type_mismatches = 0;
let analysis = host.analysis();
for f in funcs.iter().copied() {
let name = f.name(db);
let full_name = f
.module(db)
.path_to_root(db)
.into_iter()
.rev()
.filter_map(|it| it.name(db))
.chain(Some(f.name(db)))
.join("::");
if let Some(only_name) = self.only.as_deref() {
if name.to_string() != only_name && full_name != only_name {
continue;
}
}
let mut msg = format!("processing: {}", full_name);
if verbosity.is_verbose() {
if let Some(src) = f.source(db) {
let original_file = src.file_id.original_file(db);
let path = vfs.file_path(original_file);
let syntax_range = src.value.syntax().text_range();
format_to!(msg, " ({} {:?})", path, syntax_range);
}
}
if verbosity.is_spammy() {
bar.println(msg.to_string());
}
bar.set_message(&msg);
let f_id = FunctionId::from(f);
let (body, sm) = db.body_with_source_map(f_id.into());
let inference_result = db.infer(f_id.into());
let (previous_exprs, previous_unknown, previous_partially_unknown) =
(num_exprs, num_exprs_unknown, num_exprs_partially_unknown);
for (expr_id, _) in body.exprs.iter() {
let ty = &inference_result[expr_id];
num_exprs += 1;
let unknown_or_partial = if ty.is_unknown() {
num_exprs_unknown += 1;
if verbosity.is_spammy() {
if let Some((path, start, end)) =
expr_syntax_range(db, &analysis, vfs, &sm, expr_id)
{
bar.println(format!(
"{} {}:{}-{}:{}: Unknown type",
path,
start.line + 1,
start.col,
end.line + 1,
end.col,
));
} else {
bar.println(format!("{}: Unknown type", name,));
}
}
true
} else {
let mut is_partially_unknown = false;
ty.walk(&mut |ty| {
if ty.is_unknown() {
is_partially_unknown = true;
}
});
if is_partially_unknown {
num_exprs_partially_unknown += 1;
}
is_partially_unknown
};
if self.only.is_some() && verbosity.is_spammy() {
// in super-verbose mode for just one function, we print every single expression
if let Some((_, start, end)) =
expr_syntax_range(db, &analysis, vfs, &sm, expr_id)
{
bar.println(format!(
"{}:{}-{}:{}: {}",
start.line + 1,
start.col,
end.line + 1,
end.col,
ty.display(db)
));
} else {
bar.println(format!("unknown location: {}", ty.display(db)));
}
}
if unknown_or_partial && self.output == Some(OutputFormat::Csv) {
println!(
r#"{},type,"{}""#,
location_csv(db, &analysis, vfs, &sm, expr_id),
ty.display(db)
);
}
if let Some(mismatch) = inference_result.type_mismatch_for_expr(expr_id) {
num_type_mismatches += 1;
if verbosity.is_verbose() {
if let Some((path, start, end)) =
expr_syntax_range(db, &analysis, vfs, &sm, expr_id)
{
bar.println(format!(
"{} {}:{}-{}:{}: Expected {}, got {}",
path,
start.line + 1,
start.col,
end.line + 1,
end.col,
mismatch.expected.display(db),
mismatch.actual.display(db)
));
} else {
bar.println(format!(
"{}: Expected {}, got {}",
name,
mismatch.expected.display(db),
mismatch.actual.display(db)
));
}
}
if self.output == Some(OutputFormat::Csv) {
println!(
r#"{},mismatch,"{}","{}""#,
location_csv(db, &analysis, vfs, &sm, expr_id),
mismatch.expected.display(db),
mismatch.actual.display(db)
);
}
}
}
if verbosity.is_spammy() {
bar.println(format!(
"In {}: {} exprs, {} unknown, {} partial",
full_name,
num_exprs - previous_exprs,
num_exprs_unknown - previous_unknown,
num_exprs_partially_unknown - previous_partially_unknown
));
}
bar.inc(1);
}
bar.finish_and_clear();
eprintln!(
" exprs: {}, ??ty: {} ({}%), ?ty: {} ({}%), !ty: {}",
num_exprs,
num_exprs_unknown,
percentage(num_exprs_unknown, num_exprs),
num_exprs_partially_unknown,
percentage(num_exprs_partially_unknown, num_exprs),
num_type_mismatches
);
report_metric("unknown type", num_exprs_unknown, "#");
report_metric("type mismatches", num_type_mismatches, "#");
eprintln!("{:<20} {}", "Inference:", inference_sw.elapsed());
}
fn stop_watch(&self) -> StopWatch {
StopWatch::start().memory(self.memory_usage)
}
}
fn location_csv(
db: &RootDatabase,
analysis: &Analysis,
vfs: &Vfs,
sm: &BodySourceMap,
expr_id: ExprId,
) -> String {
let src = match sm.expr_syntax(expr_id) {
Ok(s) => s,
Err(SyntheticSyntax) => return "synthetic,,".to_string(),
};
let root = db.parse_or_expand(src.file_id).unwrap();
let node = src.map(|e| e.to_node(&root).syntax().clone());
let original_range = node.as_ref().original_file_range(db);
let path = vfs.file_path(original_range.file_id);
let line_index = analysis.file_line_index(original_range.file_id).unwrap();
let text_range = original_range.range;
let (start, end) =
(line_index.line_col(text_range.start()), line_index.line_col(text_range.end()));
format!("{},{}:{},{}:{}", path, start.line + 1, start.col, end.line + 1, end.col)
}
fn expr_syntax_range(
db: &RootDatabase,
analysis: &Analysis,
vfs: &Vfs,
sm: &BodySourceMap,
expr_id: ExprId,
) -> Option<(VfsPath, LineCol, LineCol)> {
let src = sm.expr_syntax(expr_id);
if let Ok(src) = src {
let root = db.parse_or_expand(src.file_id).unwrap();
let node = src.map(|e| e.to_node(&root).syntax().clone());
let original_range = node.as_ref().original_file_range(db);
let path = vfs.file_path(original_range.file_id);
let line_index = analysis.file_line_index(original_range.file_id).unwrap();
let text_range = original_range.range;
let (start, end) =
(line_index.line_col(text_range.start()), line_index.line_col(text_range.end()));
Some((path, start, end))
} else {
None
}
}
fn shuffle<T>(rng: &mut Rand32, slice: &mut [T]) {
for i in 0..slice.len() {
randomize_first(rng, &mut slice[i..]);
}
fn randomize_first<T>(rng: &mut Rand32, slice: &mut [T]) {
assert!(!slice.is_empty());
let idx = rng.rand_range(0..slice.len() as u32) as usize;
slice.swap(0, idx);
}
}
fn percentage(n: u64, total: u64) -> u64 {
(n * 100).checked_div(total).unwrap_or(100)
}
fn syntax_len(node: SyntaxNode) -> usize {
// Macro expanded code doesn't contain whitespace, so erase *all* whitespace
// to make macro and non-macro code comparable.
node.to_string().replace(|it: char| it.is_ascii_whitespace(), "").len()
}
| 37.616071 | 100 | 0.496855 |
efa38a4708f998e09b486099ff02ff40a17a19ba | 7,963 | use crate::{
environment::{
declarative_environment_record::DeclarativeEnvironmentRecord,
lexical_environment::VariableScope,
},
exec::{Executable, InterpreterState},
gc::{Finalize, Trace},
syntax::ast::node::{iteration::IterableLoopInitializer, Declaration, Node},
BoaProfiler, Context, JsResult, JsValue,
};
use std::fmt;
#[cfg(feature = "deser")]
use serde::{Deserialize, Serialize};
#[cfg_attr(feature = "deser", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Trace, Finalize, PartialEq)]
pub struct ForOfLoop {
init: Box<IterableLoopInitializer>,
iterable: Box<Node>,
body: Box<Node>,
label: Option<Box<str>>,
}
impl ForOfLoop {
pub fn new<I, B>(init: IterableLoopInitializer, iterable: I, body: B) -> Self
where
I: Into<Node>,
B: Into<Node>,
{
Self {
init: Box::new(init),
iterable: Box::new(iterable.into()),
body: Box::new(body.into()),
label: None,
}
}
pub fn init(&self) -> &IterableLoopInitializer {
&self.init
}
pub fn iterable(&self) -> &Node {
&self.iterable
}
pub fn body(&self) -> &Node {
&self.body
}
pub fn label(&self) -> Option<&str> {
self.label.as_ref().map(Box::as_ref)
}
pub fn set_label(&mut self, label: Box<str>) {
self.label = Some(label);
}
pub fn display(&self, f: &mut fmt::Formatter<'_>, indentation: usize) -> fmt::Result {
if let Some(ref label) = self.label {
write!(f, "{}: ", label)?;
}
write!(f, "for ({} of {}) ", self.init, self.iterable)?;
self.body().display(f, indentation)
}
}
impl fmt::Display for ForOfLoop {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.display(f, 0)
}
}
impl From<ForOfLoop> for Node {
fn from(for_of: ForOfLoop) -> Node {
Self::ForOfLoop(for_of)
}
}
impl Executable for ForOfLoop {
fn run(&self, context: &mut Context) -> JsResult<JsValue> {
let _timer = BoaProfiler::global().start_event("ForOf", "exec");
let iterable = self.iterable().run(context)?;
let iterator = iterable.get_iterator(context, None, None)?;
let mut result = JsValue::undefined();
loop {
{
let env = context.get_current_environment();
context.push_environment(DeclarativeEnvironmentRecord::new(Some(env)));
}
let iterator_result = iterator.next(context)?;
if iterator_result.done {
context.pop_environment();
break;
}
let next_result = iterator_result.value;
match self.init() {
IterableLoopInitializer::Identifier(ref name) => {
if context.has_binding(name.as_ref())? {
// Binding already exists
context.set_mutable_binding(
name.as_ref(),
next_result.clone(),
context.strict(),
)?;
} else {
context.create_mutable_binding(
name.as_ref(),
true,
VariableScope::Function,
)?;
context.initialize_binding(name.as_ref(), next_result)?;
}
}
IterableLoopInitializer::Var(declaration) => match declaration {
Declaration::Identifier { ident, .. } => {
if context.has_binding(ident.as_ref())? {
context.set_mutable_binding(
ident.as_ref(),
next_result,
context.strict(),
)?;
} else {
context.create_mutable_binding(
ident.as_ref(),
false,
VariableScope::Function,
)?;
context.initialize_binding(ident.as_ref(), next_result)?;
}
}
Declaration::Pattern(p) => {
for (ident, value) in p.run(Some(next_result), context)? {
if context.has_binding(ident.as_ref())? {
context.set_mutable_binding(
ident.as_ref(),
value,
context.strict(),
)?;
} else {
context.create_mutable_binding(
ident.as_ref(),
false,
VariableScope::Function,
)?;
context.initialize_binding(ident.as_ref(), value)?;
}
}
}
},
IterableLoopInitializer::Let(declaration) => match declaration {
Declaration::Identifier { ident, .. } => {
context.create_mutable_binding(
ident.as_ref(),
false,
VariableScope::Block,
)?;
context.initialize_binding(ident.as_ref(), next_result)?;
}
Declaration::Pattern(p) => {
for (ident, value) in p.run(Some(next_result), context)? {
context.create_mutable_binding(
ident.as_ref(),
false,
VariableScope::Block,
)?;
context.initialize_binding(ident.as_ref(), value)?;
}
}
},
IterableLoopInitializer::Const(declaration) => match declaration {
Declaration::Identifier { ident, .. } => {
context.create_immutable_binding(
ident.as_ref(),
false,
VariableScope::Block,
)?;
context.initialize_binding(ident.as_ref(), next_result)?;
}
Declaration::Pattern(p) => {
for (ident, value) in p.run(Some(next_result), context)? {
context.create_immutable_binding(
ident.as_ref(),
false,
VariableScope::Block,
)?;
context.initialize_binding(ident.as_ref(), value)?;
}
}
},
}
result = self.body().run(context)?;
match context.executor().get_current_state() {
InterpreterState::Break(label) => {
handle_state_with_labels!(self, label, context, break);
break;
}
InterpreterState::Continue(label) => {
handle_state_with_labels!(self, label, context, continue);
}
InterpreterState::Return => return Ok(result),
InterpreterState::Executing => {
// Continue execution.
}
}
let _ = context.pop_environment();
}
Ok(result)
}
}
| 37.21028 | 90 | 0.431747 |
567ed073086b6191ae42bc34ce5ab67543a1b2c6 | 15,449 | //! gRPC client implementation for mayastor server.
//!
//! It is not expected to be used in production env but rather for testing and
//! debugging of the server.
#![warn(unused_extern_crates)]
#[macro_use]
extern crate clap;
use bytesize::ByteSize;
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
use tonic::{transport::Channel, Code, Request, Status};
use rpc::service::mayastor_client::MayastorClient;
fn parse_share_protocol(pcol: Option<&str>) -> Result<i32, Status> {
match pcol {
None => Ok(rpc::mayastor::ShareProtocol::None as i32),
Some("nvmf") => Ok(rpc::mayastor::ShareProtocol::Nvmf as i32),
Some("iscsi") => Ok(rpc::mayastor::ShareProtocol::Iscsi as i32),
Some("none") => Ok(rpc::mayastor::ShareProtocol::None as i32),
Some(_) => Err(Status::new(
Code::Internal,
"Invalid value of share protocol".to_owned(),
)),
}
}
async fn create_pool(
mut client: MayastorClient<Channel>,
matches: &ArgMatches<'_>,
verbose: bool,
) -> Result<(), Status> {
let name = matches.value_of("POOL").unwrap().to_owned();
let disks = matches
.values_of("DISK")
.unwrap()
.map(|dev| dev.to_owned())
.collect();
let block_size = value_t!(matches.value_of("block-size"), u32).unwrap_or(0);
if verbose {
println!("Creating the pool {}", name);
}
let _ = client
.create_pool(Request::new(rpc::mayastor::CreatePoolRequest {
name,
disks,
block_size,
}))
.await?;
Ok(())
}
async fn destroy_pool(
mut client: MayastorClient<Channel>,
matches: &ArgMatches<'_>,
verbose: bool,
) -> Result<(), Status> {
let name = matches.value_of("POOL").unwrap().to_owned();
if verbose {
println!("Destroying the pool {}", name);
}
client
.destroy_pool(Request::new(rpc::mayastor::DestroyPoolRequest {
name,
}))
.await?;
Ok(())
}
async fn list_pools(
mut client: MayastorClient<Channel>,
verbose: bool,
quiet: bool,
) -> Result<(), Status> {
if verbose {
println!("Requesting a list of pools");
}
let f = client
.list_pools(Request::new(rpc::mayastor::Null {}))
.await?;
let pools = &f.get_ref().pools;
if pools.is_empty() && !quiet {
println!("No pools have been created");
} else {
if !quiet {
println!(
"{: <20} {: <8} {: >12} {: >12} DISKS",
"NAME", "STATE", "CAPACITY", "USED"
);
}
for p in pools {
print!(
"{: <20} {: <8} {: >12} {: >12} ",
p.name,
match rpc::mayastor::PoolState::from_i32(p.state).unwrap() {
rpc::mayastor::PoolState::Online => "online",
rpc::mayastor::PoolState::Degraded => "degraded",
rpc::mayastor::PoolState::Faulty => "faulty",
},
ByteSize::b(p.capacity).to_string_as(true),
ByteSize::b(p.used).to_string_as(true),
);
for disk in &p.disks {
print!(" {}", disk);
}
println!();
}
}
Ok(())
}
async fn create_replica(
mut client: MayastorClient<Channel>,
matches: &ArgMatches<'_>,
verbose: bool,
) -> Result<(), Status> {
let pool = matches.value_of("POOL").unwrap().to_owned();
let uuid = matches.value_of("UUID").unwrap().to_owned();
let size = value_t!(matches.value_of("size"), u64).unwrap();
let thin = matches.is_present("thin");
let share = parse_share_protocol(matches.value_of("protocol"))?;
if verbose {
println!("Creating replica {} on pool {}", uuid, pool);
}
let resp = client
.create_replica(Request::new(rpc::mayastor::CreateReplicaRequest {
uuid,
pool,
thin,
share,
size: size * (1024 * 1024),
}))
.await?;
println!("{}", resp.get_ref().uri);
Ok(())
}
async fn destroy_replica(
mut client: MayastorClient<Channel>,
matches: &ArgMatches<'_>,
verbose: bool,
) -> Result<(), Status> {
let uuid = matches.value_of("UUID").unwrap().to_owned();
if verbose {
println!("Destroying replica {}", uuid);
}
client
.destroy_replica(Request::new(rpc::mayastor::DestroyReplicaRequest {
uuid,
}))
.await?;
Ok(())
}
async fn share_replica(
mut client: MayastorClient<Channel>,
matches: &ArgMatches<'_>,
verbose: bool,
) -> Result<(), Status> {
let uuid = matches.value_of("UUID").unwrap().to_owned();
let share = parse_share_protocol(matches.value_of("PROTOCOL"))?;
if verbose {
println!("Sharing replica {}", uuid);
}
let resp = client
.share_replica(Request::new(rpc::mayastor::ShareReplicaRequest {
uuid,
share,
}))
.await?;
println!("{}", resp.get_ref().uri);
Ok(())
}
async fn list_replicas(
mut client: MayastorClient<Channel>,
verbose: bool,
quiet: bool,
) -> Result<(), Status> {
if verbose {
println!("Requesting a list of replicas");
}
let resp = client
.list_replicas(Request::new(rpc::mayastor::Null {}))
.await?;
let replicas = &resp.get_ref().replicas;
if replicas.is_empty() && !quiet {
println!("No replicas have been created");
} else {
if !quiet {
println!(
"{: <15} {: <36} {: <8} {: <8} {: <10} URI",
"POOL", "NAME", "THIN", "SHARE", "SIZE",
);
}
for r in replicas {
println!(
"{: <15} {: <36} {: <8} {: <8} {: <10} {}",
r.pool,
r.uuid,
r.thin,
match rpc::mayastor::ShareProtocol::from_i32(r.share) {
Some(rpc::mayastor::ShareProtocol::None) => {
"none"
}
Some(rpc::mayastor::ShareProtocol::Nvmf) => {
"nvmf"
}
Some(rpc::mayastor::ShareProtocol::Iscsi) => {
"iscsi"
}
None => "unknown",
},
ByteSize::b(r.size).to_string_as(true),
r.uri,
);
}
}
Ok(())
}
async fn stat_replicas(
mut client: MayastorClient<Channel>,
verbose: bool,
quiet: bool,
) -> Result<(), Status> {
if verbose {
println!("Requesting replicas stats");
}
let resp = client
.stat_replicas(Request::new(rpc::mayastor::Null {}))
.await?;
let replicas = &resp.get_ref().replicas;
if replicas.is_empty() && !quiet {
println!("No replicas have been created");
} else {
if !quiet {
println!(
"{: <20} {: <36} {: >10} {: >10} {: >10} {: >10}",
"POOL", "NAME", "RDCNT", "WRCNT", "RDBYTES", "WRBYTES",
);
}
for r in replicas {
let stats = r.stats.as_ref().unwrap();
println!(
"{: <20} {: <36} {: >10} {: >10} {: >10} {: >10}",
r.pool,
r.uuid,
stats.num_read_ops,
stats.num_write_ops,
stats.bytes_read,
stats.bytes_written,
);
}
}
Ok(())
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let matches = App::new("Mayastor grpc client")
.version("0.1")
.settings(&[AppSettings::SubcommandRequiredElseHelp,
AppSettings::ColoredHelp, AppSettings::ColorAlways])
.about("Client for mayastor gRPC server")
.arg(
Arg::with_name("address")
.short("a")
.long("address")
.value_name("HOST")
.help("IP address of mayastor server (default 127.0.0.1)")
.takes_value(true),
)
.arg(
Arg::with_name("port")
.short("p")
.long("port")
.value_name("NUMBER")
.help("Port number of mayastor server (default 10124)")
.takes_value(true),
)
.arg(
Arg::with_name("verbose")
.short("v")
.long("verbose")
.multiple(true)
.help("Verbose output"),
)
.arg(
Arg::with_name("quiet")
.short("q")
.long("quiet")
.help("Do not print any output except for list records"),
)
.subcommand(
SubCommand::with_name("pool")
.about("Storage pool management")
.subcommand(
SubCommand::with_name("create")
.about("Create storage pool")
.arg(
Arg::with_name("block-size")
.short("b")
.long("block-size")
.value_name("NUMBER")
.help("block size of the underlying devices")
.takes_value(true),
)
.arg(
Arg::with_name("POOL")
.help("Storage pool name")
.required(true)
.index(1),
)
.arg(
Arg::with_name("DISK")
.help("Disk device files")
.required(true)
.multiple(true)
.index(2),
),
)
.subcommand(
SubCommand::with_name("destroy")
.about("Destroy storage pool")
.arg(
Arg::with_name("POOL")
.help("Storage pool name")
.required(true)
.index(1),
),
)
.subcommand(SubCommand::with_name("list").about("List storage pools")),
)
.subcommand(
SubCommand::with_name("replica")
.about("Replica management")
.subcommand(
SubCommand::with_name("create")
.about("Create replica on pool")
.arg(
Arg::with_name("POOL")
.help("Storage pool name")
.required(true)
.index(1),
)
.arg(
Arg::with_name("UUID")
.help("Unique replica uuid")
.required(true)
.index(2),
)
.arg(
Arg::with_name("protocol")
.short("p")
.long("protocol")
.value_name("PROTOCOL")
.help("Name of a protocol (nvmf, iscsi) used for sharing the replica (default none)")
.takes_value(true),
)
.arg(
Arg::with_name("size")
.short("s")
.long("size")
.value_name("NUMBER")
.help("Size of the replica in MiB")
.takes_value(true)
.required(true),
)
.arg(
Arg::with_name("thin")
.short("t")
.long("thin")
.help("Replica is thin provisioned (default false)")
.takes_value(false),
),
)
.subcommand(
SubCommand::with_name("destroy")
.about("Destroy replica")
.arg(
Arg::with_name("UUID")
.help("Replica uuid")
.required(true)
.index(1),
),
)
.subcommand(
SubCommand::with_name("share")
.about("Share or unshare replica")
.arg(
Arg::with_name("UUID")
.help("Replica uuid")
.required(true)
.index(1),
)
.arg(
Arg::with_name("PROTOCOL")
.help("Replica uuid")
.help("Name of a protocol (nvmf, iscsi) used for sharing or \"none\" to unshare the replica")
.required(true)
.index(2),
),
)
.subcommand(SubCommand::with_name("list").about("List replicas"))
.subcommand(SubCommand::with_name("stats").about("IO stats of replicas")),
)
.get_matches();
let endpoint = {
let addr = matches.value_of("address").unwrap_or("127.0.0.1");
let port = value_t!(matches.value_of("port"), u16).unwrap_or(10124);
format!("{}:{}", addr, port)
};
let verbose = matches.occurrences_of("verbose") > 0;
let quiet = matches.is_present("quiet");
let uri = format!("http://{}", endpoint);
let client = MayastorClient::connect(uri).await?;
match matches.subcommand() {
("pool", Some(m)) => match m.subcommand() {
("create", Some(m)) => create_pool(client, &m, verbose).await?,
("list", Some(_m)) => list_pools(client, verbose, quiet).await?,
("destroy", Some(m)) => destroy_pool(client, &m, quiet).await?,
_ => {}
},
("replica", Some(m)) => match m.subcommand() {
("create", Some(matches)) => {
create_replica(client, matches, verbose).await?
}
("destroy", Some(matches)) => {
destroy_replica(client, matches, verbose).await?
}
("share", Some(matches)) => {
share_replica(client, matches, verbose).await?
}
("list", Some(_matches)) => {
list_replicas(client, verbose, quiet).await?
}
("stats", Some(_matches)) => {
stat_replicas(client, verbose, quiet).await?
}
_ => {}
},
_ => {}
};
Ok(())
}
| 32.455882 | 125 | 0.430449 |
486a297e717cc9ab9e442348ecfa1d16b00ca10a | 249 | //! Lowers AST into HIR.
#![deny(missing_debug_implementations)]
#![deny(missing_docs)]
#![deny(rust_2018_idioms)]
mod expr;
mod item;
mod root;
mod simp;
mod stmt;
mod ty;
mod util;
pub use root::get;
pub use util::{Lowered, PragmaError, Ptrs};
| 14.647059 | 43 | 0.710843 |
39fab0ea719fa04aa16dfac292f8c15f0033ec03 | 5,543 | use egui::*;
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct LayoutTest {
// Identical to contents of `egui::Layout`
layout: LayoutSettings,
// Extra for testing wrapping:
wrap_column_width: f32,
wrap_row_height: f32,
}
impl Default for LayoutTest {
fn default() -> Self {
Self {
layout: LayoutSettings::top_down(),
wrap_column_width: 150.0,
wrap_row_height: 20.0,
}
}
}
#[derive(Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct LayoutSettings {
// Similar to the contents of `egui::Layout`
main_dir: Direction,
main_wrap: bool,
cross_align: Align,
cross_justify: bool,
}
impl Default for LayoutSettings {
fn default() -> Self {
Self::top_down()
}
}
impl LayoutSettings {
fn top_down() -> Self {
Self {
main_dir: Direction::TopDown,
main_wrap: false,
cross_align: Align::Min,
cross_justify: false,
}
}
fn top_down_justified_centered() -> Self {
Self {
main_dir: Direction::TopDown,
main_wrap: false,
cross_align: Align::Center,
cross_justify: true,
}
}
fn horizontal_wrapped() -> Self {
Self {
main_dir: Direction::LeftToRight,
main_wrap: true,
cross_align: Align::Center,
cross_justify: false,
}
}
fn layout(&self) -> Layout {
Layout::from_main_dir_and_cross_align(self.main_dir, self.cross_align)
.with_main_wrap(self.main_wrap)
.with_cross_justify(self.cross_justify)
}
}
impl super::Demo for LayoutTest {
fn name(&self) -> &'static str {
"Layout Test"
}
fn show(&mut self, ctx: &egui::Context, open: &mut bool) {
egui::Window::new(self.name())
.open(open)
.resizable(false)
.show(ctx, |ui| {
use super::View as _;
self.ui(ui);
});
}
}
impl super::View for LayoutTest {
fn ui(&mut self, ui: &mut Ui) {
ui.label("Tests and demonstrates the limits of the egui layouts");
self.content_ui(ui);
Resize::default()
.default_size([150.0, 200.0])
.show(ui, |ui| {
if self.layout.main_wrap {
if self.layout.main_dir.is_horizontal() {
ui.allocate_ui(
vec2(ui.available_size_before_wrap().x, self.wrap_row_height),
|ui| ui.with_layout(self.layout.layout(), demo_ui),
);
} else {
ui.allocate_ui(
vec2(self.wrap_column_width, ui.available_size_before_wrap().y),
|ui| ui.with_layout(self.layout.layout(), demo_ui),
);
}
} else {
ui.with_layout(self.layout.layout(), demo_ui);
}
});
ui.label("Resize to see effect");
}
}
impl LayoutTest {
pub fn content_ui(&mut self, ui: &mut Ui) {
ui.horizontal(|ui| {
ui.selectable_value(&mut self.layout, LayoutSettings::top_down(), "Top-down");
ui.selectable_value(
&mut self.layout,
LayoutSettings::top_down_justified_centered(),
"Top-down, centered and justified",
);
ui.selectable_value(
&mut self.layout,
LayoutSettings::horizontal_wrapped(),
"Horizontal wrapped",
);
});
ui.horizontal(|ui| {
ui.label("Main Direction:");
for &dir in &[
Direction::LeftToRight,
Direction::RightToLeft,
Direction::TopDown,
Direction::BottomUp,
] {
ui.radio_value(&mut self.layout.main_dir, dir, format!("{:?}", dir));
}
});
ui.horizontal(|ui| {
ui.checkbox(&mut self.layout.main_wrap, "Main wrap")
.on_hover_text("Wrap when next widget doesn't fit the current row/column");
if self.layout.main_wrap {
if self.layout.main_dir.is_horizontal() {
ui.add(Slider::new(&mut self.wrap_row_height, 0.0..=200.0).text("Row height"));
} else {
ui.add(
Slider::new(&mut self.wrap_column_width, 0.0..=200.0).text("Column width"),
);
}
}
});
ui.horizontal(|ui| {
ui.label("Cross Align:");
for &align in &[Align::Min, Align::Center, Align::Max] {
ui.radio_value(&mut self.layout.cross_align, align, format!("{:?}", align));
}
});
ui.checkbox(&mut self.layout.cross_justify, "Cross Justified")
.on_hover_text("Try to fill full width/height (e.g. buttons)");
}
}
fn demo_ui(ui: &mut Ui) {
ui.add(egui::Label::new("Wrapping text followed by example widgets:").wrap(true));
let mut dummy = false;
ui.checkbox(&mut dummy, "checkbox");
ui.radio_value(&mut dummy, false, "radio");
let _ = ui.button("button");
}
| 30.96648 | 99 | 0.517951 |
798cfbb2e1f4a1c8329c50a105659c21ba2ad7c4 | 4,148 | // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
/// This module implements our vsock connection state machine. The heavy lifting is done by
/// `connection::VsockConnection`, while this file only defines some constants and helper structs.
mod connection;
mod txbuf;
pub use self::connection::VsockConnection;
pub mod defs {
/// Vsock connection TX buffer capacity.
pub const CONN_TX_BUF_SIZE: usize = 64 * 1024;
/// After the guest thinks it has filled our TX buffer up to this limit (in bytes), we'll send
/// them a credit update packet, to let them know we can handle more.
pub const CONN_CREDIT_UPDATE_THRESHOLD: usize = CONN_TX_BUF_SIZE - 4 * 4 * 1024;
/// Connection request timeout, in millis.
pub const CONN_REQUEST_TIMEOUT_MS: u64 = 2000;
/// Connection graceful shutdown timeout, in millis.
pub const CONN_SHUTDOWN_TIMEOUT_MS: u64 = 2000;
}
#[derive(Debug)]
pub enum Error {
/// Attempted to push data to a full TX buffer.
TxBufFull,
/// An I/O error occurred, when attempting to flush the connection TX buffer.
TxBufFlush(std::io::Error),
/// An I/O error occurred, when attempting to write data to the host-side stream.
StreamWrite(std::io::Error),
}
type Result<T> = std::result::Result<T, Error>;
/// A vsock connection state.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ConnState {
/// The connection has been initiated by the host end, but is yet to be confirmed by the guest.
LocalInit,
/// The connection has been initiated by the guest, but we are yet to confirm it, by sending
/// a response packet (VSOCK_OP_RESPONSE).
PeerInit,
/// The connection handshake has been performed successfully, and data can now be exchanged.
Established,
/// The host (AF_UNIX) socket was closed.
LocalClosed,
/// A VSOCK_OP_SHUTDOWN packet was received from the guest. The tuple represents the guest R/W
/// indication: (will_not_recv_anymore_data, will_not_send_anymore_data).
PeerClosed(bool, bool),
/// The connection is scheduled to be forcefully terminated as soon as possible.
Killed,
}
/// An RX indication, used by `VsockConnection` to schedule future `recv_pkt()` responses.
/// For instance, after being notified that there is available data to be read from the host stream
/// (via `notify()`), the connection will store a `PendingRx::Rw` to be later inspected by
/// `recv_pkt()`.
#[derive(Clone, Copy, PartialEq)]
enum PendingRx {
/// We need to yield a connection request packet (VSOCK_OP_REQUEST).
Request = 0,
/// We need to yield a connection response packet (VSOCK_OP_RESPONSE).
Response = 1,
/// We need to yield a forceful connection termination packet (VSOCK_OP_RST).
Rst = 2,
/// We need to yield a data packet (VSOCK_OP_RW), by reading from the AF_UNIX socket.
Rw = 3,
/// We need to yield a credit update packet (VSOCK_OP_CREDIT_UPDATE).
CreditUpdate = 4,
}
impl PendingRx {
/// Transform the enum value into a bitmask, that can be used for set operations.
fn into_mask(self) -> u16 {
1u16 << (self as u16)
}
}
/// A set of RX indications (`PendingRx` items).
struct PendingRxSet {
data: u16,
}
impl PendingRxSet {
/// Insert an item into the set.
fn insert(&mut self, it: PendingRx) {
self.data |= it.into_mask();
}
/// Remove an item from the set and return:
/// - true, if the item was in the set; or
/// - false, if the item wasn't in the set.
fn remove(&mut self, it: PendingRx) -> bool {
let ret = self.contains(it);
self.data &= !it.into_mask();
ret
}
/// Check if an item is present in this set.
fn contains(&self, it: PendingRx) -> bool {
self.data & it.into_mask() != 0
}
/// Check if the set is empty.
fn is_empty(&self) -> bool {
self.data == 0
}
}
/// Create a set containing only one item.
impl From<PendingRx> for PendingRxSet {
fn from(it: PendingRx) -> Self {
Self {
data: it.into_mask(),
}
}
}
| 34.566667 | 99 | 0.669961 |
729a585b2d8095fd32843a9f85002d9f28acdb45 | 861 | // Copyright 2018 Joshua Minter
//
// 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.
include!(concat!(env!("OUT_DIR"), "/gl.rs"));
pub trait CheckError {
fn check_error(&self);
}
impl CheckError for Gl {
fn check_error(&self) {
unsafe {
let error = self.GetError();
if error != NO_ERROR {
panic!("glGetError = 0x{:X}", error)
}
}
}
} | 28.7 | 75 | 0.700348 |
f897b5930d03ba8dbbe6683dcf88f125c0321e92 | 26,497 | use crate::{
ai::negamax,
character::{Character, CharacterPlugin, DialogueFace, DialogueText, Say},
choss::{draw_choss, piece_tex_name, ChossGame, SIZE},
piece::{Action, Color as PieceColor, Piece},
pos::Pos,
utils::screen_to_world,
};
use bevy::prelude::*;
use bevy::{render::color::Color, tasks::Task};
use rand::seq::SliceRandom;
use std::collections::{HashMap, HashSet};
#[derive(Component)]
struct MovingTo(Transform);
#[derive(Component)]
struct Die;
#[derive(Component)]
struct PromoteTo(Piece, PieceColor);
#[derive(PartialEq, Eq)]
enum GameStatus {
Playing,
Draw,
Win,
Loss,
Preparing,
Placing,
Ending,
}
impl Default for GameStatus {
fn default() -> Self {
GameStatus::Preparing
}
}
#[derive(Default)]
struct Game {
opponents: Vec<Entity>,
opponent: usize,
to_play: Option<(Pos, Vec<Action>)>,
last_eval: Option<f32>,
lines_sent: HashSet<String>,
status: GameStatus,
cached_moves: Vec<(f32, Pos, Vec<Action>)>,
turn: u32,
last_state: Option<ChossGame>,
carl_lines: Vec<String>,
last_move_time: f64,
}
impl Game {
fn new() -> Self {
let mut carl_lines = vec![
"Oh... that won't do.".to_string(),
"Mh, that doesn't work.".to_string(),
"Nope, this is not good.".to_string(),
"Ugh, I need another move !".to_string(),
"Again ...".to_string(),
];
carl_lines.reverse();
Game {
carl_lines,
..Default::default()
}
}
fn opponent(&self) -> Entity {
self.opponents[self.opponent]
}
fn get_dialogue(&mut self, score: f32) -> Option<(String, String)> {
let mut res = None;
if self.opponent == 0 {
// Alice's dialogues
if let Some(last_eval) = self.last_eval {
let score_diff = last_eval - score;
println!(
"prev e: {}, new e: {}, diff: {}",
last_eval, score, score_diff
);
if score < -5. {
res = Some(("neutral", "Oof, now I'm in trouble ..."));
}
if score_diff.abs() > 2. {
if score_diff < 0. {
// player made a mistake (probably)
res = Some((
"neutral",
"Oh, that looks like a mistake ?\nWell it happens.",
));
} else if score < 0. {
// alice made a mistake (probably)
res = Some(("weary", "Ugh, I think I blundered...\nDon't you wish you could \nundo your moves sometimes ?"));
}
}
} else {
res = Some(("happy", "You got it !\nNow may the best player win !"));
}
} else if self.opponent == 1 {
// Carl's dialogues
if let Some(last_eval) = self.last_eval {
let score_diff = last_eval - score;
if score_diff.abs() > 2. {
if score_diff < 0. {
// player made a mistake (probably)
res = Some(("smug", "All according to my calculations."));
} else if self.should_undo(score) {
// Carl made a mistake (probably)
let line = if self.carl_lines.len() > 1 {
self.carl_lines.pop().unwrap()
} else {
self.carl_lines[0].clone()
};
return Some(("neutral".to_string(), line));
} else if score < 0. {
res = Some(("panicked", "Nothing is working !!"));
}
}
}
}
// make sure no dialogue line is sent twice
if let Some((face, line)) = res {
if !self.lines_sent.insert(line.to_string()) {
return None;
}
return Some((face.to_string(), line.to_string()));
}
None
}
fn cached_moves_mut(&mut self, turn: u32) -> Option<&mut Vec<(f32, Pos, Vec<Action>)>> {
if turn == self.turn {
return Some(&mut self.cached_moves);
}
None
}
fn update_cached_moves(&mut self, moves: Vec<(f32, Pos, Vec<Action>)>, turn: u32) {
self.cached_moves = moves;
self.turn = turn;
}
fn should_undo(&self, score: f32) -> bool {
if self.opponent == 1 && self.cached_moves.len() > 0 {
if let Some(last_eval) = self.last_eval {
return last_eval - score > 2. && score < 2.;
}
}
false
}
}
#[derive(Component)]
struct UndoingComp {
max_speed: f32,
speed: f32,
ascending: bool,
}
impl UndoingComp {
fn new() -> Self {
UndoingComp {
max_speed: 8000.,
speed: 0.,
ascending: true,
}
}
}
fn create_opponents(mut commands: Commands, server: Res<AssetServer>, mut game: ResMut<Game>) {
let alice_entity = commands
.spawn()
.insert(Character::new(
"Alice",
vec![
"happy".to_string(),
"neutral".to_string(),
"weary".to_string(),
],
&server,
))
.id();
game.opponents.push(alice_entity);
let carl_entity = commands
.spawn()
.insert(Character::new(
"Carl Blok",
vec![
"exhausted".to_string(),
"neutral".to_string(),
"panicked".to_string(),
"smug".to_string(),
],
&server,
))
.id();
game.opponents.push(carl_entity);
}
fn play_move(
mut commands: Commands,
mut choss: ResMut<ChossGame>,
mut piece_ents: ResMut<HashMap<Pos, Entity>>,
mut game: ResMut<Game>,
query_say: Query<(), With<Say>>,
query_undo: Query<(), With<UndoingComp>>,
mut query_text: Query<&mut Text, With<DialogueText>>,
mut query_face: Query<&mut Handle<Image>, With<DialogueFace>>,
server: Res<AssetServer>,
audio: Res<Audio>,
time: Res<Time>,
) {
// only play the move if no one's talking and no one's undoing
if query_say.is_empty()
&& query_undo.is_empty()
&& time.seconds_since_startup() - game.last_move_time > 1.
{
if let Some((pos, actions)) = &game.to_play {
let color = choss.turn_color();
choss.play(*pos, actions);
let ent = *piece_ents.get(&pos).unwrap();
let mut is_take = false;
for action in actions {
match action {
Action::Go(new_pos) => {
commands
.entity(ent)
.insert(MovingTo(choss.board_to_world(*new_pos)));
// if anything was on this new square, it should die
if let Some(o_ent) = piece_ents.get(&new_pos) {
is_take = true;
commands.entity(*o_ent).insert(Die);
}
piece_ents.remove_entry(&pos);
piece_ents.insert(*new_pos, ent);
}
Action::Take(new_pos) => {
let o_ent = *piece_ents.get(&new_pos).unwrap();
commands.entity(o_ent).insert(Die);
piece_ents.remove_entry(&new_pos);
is_take = true;
}
Action::Promotion(new_piece) => {
commands.entity(ent).insert(PromoteTo(*new_piece, color));
}
}
}
if color == choss.player {
if let Ok(mut text) = query_text.get_single_mut() {
text.sections[0].value = "".to_string();
}
if let Ok(mut face) = query_face.get_single_mut() {
*face = server.load("empty.png");
}
}
if choss.board.is_checked(color.next()) {
audio.play(server.load("sounds/check.ogg"));
} else if is_take {
audio.play(server.load("sounds/take.ogg"));
} else {
audio.play(server.load("sounds/move.ogg"));
}
game.to_play = None;
// check if the game is over
if choss.board.moves(color.next(), true).len() == 0 {
if choss.board.is_checked(color.next()) {
if color == choss.player {
game.status = GameStatus::Win;
} else {
game.status = GameStatus::Loss;
}
} else {
game.status = GameStatus::Draw;
}
}
game.last_move_time = time.seconds_since_startup();
}
}
}
fn mouse_button_input(
q_camera: Query<(&Camera, &GlobalTransform)>,
q_say: Query<(), With<Say>>,
buttons: Res<Input<MouseButton>>,
windows: Res<Windows>,
mut selected: ResMut<SelectedSquare>,
mut game: ResMut<Game>,
choss: ResMut<ChossGame>,
) {
if buttons.just_released(MouseButton::Left) {
// only take input when no one's talking
if q_say.is_empty() && game.status == GameStatus::Playing {
let window = windows.get_primary().unwrap();
if let Some(screen_pos) = window.cursor_position() {
let (camera, camera_transform) = q_camera.single();
let world_pos: Vec2 = screen_to_world(window, camera, camera_transform, screen_pos);
let pos = choss.world_to_board(world_pos);
if choss.board.in_bound(pos) {
if let Some(old_pos) = selected.0 {
// if the old and new pos correspond to a playable action, play it
if let Some(actions) = choss.playable_move(old_pos, pos) {
game.to_play = Some((old_pos, actions));
selected.0 = None;
} else {
selected.0 = Some(pos);
}
} else {
selected.0 = Some(pos);
}
} else {
selected.0 = None;
}
}
}
}
}
#[derive(Component)]
struct MoveDisplay;
fn display_moves(
query: Query<Entity, With<MoveDisplay>>,
mut commands: Commands,
selected: Res<SelectedSquare>,
choss: Res<ChossGame>,
server: Res<AssetServer>,
) {
if selected.is_changed() {
// despawn all previously shown MoveDisplays
for move_display in query.iter() {
commands.entity(move_display).despawn();
}
// check if the new selected pos corresponds to a player piece
if let Some(pos) = selected.0 {
if let Some(moves) = choss.playable_moves(pos) {
// spawn a move display for each move of this piece
let sprite = SpriteBundle {
sprite: Sprite {
color: Color::rgba(0., 0., 0., 0.5),
custom_size: Some(Vec2::new(SIZE as f32 / 2.5, SIZE as f32 / 2.5)),
..Default::default()
},
texture: server.load("circle.png"),
..Default::default()
};
for actions in moves {
for action in actions {
if let Action::Go(go_pos) = action {
let mut sprite_clone = sprite.clone();
sprite_clone.transform = choss.board_to_world(go_pos);
commands.spawn_bundle(sprite_clone).insert(MoveDisplay);
}
}
}
}
}
}
}
fn move_to(
mut commands: Commands,
mut query: Query<(Entity, &mut Transform, &MovingTo)>,
time: Res<Time>,
) {
for (ent, mut transform, moving_to) in query.iter_mut() {
let mut diff = moving_to.0.translation - transform.translation;
let mut length = time.delta_seconds() * SIZE as f32 * 20.;
// the piece finished moving
if length >= diff.length() {
length = diff.length();
commands.entity(ent).remove::<MovingTo>();
}
if length > 0. {
diff = length * diff / diff.length();
transform.translation = transform.translation + diff;
}
}
}
fn die(mut commands: Commands, mut query: Query<Entity, With<Die>>) {
for ent in query.iter_mut() {
// for now we just despawn the entity, might do fancy things later
commands.entity(ent).despawn();
}
}
fn promote(
mut commands: Commands,
mut query: Query<(Entity, &mut Handle<Image>, &PromoteTo)>,
server: Res<AssetServer>,
) {
for (entity, mut image, promote) in query.iter_mut() {
commands.entity(entity).remove::<PromoteTo>();
*image = server.load(
format!(
"choss_pieces/{}.png",
piece_tex_name(&promote.0, &promote.1)
)
.as_str(),
);
}
}
#[derive(Component)]
struct WaitUntil(f64);
#[derive(Component)]
struct AITask(Task<Vec<(f32, Pos, Vec<Action>)>>);
fn start_ai_turn(
mut commands: Commands,
mut game: ResMut<Game>,
choss: Res<ChossGame>,
moving_query: Query<(), With<MovingTo>>,
query_undo: Query<(), With<UndoingComp>>,
) {
if moving_query.is_empty()
&& query_undo.is_empty()
&& game.status == GameStatus::Playing
&& choss.player != choss.turn_color()
&& game.to_play.is_none()
{
// play the AI move
if let Some(cached_moves) = game.cached_moves_mut(choss.turn) {
let (_, pos, actions) = cached_moves.pop().unwrap();
if cached_moves.len() == 0 {
commands
.entity(game.opponent())
.insert(Say::new("panicked", "If this doesn't work ..."));
}
game.to_play = Some((pos, actions));
} else {
let value = choss.remaining_value();
let depth = if value < 5. {
4
} else if value < 10. {
2
} else {
1
};
println!("thinking with base depth {}", depth);
let moves = negamax(&choss.board, choss.turn_color(), depth);
// Randomly pick a move with that's not too far away from best in the 3 first moves
let best_move = moves[0].clone();
let best_score = best_move.0;
let mut filtered_moves: Vec<_> = moves
.into_iter()
.take(3)
.filter(|(score, _, _)| *score >= best_score - 3.)
.collect();
if filtered_moves.len() == 0 {
// this shouldn't be possible but it seems like it is lol
println!("wtf ? {}", best_score);
filtered_moves = vec![best_move];
}
filtered_moves.shuffle(&mut rand::thread_rng());
let (_, pos, actions) = filtered_moves.pop().unwrap();
if let Some((face, text)) = game.get_dialogue(best_score) {
commands
.entity(game.opponent())
.insert(Say::new(face, text));
}
// check if we must undo here
if game.should_undo(best_score) {
commands.spawn().insert(UndoingComp::new());
} else {
game.last_state = Some((*choss).clone());
game.last_eval = Some(best_score);
game.to_play = Some((pos, actions));
game.update_cached_moves(filtered_moves, choss.turn);
}
}
}
}
fn undo(
mut commands: Commands,
query_say: Query<(), With<Say>>,
mut query_cam: Query<&mut Transform, With<Camera>>,
mut query_undo: Query<(Entity, &mut UndoingComp)>,
mut query_text: Query<&mut Text, With<DialogueText>>,
mut query_face: Query<&mut Handle<Image>, With<DialogueFace>>,
mut game: ResMut<Game>,
mut choss: ResMut<ChossGame>,
server: Res<AssetServer>,
time: Res<Time>,
) {
if query_say.is_empty() {
if let Ok((entity, mut undoingcomp)) = query_undo.get_single_mut() {
if let Ok(mut transform) = query_cam.get_single_mut() {
transform.translation.x += undoingcomp.speed * time.delta_seconds();
if transform.translation.x > 1000. {
transform.translation.x = -1000.;
}
if undoingcomp.ascending {
undoingcomp.speed += undoingcomp.max_speed * 0.5 * time.delta_seconds();
if undoingcomp.speed > undoingcomp.max_speed {
// "zenith" of the undoing, we can replace the board here
if let Ok(mut text) = query_text.get_single_mut() {
text.sections[0].value = "".to_string();
}
if let Ok(mut face) = query_face.get_single_mut() {
*face = server.load("empty.png");
}
*choss = game.last_state.clone().unwrap();
game.status = GameStatus::Placing;
undoingcomp.speed = undoingcomp.max_speed;
undoingcomp.ascending = false;
}
} else {
undoingcomp.speed -= undoingcomp.max_speed * 0.5 * time.delta_seconds();
if undoingcomp.speed < 400. {
// undoing is over
game.last_move_time = time.seconds_since_startup() + 1.;
undoingcomp.speed = 0.;
transform.translation.x = 0.;
commands.entity(entity).despawn();
}
}
}
}
}
}
fn clean_up_pieces(commands: &mut Commands, piece_ents: &mut HashMap<Pos, Entity>) {
for entity in piece_ents.values() {
commands.entity(*entity).despawn();
}
piece_ents.clear();
}
fn start_game(
query_say: Query<(), With<Say>>,
mut commands: Commands,
mut game: ResMut<Game>,
mut choss: ResMut<ChossGame>,
) {
if query_say.is_empty() && game.status == GameStatus::Preparing {
if game.opponent == 0 {
// start the alice game
commands.entity(game.opponent()).insert(Say::new(
"happy",
"Welcome to the Choss club !\n\
It's your first game right ?\n\
Well you win if you capture my King,\n\
the piece with a cross on its head.\n\
Select a white piece to make a move.",
));
} else {
// start the carl game
commands.entity(game.opponent()).insert(Say::new(
"smug",
"My name's Carl Brok.\nI've never lost a game here,\nso I don't expect much from you\nbut let's see what you got.",
));
}
// setup the board
*choss = ChossGame::new(PieceColor::White);
game.last_eval = Some(0.);
game.cached_moves = Vec::new();
game.status = GameStatus::Placing;
}
}
fn place_pieces(
mut commands: Commands,
mut piece_ents: ResMut<HashMap<Pos, Entity>>,
mut game: ResMut<Game>,
choss: Res<ChossGame>,
server: Res<AssetServer>,
) {
if game.status == GameStatus::Placing {
clean_up_pieces(&mut commands, &mut piece_ents);
for (i, square) in choss.board.squares.iter().enumerate() {
if let Some((color, piece)) = square {
let handle = server
.load(format!("choss_pieces/{}.png", piece_tex_name(piece, color)).as_str());
let pos = choss.board.pos(i);
piece_ents.insert(
pos,
commands
.spawn_bundle(SpriteBundle {
sprite: Sprite {
custom_size: Some(Vec2::new(SIZE as f32 * 0.8, SIZE as f32 * 0.8)),
..Default::default()
},
texture: handle,
transform: choss.board_to_world(pos),
..Default::default()
})
.id(),
);
}
}
game.status = GameStatus::Playing;
}
}
fn end_game(mut commands: Commands, mut game: ResMut<Game>) {
if game.status == GameStatus::Win
|| game.status == GameStatus::Loss
|| game.status == GameStatus::Draw
{
if game.opponent == 0 {
// end the alice game
if game.status == GameStatus::Win {
commands.entity(game.opponent()).insert(Say::new(
"happy",
"Wow you actually won ! Amazing !\nWell, your next opponent won't be as easy.\nHe's kinda annoying but really strong.",
));
} else if game.status == GameStatus::Loss {
commands.entity(game.opponent()).insert(Say::new(
"happy",
"Chockmate ! I won but it's okay,\nit was your first game after all.\nAll this reflexion got me tired though,\nI'm going to relax and leave you with Carl,\nhe's strong so you'll learn a lot !",
));
} else {
commands.entity(game.opponent()).insert(Say::new(
"happy",
"Uh, it's a draw then ! Not bad !\nAll this reflexion got me tired though,\nI'm going to relax and leave you with Carl,\nhe's strong so you'll learn a lot !",
));
}
game.opponent = 1;
game.status = GameStatus::Preparing;
} else {
// end the carl game
if game.status == GameStatus::Win {
commands.entity(game.opponent()).insert(Say::new(
"exhausted",
"I - I actually lost...\n\
I'm starting to realise now .\n\
Even since I started using it,\n\
I stopped improving...\n\
Was this ability my undoing ? . . . . .",
));
game.status = GameStatus::Ending;
} else if game.status == GameStatus::Loss {
commands.entity(game.opponent()).insert(Say::new(
"smug",
"Chockmate. I won as expected.\nStay if you want to play me again !",
));
game.status = GameStatus::Preparing;
} else {
commands.entity(game.opponent()).insert(Say::new(
"neutral",
"Eh, I let you draw on purpose.\nStay if you want to play me again !",
));
game.status = GameStatus::Preparing;
}
}
}
}
#[derive(Component)]
struct Title;
fn display_end(
mut commands: Commands,
mut piece_ents: ResMut<HashMap<Pos, Entity>>,
mut game: ResMut<Game>,
query_title: Query<Entity, With<Title>>,
server: Res<AssetServer>,
keys: Res<Input<KeyCode>>,
query_say: Query<(), With<Say>>,
mut query_text: Query<&mut Text, With<DialogueText>>,
mut query_face: Query<&mut Handle<Image>, With<DialogueFace>>,
audio: Res<Audio>,
) {
if game.status == GameStatus::Ending && query_say.is_empty() {
if let Ok(entity) = query_title.get_single() {
if keys.just_pressed(KeyCode::R) {
// R was pressed
commands.entity(entity).despawn();
game.opponent = 0;
game.status = GameStatus::Preparing;
}
} else {
// clean the pieces
clean_up_pieces(&mut commands, &mut piece_ents);
if let Ok(mut text) = query_text.get_single_mut() {
text.sections[0].value = "".to_string();
}
if let Ok(mut face) = query_face.get_single_mut() {
*face = server.load("empty.png");
}
// display the title
audio.play(server.load("sounds/take.ogg"));
commands
.spawn_bundle(SpriteBundle {
sprite: Sprite {
custom_size: Some(Vec2::new(570., 100.)),
..Default::default()
},
texture: server.load("title.png"),
..Default::default()
})
.insert(Title);
}
}
}
pub struct SelectedSquare(Option<Pos>);
pub struct HoveredSquare(Option<Pos>);
pub struct Undoing;
impl Plugin for Undoing {
fn build(&self, app: &mut App) {
app.insert_resource(ChossGame::new(PieceColor::White))
.add_plugin(CharacterPlugin)
.insert_resource(Game::new())
.insert_resource(HashMap::<Pos, Entity>::new())
.insert_resource(SelectedSquare(None))
.insert_resource(HoveredSquare(None))
.add_startup_system(create_opponents)
.add_startup_system(draw_choss)
.add_system(play_move.label("play"))
.add_system(mouse_button_input)
.add_system(display_moves)
.add_system(move_to)
.add_system(die)
.add_system(promote)
.add_system(start_ai_turn.after("play"))
// ensure dialogue gets instanciated before the next play_move call
.add_system(start_game.label("start"))
.add_system(end_game.after("start"))
.add_system(place_pieces)
.add_system(undo)
.add_system(display_end.before("start"));
}
}
| 36.05034 | 213 | 0.494962 |
61a809a4ab7e484c76cd690d07ad72138c09cb66 | 163 | // functions1.rs
// Make me compile! Execute `rustlings hint functions1` for hints :)
fn call_me() {
println!("I'm called!");
}
fn main() {
call_me();
}
| 14.818182 | 68 | 0.613497 |
644b2f8303a07cce08b991d5a6d7b191c8cadb93 | 5,587 | #[doc = "Register `RXD` reader"]
pub struct R(crate::R<RXD_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<RXD_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<RXD_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<RXD_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `RXD` writer"]
pub struct W(crate::W<RXD_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<RXD_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<RXD_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<RXD_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `PIN` reader - Pin number"]
pub struct PIN_R(crate::FieldReader<u8, u8>);
impl PIN_R {
pub(crate) fn new(bits: u8) -> Self {
PIN_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for PIN_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `PIN` writer - Pin number"]
pub struct PIN_W<'a> {
w: &'a mut W,
}
impl<'a> PIN_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f);
self.w
}
}
#[doc = "Connection\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CONNECT_A {
#[doc = "1: Disconnect"]
DISCONNECTED = 1,
#[doc = "0: Connect"]
CONNECTED = 0,
}
impl From<CONNECT_A> for bool {
#[inline(always)]
fn from(variant: CONNECT_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `CONNECT` reader - Connection"]
pub struct CONNECT_R(crate::FieldReader<bool, CONNECT_A>);
impl CONNECT_R {
pub(crate) fn new(bits: bool) -> Self {
CONNECT_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CONNECT_A {
match self.bits {
true => CONNECT_A::DISCONNECTED,
false => CONNECT_A::CONNECTED,
}
}
#[doc = "Checks if the value of the field is `DISCONNECTED`"]
#[inline(always)]
pub fn is_disconnected(&self) -> bool {
**self == CONNECT_A::DISCONNECTED
}
#[doc = "Checks if the value of the field is `CONNECTED`"]
#[inline(always)]
pub fn is_connected(&self) -> bool {
**self == CONNECT_A::CONNECTED
}
}
impl core::ops::Deref for CONNECT_R {
type Target = crate::FieldReader<bool, CONNECT_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CONNECT` writer - Connection"]
pub struct CONNECT_W<'a> {
w: &'a mut W,
}
impl<'a> CONNECT_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CONNECT_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Disconnect"]
#[inline(always)]
pub fn disconnected(self) -> &'a mut W {
self.variant(CONNECT_A::DISCONNECTED)
}
#[doc = "Connect"]
#[inline(always)]
pub fn connected(self) -> &'a mut W {
self.variant(CONNECT_A::CONNECTED)
}
#[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 << 31)) | ((value as u32 & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bits 0:4 - Pin number"]
#[inline(always)]
pub fn pin(&self) -> PIN_R {
PIN_R::new((self.bits & 0x1f) as u8)
}
#[doc = "Bit 31 - Connection"]
#[inline(always)]
pub fn connect(&self) -> CONNECT_R {
CONNECT_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:4 - Pin number"]
#[inline(always)]
pub fn pin(&mut self) -> PIN_W {
PIN_W { w: self }
}
#[doc = "Bit 31 - Connection"]
#[inline(always)]
pub fn connect(&mut self) -> CONNECT_W {
CONNECT_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Pin select for RXD\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rxd](index.html) module"]
pub struct RXD_SPEC;
impl crate::RegisterSpec for RXD_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [rxd::R](R) reader structure"]
impl crate::Readable for RXD_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [rxd::W](W) writer structure"]
impl crate::Writable for RXD_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets RXD to value 0xffff_ffff"]
impl crate::Resettable for RXD_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0xffff_ffff
}
}
| 28.505102 | 402 | 0.573116 |
bb931b2f871233970e745fdaedcee015b1882300 | 2,419 | #[macro_use]
extern crate derive_new;
extern crate lazy_static;
extern crate libc;
extern crate log;
#[macro_use]
extern crate objekt;
extern crate num_traits;
#[cfg(test)]
extern crate proptest;
pub mod align;
pub mod f16;
#[macro_use]
pub mod frame;
mod generic;
#[cfg(target_arch = "x86_64")]
pub mod x86_64_fma;
#[cfg(target_arch = "aarch64")]
pub mod arm64;
#[cfg(any(target_arch = "arm", target_arch = "armv7"))]
pub mod arm32;
pub use self::frame::mmm;
pub use self::frame::sigmoid;
pub use self::frame::tanh;
pub use self::frame::vecmatmul;
pub struct Ops {
pub svmm: Box<dyn Fn(usize, usize) -> Box<dyn vecmatmul::VecMatMul<f32>> + Send + Sync>,
pub smmm: Box<dyn Fn(usize, usize, usize) -> Box<dyn mmm::MatMatMul<f32>> + Send + Sync>,
pub ssigmoid: Box<dyn Fn() -> Box<dyn sigmoid::Sigmoid<f32>> + Send + Sync>,
pub stanh: Box<dyn Fn() -> Box<dyn tanh::Tanh<f32>> + Send + Sync>,
}
pub fn generic() -> Ops {
Ops {
svmm: Box::new(|k, n| {
Box::new(vecmatmul::PackedVecMatMul::<generic::SVecMatMul8, f32>::new(k, n))
}),
smmm: Box::new(|m, k, n| {
Box::new(mmm::MatMatMulImpl::<generic::SMmm4x4, f32>::new(m, k, n))
}),
ssigmoid: Box::new(|| Box::new(sigmoid::SigmoidImpl::<generic::SSigmoid4, f32>::new())),
stanh: Box::new(|| Box::new(tanh::TanhImpl::<generic::STanh4, f32>::new())),
}
}
#[allow(unreachable_code, unused_mut)]
pub fn best() -> Ops {
let mut ops = generic();
#[cfg(target_arch = "x86_64")]
{
if is_x86_feature_detected!("fma") {
ops.smmm = Box::new(|m, k, n| {
Box::new(mmm::MatMatMulImpl::<x86_64_fma::mmm::SMatMatMul16x6, f32>::new(m, k, n))
});
log::info!("x86_64/fma activated");
}
}
#[cfg(any(target_arch = "arm", target_arch = "armv7"))]
arm32::plug(&mut ops);
#[cfg(target_arch = "aarch64")]
arm64::plug(&mut ops);
return ops;
}
lazy_static::lazy_static! {
static ref OPS: Ops = {
best()
};
}
pub fn ops() -> &'static Ops {
&*OPS
}
#[cfg(test)]
pub(crate) fn check_close(
found: &[f32],
expected: &[f32],
) -> proptest::test_runner::TestCaseResult {
proptest::prop_assert!(
found.iter().zip(expected.iter()).all(|(a, b)| (a - b).abs() < 0.001),
"found: {:?} expected: {:?}",
found,
expected
);
Ok(())
}
| 25.734043 | 98 | 0.580405 |
e545ddf2eaeb665cb169c12ce5b8c1b1f98c9fe3 | 4,826 | use thoth_api::account::model::AccountDetails;
use yew::html;
use yew::prelude::*;
use yew::virtual_dom::VNode;
use yew_router::prelude::*;
use crate::route::AdminRoute;
use crate::route::AppRoute;
use crate::THOTH_API;
pub struct NavbarComponent {
props: Props,
link: ComponentLink<Self>,
}
pub enum Msg {
Logout,
}
#[derive(Properties, Clone)]
pub struct Props {
pub current_user: Option<AccountDetails>,
pub callback: Callback<()>,
}
impl Component for NavbarComponent {
type Message = Msg;
type Properties = Props;
fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
NavbarComponent { props, link }
}
fn change(&mut self, props: Self::Properties) -> ShouldRender {
self.props = props;
true
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::Logout => {
self.props.callback.emit(());
true
}
}
}
fn view(&self) -> VNode {
let logout = self.link.callback(|e: MouseEvent| {
e.prevent_default();
Msg::Logout
});
html! {
<nav class="navbar is-warning" role="navigation" aria-label="main navigation">
<div class="navbar-brand">
<a class="navbar-item" href="/">
<img src="/img/thoth-logo.png" width="50" height="58" style="max-height: none" />
</a>
<a role="button" class="navbar-burger burger" aria-label="menu" aria-expanded="false" data-target="thothNavbar">
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
</a>
</div>
<div id="thothNavbar" class="navbar-menu">
<div class="navbar-start">
<RouterAnchor<AppRoute>
classes="navbar-item"
route=AppRoute::Home
>
{"Catalogue"}
</ RouterAnchor<AppRoute>>
<div class="navbar-item has-dropdown is-hoverable">
<a class="navbar-link">
{ "Docs" }
</a>
<div class="navbar-dropdown">
<a class="navbar-item" href="https://github.com/thoth-pub/thoth" title="Project">
{ "Project" }
</a>
<a class="navbar-item" href="https://github.com/thoth-pub/thoth/projects" title="Timeline">
{ "Timeline" }
</a>
<hr class="navbar-divider" />
<a class="navbar-item" href={format!("{}/graphiql", THOTH_API)} title="GraphiQL">
{ "GraphiQL" }
</a>
</div>
</div>
<RouterAnchor<AppRoute>
classes="navbar-item"
route=AppRoute::Admin(AdminRoute::Dashboard)
>
{"Admin"}
</ RouterAnchor<AppRoute>>
</div>
</div>
<div class="navbar-end">
<div class="navbar-item">
<div class="buttons">
<a class="button is-danger" href="https://github.com/thoth-pub/thoth/blob/master/CHANGELOG.md">
{"v"}{ env!("CARGO_PKG_VERSION") }
</a>
{
if self.props.current_user.is_some() {
html! {
<button class="button is-light" onclick=logout>
{ "Logout" }
</button>
}
} else {
html! {
<RouterAnchor<AppRoute> classes="button is-light" route=AppRoute::Login>
{"Login"}
</ RouterAnchor<AppRoute>>
}
}
}
</div>
</div>
</div>
</nav>
}
}
}
| 36.560606 | 132 | 0.3908 |
1cfffc74be45fd6db9d9334ae0f0b74bf2eb8fbe | 33,270 | use pyo3::prelude::*;
use rand::Rng;
use rustfst::algorithms::determinize::{
determinize_with_config, DeterminizeConfig, DeterminizeType,
};
use rustfst::algorithms::tr_sort as rs_tr_sort;
use rustfst::algorithms::{
closure, compose, concat, invert, project, rm_epsilon, union, ProjectType,
};
use rustfst::algorithms::{minimize_with_config, MinimizeConfig};
use rustfst::fst_impls::VectorFst;
use rustfst::fst_properties::FstProperties;
use rustfst::fst_traits::{CoreFst, ExpandedFst, SerializableFst};
use rustfst::prelude::*;
use rustfst::semirings::TropicalWeight;
use rustfst::utils::{acceptor, transducer};
use rustfst::KSHORTESTDELTA;
use std::collections::HashSet;
use std::iter::FromIterator;
use std::path::Path;
use std::sync::Arc;
pub mod att_parse;
#[derive(Debug, Clone, Copy)]
enum LabelColor {
White,
Gray,
Black,
}
#[derive(Debug, Clone, Copy)]
enum Action {
Enter,
Exit,
}
/// Wraps a [`rustfst`] SymbolTable struct as a Python class.
///
/// # Example
/// ## Rust
/// ```
/// let symt = SymTab::new(vec!["a", "b", "c"]);
/// assert_eq!(symt.get_symbol(1), "a");
/// ```
/// ## Python
/// ```{.python}
/// symt = SymTab(["a", "b", "c"])
/// assert(symt.get_symbol(1) == "a")
/// ```
#[pyclass]
pub struct SymTab {
/// A SymbolTable struct from [`rustfst`]
symt: SymbolTable,
}
#[pymethods]
impl SymTab {
/// Constructs a new [`SymTab`] instance
///
/// # Example
///
/// ```
/// let symt = SymTab::new(vec!["a", "b", "c"]);
/// ```
#[new]
pub fn new(sigma: Vec<String>) -> Self {
let mut symt = SymbolTable::new();
for s in sigma {
symt.add_symbol(s);
}
SymTab { symt }
}
/// Adds a symbol to a [`SymTab`] with an associated label
///
/// # Example
///
/// ```
/// let symt = SymTab::new(vec!["a", "b"]);
/// symt.add_symbol("c");
/// assert_eq!(symt.get_symbol(3)?, "c");
/// ```
pub fn add_symbol(&mut self, s: &str) -> PyResult<()> {
self.symt.add_symbol(s);
Ok(())
}
/// Given a symbol, returns the corresponding label
///
/// # Example
///
/// ```
/// let symt = SymTab::new(vec!["a", "b", "c"]);
/// assert_eq!(symt.get_label("b")?, 2);
/// ```
pub fn get_label(&self, s: &str) -> Option<Label> {
self.symt.get_label(s)
}
/// Given a label, returns the corresponding symbol
///
/// # Example
///
/// ```
/// let symt = SymTab::new(vec!["a", "b", "c"]);
/// assert_eq!(symt.get_symbol(3), "c");
/// ```
pub fn get_symbol(&self, l: Label) -> Option<&str> {
self.symt.get_symbol(l)
}
}
/// Wraps the [`VectorFst`] struct from [`rustfst`]. Assumes weights are in the tropical semiring.
///
/// # Examples
///
/// ## Rust
/// ```
/// use wfst4str::WeightedFst;
///
/// let t = WeightedFst::new();
/// let sym = vec!["a", "b", "c"];
/// t.set_input_symbols(sym);
/// t.set_output_symbols(sym);
/// let q0 = t.add_state();
/// let q1 = t.add_state();
/// t.set_start(q0).unwrap();
/// t.set_final(q1, 0.0).unwrap();
/// t.add_tr(0, 1, "a", "b").unwrap();
/// ```
/// ## Python
///
/// ```python
/// import wfst4str
///
/// t = wfst4str.WeightedFst();
/// sym = ['a', 'b', 'c']
/// t.set_input_symbols(sym)
/// t.set_output_symbols(sym)
/// q0 = t.add_state()
/// q1 = t.add_state()
/// t.set_start(q0)
/// q1.set_final(q1, 0.0)
/// t.add_tr(0, 1, 'a', 'b')
/// ```
///
#[pyclass]
pub struct WeightedFst {
fst: VectorFst<TropicalWeight>,
}
impl Default for WeightedFst {
fn default() -> Self {
WeightedFst::new()
}
}
#[pymethods]
impl WeightedFst {
/// Constructs a [`WeightedFst`] object.
///
/// # Examples
///
/// ## Python
///
/// ```python
/// import wfst4str
/// t = wfst4str.WeightedFst()
/// sym = ['a', 'b', 'c']
/// t.set_input_symbols(sym)
/// t.set_output_symbols(sym)
/// q0 = t.add_state()
/// q1 = t.add_state()
/// t.set_start(q0)
/// q1.set_final(q1, 0.0)
/// t.add_tr(0, 1, 'a', 'b')
/// assert (t.apply('a') == 'b')
/// ```
// Constructing wFSTs
#[new]
pub fn new() -> Self {
WeightedFst {
fst: VectorFst::new(),
}
}
/// Creates a symbol table from a vector of strings and associates it with the wFST (as the input symbol table),.
///
/// # Example
///
/// ## Python
///
/// ```python
/// import wfst4str
/// t = wfst4str.WeightedFst()
/// t.set_input_symbols(['a', 'b', 'c'])
/// ```
pub fn set_input_symbols(&mut self, sym_vec: Vec<String>) {
let symt = SymTab::new(sym_vec);
self.fst.set_input_symbols(Arc::new(symt.symt))
}
/// Creates a symbol table from a vector of strings and associates it with the wFST ().
///
/// # Example
///
/// ## Python
///
/// ```python
/// import wfst4str
/// t = wfst4str.WeightedFst()
/// t.set_output_symbols(['a', 'b', 'c'])
/// ```
pub fn set_output_symbols(&mut self, sym_vec: Vec<String>) {
let symt = SymTab::new(sym_vec);
self.fst.set_output_symbols(Arc::new(symt.symt))
}
/// Returns the input symbols of the wFST as a list
///
/// # Example
///
/// ## Python
///
/// ```python
/// t = wfst4str.WeightedFst()
/// t.set_input_symbols(['a', 'b', 'c'])
/// assert t.get_input_symbols() = ['a', 'b', 'c']
/// ```
pub fn get_input_symbols(&self) -> PyResult<Vec<String>> {
Ok(self
.fst
.input_symbols()
.unwrap_or(&Arc::new(SymbolTable::new()))
.iter()
.map(|(_, s)| s.to_string())
.collect())
}
/// Returns the output symbols of the wFST as a list
///
/// # Python
///
/// ```python
/// t = wfst4str.WeightedFst()
/// t.set_output_symbols(['a', 'b', 'c'])
/// assert t.get_output_symbols() = ['a', 'b', 'c']
/// ```
pub fn get_output_symbols(&self) -> PyResult<Vec<String>> {
Ok(self
.fst
.output_symbols()
.unwrap_or(&Arc::new(SymbolTable::new()))
.iter()
.map(|(_, s)| s.to_string())
.collect())
}
/// Adds `n` states to the wFST.
///
/// # Examples
///
/// ## Python
///
/// ```python
/// t = wfst4str.WeightedFst()
/// # Add 5 states to t
/// t.add_states(5)
/// ```
pub fn add_states(&mut self, n: usize) {
self.fst.add_states(n)
}
/// Adds one new state and returns the corresponding ID (an integer).
///
/// # Examples
///
/// ## Python
///
/// ```python
/// t = wfst4str.WeightedFst()
/// # Add 1 states to t
/// q0 = t.add_state()
/// assert q0 == 0
/// ```
pub fn add_state(&mut self) -> StateId {
self.fst.add_state()
}
/// Sets `state` as a start state (initial state).
///
/// # Examples
///
/// ## Python
///
/// ```python
/// t = wfst4str.WeightedFst()
/// q0 = t.add_state()
/// t.set_start(q0)
/// ```
pub fn set_start(&mut self, state: StateId) -> PyResult<()> {
self.fst
.set_start(state)
.unwrap_or_else(|e| panic!("Cannot set {:?} as start state: {}", state, e));
Ok(())
}
/// Sets `state` as a final state (accepting state).
///
/// # Examples
///
/// ## Python
///
/// ```python
/// t = wfst4str.WeightedFst()
/// q0 = t.add_state()
/// t.set_final(q0)
/// ```
pub fn set_final(&mut self, state: StateId, weight: f32) -> PyResult<()> {
self.fst
.set_final(state, weight)
.unwrap_or_else(|e| panic!("Cannot set {:?} as final state: {}", state, e));
Ok(())
}
/// Returns the number of states in the wFST.
///
/// # Examples
///
/// ## Python
///
/// ```python
/// t = wfst4str.WeightedFst()
/// t.add_state()
/// assert t.num_states == 1
/// ```
pub fn num_states(&self) -> StateId {
self.fst.num_states()
}
/// Adds a transition to the wFST from `source_state` to `next_state` with
/// input symbol `isym`, output symbol `osym`, and weight `weight`
///
/// # Examples
///
/// ## Python
///
/// ```python
/// t = wfst4str.WeightedFst()
/// q0 = t.add_state()
/// q1 = t.add_state()
/// t.set_output_symbols(['a', 'b', 'c'])
/// t.set_input_symbols(['a', 'b', 'c'])
/// t.add_tr(q0, q1, 'a', 'b', 1.0)
/// ```
pub fn add_tr(
&mut self,
source_state: StateId,
next_state: StateId,
isym: &str,
osym: &str,
weight: f32,
) -> PyResult<()> {
let empty_symt = Arc::new(SymbolTable::new());
let ilabel = &self
.fst
.input_symbols()
.unwrap_or(&empty_symt)
.get_label(isym)
.unwrap_or(0);
let olabel = &self
.fst
.output_symbols()
.unwrap_or(&empty_symt)
.get_label(osym)
.unwrap_or(0);
let tr = Tr::<TropicalWeight>::new(*ilabel, *olabel, weight, next_state);
self.fst.add_tr(source_state, tr).unwrap_or_else(|e| {
println!(
"Cannot add Tr from {:?} to {:?}: {}",
source_state, next_state, e
)
});
Ok(())
}
// Convenience methods
/// Takes an string and returns a corresponding linear wFST (an acceptor,
/// since the input labels are the same as the output labels and it,
/// therefore, is functionally a wFSA).
pub fn to_linear_acceptor(&self, s: &str) -> PyResult<WeightedFst> {
let labs = self.isyms_to_labs(s);
let fst: VectorFst<TropicalWeight> = acceptor(&labs, TropicalWeight::one());
Ok(WeightedFst { fst })
}
/// Returns a wFST that transduces between `s1` and `s2`.
pub fn to_linear_transducer(&self, s1: &str, s2: &str) -> PyResult<WeightedFst> {
let labs1 = self.isyms_to_labs(s1);
let labs2 = self.isyms_to_labs(s2);
let max_len = labs1.len().max(labs2.len());
let labs1: Vec<Label> = labs1
.into_iter()
.chain(std::iter::repeat(0))
.take(max_len)
.collect();
let labs2: Vec<Label> = labs2
.into_iter()
.chain(std::iter::repeat(0))
.take(max_len)
.collect();
let fst: VectorFst<TropicalWeight> =
transducer(&labs1[..], &labs2[..], TropicalWeight::one());
Ok(WeightedFst { fst })
}
// Application
/// Applies the wFST to a string (consisting of symbols in the wFSTs `SymbolTable`s).
pub fn apply(&mut self, s: &str) -> PyResult<HashSet<String>> {
let mut lfst = self
.to_linear_acceptor(s)
.unwrap_or_else(|e| panic!("Cannot linearize \"{}\": {}", s, e));
let mut fst2 = lfst.compose(self).expect("Cannot compose wFSTs.");
fst2.fst.set_symts_from_fst(&self.fst);
match fst2.num_states() {
0 => Ok(HashSet::new()),
_ => fst2.paths_as_strings(),
}
}
/// Returns a set of strings corresponding the shortest paths (paths having
/// the smallest weight) through the string when composed with the FST.
pub fn strings_for_shortest_paths(&mut self, s: &str) -> PyResult<HashSet<String>> {
let mut fst = self
.to_linear_acceptor(s)
.unwrap_or_else(|e| panic!("Cannot linearize \"{}\": {}", s, e));
let mut fst2 = fst.compose(self).expect("Cannot compose wFSTs.");
fst2.fst.set_symts_from_fst(&self.fst);
match fst2.num_states() {
0 => Ok(HashSet::new()),
_ => fst2.shortest_path(),
}
}
/// Returns strings based upon the output symbols of each path
pub fn paths_as_strings(&self) -> PyResult<HashSet<String>> {
if self.is_cyclic().unwrap() {
panic!("wFST is cyclic. The set of all paths through it is infinite. Check your wFST for logic errors.`")
}
Ok(HashSet::from_iter(self.fst.paths_iter().map(|p| {
p.olabels
.iter()
.map(|&l| {
self.fst
.output_symbols()
.unwrap_or_else(|| panic!("Cannot access output SymbolTable."))
.get_symbol(l)
.unwrap_or("")
.to_string()
})
.collect::<Vec<String>>()
.join("")
})))
}
/// Returns a list of (string, weight) pairs corresponding to the possible
/// paths obtained by composing an FSA accepting only `s` with the wFST.
/// Pairs are ordered by weight.
pub fn outputs_by_weight(&mut self, s: &str) -> PyResult<Vec<(String, f32)>> {
let mut lfst = self
.to_linear_acceptor(s)
.unwrap_or_else(|e| panic!("Cannot linearize \"{}\": {}", s, e));
let mut fst2 = lfst.compose(self).expect("Cannot compose wFSTs.");
fst2.fst.set_symts_from_fst(&self.fst);
let mut outputs: Vec<(String, f32)> = fst2
.fst
.paths_iter()
.map(|p| {
(
p.olabels
.iter()
.map(|&l| {
self.fst
.output_symbols()
.unwrap_or_else(|| panic!("Cannot access ouput SymbolTable."))
.get_symbol(l)
.unwrap_or("")
.to_string()
})
.collect::<Vec<String>>()
.join(""),
*p.weight.value(),
)
})
.collect();
outputs.sort_unstable_by(|(_s1, w1), (_s2, w2)| w1.partial_cmp(w2).unwrap());
Ok(outputs)
}
/// Returns the string corresponding to the path through the s ∘ wFST with the
/// least weight. This, rather than `strings_for_shortest_paths`, is to be
/// used in evaluation.
pub fn best_output(&mut self, s: &str) -> PyResult<String> {
let outputs: Vec<(String, f32)> = self.outputs_by_weight(s).unwrap();
if !outputs.is_empty() {
let (s, _) = &outputs[0];
Ok(s.to_string())
} else {
Ok("".to_string())
}
}
/// Returns the shortest path through the wFST. Deprecated in favor of
/// `best_output`, which proces more understandable results.
pub fn shortest_path(&self) -> PyResult<HashSet<String>> {
let mut shortest = WeightedFst {
fst: shortest_path(&self.fst)
.unwrap_or_else(|e| panic!("Cannot convert wFST to shortest path: {}", e)),
};
shortest.fst.set_input_symbols(
self.fst
.input_symbols()
.unwrap_or(&Arc::new(SymbolTable::new()))
.clone(),
);
shortest.fst.set_output_symbols(
self.fst
.output_symbols()
.unwrap_or(&Arc::new(SymbolTable::new()))
.clone(),
);
shortest.fst.set_symts_from_fst(&self.fst);
shortest.paths_as_strings()
}
// Linearizing and delinearizing wFSTs
/// Serializes the wFST to a text file at `path` in AT&T format (OpenFST compatible).
pub fn write_text(&self, path: &str) -> PyResult<()> {
let path_output = Path::new(path);
self.fst
.write_text(path_output)
.unwrap_or_else(|e| panic!("Could not write to {}: {}", path, e));
Ok(())
}
/// Returns a serialization of the wFST as a string in AT&T format (OpenFST compatible).
pub fn text(&self) -> String {
match self.fst.text() {
Ok(s) => s,
Err(e) => panic!("Cannot produce text representation: {}", e),
}
}
/// Outputs a representation of the wFST as a `dot` file to `path`, which
/// can be visualized with Graphviz.
pub fn draw(&self, path: &str) -> PyResult<()> {
let config = DrawingConfig::default();
let path_output = Path::new(path);
self.fst
.draw(path_output, &config)
.unwrap_or_else(|e| panic!("Cannot write to path {}: {}", path, e));
Ok(())
}
/// Populates a [`WeightedFst`] based on an AT&T description. Before this
/// method is called, the wFST must have an input and output symbol table.
pub fn populate_from_att(&mut self, text: &str) -> PyResult<()> {
if let Ok((_, exprs)) = att_parse::att_file(text) {
for expr in exprs {
match expr {
att_parse::AttExpr::AttTr(tr_expr) => {
let isymt = self
.fst
.input_symbols()
.unwrap_or_else(|| panic!("No input symbol table!"));
let osymt = self
.fst
.output_symbols()
.unwrap_or_else(|| panic!("No output symbol table!"));
let ilabel = isymt
.get_label(tr_expr.isymbol.clone())
.unwrap_or_else(|| panic!("Unkown symbol {:?}", tr_expr.isymbol));
let olabel = osymt
.get_label(tr_expr.osymbol.clone())
.unwrap_or_else(|| panic!("Unkown symbol {:?}", tr_expr.osymbol));
let tr = Tr::<TropicalWeight>::new(
ilabel,
olabel,
tr_expr.weight,
tr_expr.nextstate,
);
while !(self.fst.states_iter().any(|x| x == tr_expr.sourcestate)
&& self.fst.states_iter().any(|x| x == tr_expr.nextstate))
{
self.fst.add_state();
}
self.fst
.add_tr(tr_expr.sourcestate, tr)
.unwrap_or_else(|e| {
println!(
"Could not create transition from {:?} to {:?}: {:?}.",
tr_expr.sourcestate, tr_expr.nextstate, e
);
});
}
att_parse::AttExpr::AttFinal(fs_expr) => {
while !(self.fst.states_iter().any(|x| x == fs_expr.state)) {
self.fst.add_state();
}
self.fst
.set_final(fs_expr.state, fs_expr.finalweight)
.unwrap_or_else(|e| {
println!("No such state: {:?} {:?}", fs_expr.state, e)
});
}
att_parse::AttExpr::AttNone => (),
}
// println!("self.fst: {:?}", self.fst);
}
}
Ok(())
}
// Algorithms
/// Kleene closure of a wFST via mutation
pub fn closure_in_place_star(&mut self) {
closure::closure(&mut self.fst, closure::ClosureType::ClosureStar)
}
/// Kleene plus closure of a wFST via mutation
pub fn closure_in_place_plus(&mut self) {
closure::closure(&mut self.fst, closure::ClosureType::ClosurePlus)
}
/// Returns the Kleene closure of a wFST
pub fn closure_star(&self) -> PyResult<WeightedFst> {
let mut fst = self.fst.clone();
closure::closure(&mut fst, closure::ClosureType::ClosureStar);
Ok(WeightedFst { fst })
}
/// Returns the Kleene plus closure of a wFST
pub fn closure_plus(&self) -> PyResult<WeightedFst> {
let mut fst = self.fst.clone();
closure::closure(&mut fst, closure::ClosureType::ClosurePlus);
Ok(WeightedFst { fst })
}
/// Returns the composition of the wFST and another wFST (`other`)
pub fn compose(&mut self, other: &mut WeightedFst) -> PyResult<WeightedFst> {
self.tr_olabel_sort();
other.tr_ilabel_sort();
Ok(WeightedFst {
fst: compose::compose(self.fst.clone(), other.fst.clone()).expect("Couldn't compose!"),
})
}
/// Returns the concatentaion of the wFST and another wFST (`other`)
pub fn concat(&self, other: &WeightedFst) -> PyResult<WeightedFst> {
let mut fst = self.fst.clone();
concat::concat(&mut fst, &other.fst).expect("Cannot concatenate wFSTs!");
Ok(WeightedFst { fst })
}
/// Returns a determinized wFST weakly equivalent to `self`.
pub fn determinize(&self) -> PyResult<WeightedFst> {
let mut fst: VectorFst<TropicalWeight> = determinize_with_config(
&self.fst,
DeterminizeConfig::new(KSHORTESTDELTA, DeterminizeType::DeterminizeDisambiguate),
)
.expect("Could not determinize wFST");
fst.set_properties(
fst.properties() | FstProperties::I_DETERMINISTIC | FstProperties::O_DETERMINISTIC,
);
Ok(WeightedFst { fst })
}
/// Concatenates a wFST (`other`) to the wFST in place.
pub fn concat_in_place(&mut self, other: &WeightedFst) {
concat::concat(&mut self.fst, &other.fst).expect("Cannot concatenate wFST!")
}
/// Returns the inversion of a wFST.
pub fn invert(&self) -> PyResult<WeightedFst> {
let mut fst = self.fst.clone();
invert(&mut fst);
Ok(WeightedFst { fst })
}
/// Inverts a wFST in place.
pub fn invert_in_place(&mut self) {
invert(&mut self.fst)
}
/// Returns a minimized wFST. Minimizes any deterministic wFST. Also
/// minimizes non-deterministic wFSTs if they use an idempotent semiring.
pub fn minimize(&self) -> PyResult<WeightedFst> {
let mut fst = self.fst.clone();
minimize_with_config(&mut fst, MinimizeConfig::new(KSHORTESTDELTA, true))
.expect("Cannot minimize wFST!");
Ok(WeightedFst { fst })
}
/// Minimizes a deterministic wFST in place. Also minizes non-deterministic
/// wFSTs if they use an idempotent semiring.
pub fn minimize_in_place(&mut self) -> PyResult<()> {
minimize_with_config(&mut self.fst, MinimizeConfig::new(KSHORTESTDELTA, true))
.expect("Cannot minimize wFST!");
Ok(())
}
/// Project the input labels of a wFST, replacing the output labels with them.
pub fn project_input(&self) -> PyResult<WeightedFst> {
let mut fst = self.fst.clone();
project(&mut fst, ProjectType::ProjectInput);
Ok(WeightedFst { fst })
}
/// Project the input labels of a wFST, replacing the output labels with them.
pub fn project_output(&self) -> PyResult<WeightedFst> {
let mut fst = self.fst.clone();
project(&mut fst, ProjectType::ProjectOutput);
Ok(WeightedFst { fst })
}
/// In-place input projection of the wFST.
pub fn project_in_place_input(&mut self) {
project(&mut self.fst, ProjectType::ProjectInput);
}
/// In-place output projection of the wFST.
pub fn project_in_place_output(&mut self) {
project(&mut self.fst, ProjectType::ProjectOutput);
}
/// Returns the union of the wFST and another (`other`).
pub fn union(&self, other: &WeightedFst) -> PyResult<WeightedFst> {
let mut fst = self.fst.clone();
union::union(&mut fst, &other.fst).expect("Cannot union wFSTs!");
Ok(WeightedFst { fst })
}
/// In-place union of the wFST and another (`other`).
pub fn union_in_place(&mut self, other: &WeightedFst) {
union::union(&mut self.fst, &other.fst).expect("Cannot union wFSTs!");
}
/// Returns a wFST with epsilon-transitions (transitions with epsilon as
/// both input and output labels) removed.
pub fn rm_epsilon(&mut self) -> PyResult<WeightedFst> {
let mut fst = self.fst.clone();
rm_epsilon::rm_epsilon(&mut fst).expect("Cannot remove epsilons!");
Ok(WeightedFst { fst })
}
/// Removes epsilon transitions in place.
pub fn rm_epsilon_in_place(&mut self) -> PyResult<()> {
rm_epsilon::rm_epsilon(&mut self.fst).expect("Cannot remove epsilons!");
Ok(())
}
/// Sorts the transitions of a wFST based on its input labels.
pub fn tr_ilabel_sort(&mut self) {
let _comp = ILabelCompare {};
rs_tr_sort(&mut self.fst, _comp);
self.fst
.set_properties(self.fst.properties() | FstProperties::I_LABEL_SORTED)
}
/// Sorts the transitions of a wFST based on its output labels.
pub fn tr_olabel_sort(&mut self) {
let _comp = OLabelCompare {};
rs_tr_sort(&mut self.fst, _comp);
self.fst
.set_properties(self.fst.properties() | FstProperties::O_LABEL_SORTED)
// self.fst.set_properties_with_mask(self.fst.properties(), FstProperties::O_LABEL_SORTED)
}
// Handling special symbols
/// Replaces transitions labeled with <oth> with transitions with all unused
/// input labels as input and output labels.
pub fn explode_oth(&mut self, special: HashSet<String>) -> PyResult<()> {
let fst = &mut self.fst; // Make a mutual reference to the inner field of &self to reduce boilerplate
let empty_symt = Arc::new(SymbolTable::new());
let symt = fst.input_symbols().unwrap_or(&empty_symt);
let special = &mut special.clone();
special.insert("<eps>".to_string());
special.insert("<oth>".to_string());
let oth_label = symt
.get_label("<oth>")
.unwrap_or_else(|| panic!("SymbolTable does not include '<oth>'"));
let normal_set: HashSet<Label> = symt
.iter()
.filter(|(_, s)| !special.contains(&s.to_string()))
.map(|(x, _)| x)
.into_iter()
.collect();
for s in fst.states_iter() {
let trs: Vec<Tr<TropicalWeight>> = fst.pop_trs(s).unwrap_or_default().clone();
let outbound: HashSet<Label> = trs.iter().map(|tr| tr.ilabel).collect();
let difference: HashSet<Label> = normal_set.difference(&outbound).copied().collect();
for tr in trs.iter() {
if tr.ilabel == oth_label {
for &lab in &difference {
fst.emplace_tr(s, lab, lab, tr.weight, tr.nextstate)
.unwrap_or_else(|e| panic!("Cannot create Tr: {}", e));
}
} else {
fst.emplace_tr(s, tr.ilabel, tr.olabel, tr.weight, tr.nextstate)
.unwrap_or_else(|e| panic!("Cannot create Tr: {}", e));
}
}
}
Ok(())
}
/// Replace transitions with with input symbol `sym` (e.g., "<v>") with a
/// set of transitions in which the the input symbols consist of the symbols
/// in `syms` (e.g., vec!["a", "e", "i", "o", "u"]).
pub fn sub(&mut self, sym: String, syms: Vec<String>) {
let fst = &mut self.fst;
let empty_symt = Arc::new(SymbolTable::new());
let symt = fst.input_symbols().unwrap_or(&empty_symt);
let lab = symt
.get_label(&sym)
.unwrap_or_else(|| panic!("Symbol table does not include \"{}\"!", sym));
let labs: Vec<Label> = syms
.iter()
.map(|x| {
symt.get_label(&x)
.unwrap_or_else(|| panic!("Symbol table does not include \"{}\"!", x))
})
.collect();
for s in fst.states_iter() {
let trs: Vec<Tr<TropicalWeight>> = fst.pop_trs(s).unwrap_or_default().clone();
for tr in trs {
if tr.ilabel == lab {
for &l in labs.iter() {
fst.emplace_tr(s, l, l, tr.weight, tr.nextstate)
.unwrap_or_else(|e| {
panic!("Cannot emplace Tr from state {}: {}", s, e)
});
}
} else {
fst.add_tr(s, tr)
.unwrap_or_else(|e| panic!("Cannot add Tr from {}: {}", s, e));
}
}
}
}
// Various
/// Returns true if the wFST has a cycle. Otherwise, it returns false.
pub fn is_cyclic_old(&self) -> PyResult<bool> {
let fst2 = self.fst.clone();
let mut stack: Vec<StateId> = Vec::new();
match fst2.start() {
Some(s) => stack.push(s),
_ => panic!("wFST lacks a start state. Aborting."),
}
let mut visited = vec![false; self.fst.num_states()];
while !stack.is_empty() {
let s = stack.pop().unwrap();
for tr in fst2
.get_trs(s)
.unwrap_or_else(|e| panic!("State {} not present in wFST: {}", s, e))
.iter()
{
if visited[tr.nextstate] {
return Ok(true);
} else {
stack.push(tr.nextstate);
visited[s] = true;
}
}
}
Ok(false)
}
/// Returns true if the wFST has a cycle. Otherwise, it returns false.
pub fn is_cyclic(&self) -> PyResult<bool> {
let fst = self.fst.clone();
let mut stack: Vec<(Action, StateId)> = Vec::new();
match fst.start() {
Some(s) => stack.push((Action::Enter, s)),
_ => panic!("wFST lacks a start state. Aborting."),
}
let mut state = vec![LabelColor::White; self.fst.num_states()];
while !stack.is_empty() {
match stack.pop() {
Some((Action::Exit, v)) => state[v] = LabelColor::Black,
Some((Action::Enter, v)) => {
state[v] = LabelColor::Gray;
stack.push((Action::Exit, v));
for tr in fst
.get_trs(v)
.unwrap_or_else(|e| panic!("State {} not present in wFST: {}", v, e))
.iter()
{
let n = tr.nextstate;
match state[n] {
LabelColor::Gray => return Ok(true),
LabelColor::White => stack.push((Action::Enter, n)),
_ => (),
}
}
}
_ => (),
}
}
Ok(false)
}
/// Given a string, returns a list of labels.
fn isyms_to_labs(&self, s: &str) -> Vec<Label> {
let symt = self
.fst
.input_symbols()
.expect("wFST lacks input symbol table.");
s.chars()
.map(|x| {
symt.get_label(x.to_string())
.unwrap_or_else(|| panic!("Input symbol table lacks symbol \"{}\".", x))
})
.collect::<Vec<Label>>()
}
/// Adds a small amount of random noise to the weight of each transition.
pub fn add_noise(&mut self) -> PyResult<()> {
let mut rng = rand::thread_rng();
for s in self.fst.states_iter() {
let trs: Vec<Tr<TropicalWeight>> = self.fst.pop_trs(s).unwrap_or_default().clone();
for tr in trs.iter() {
let noise = TropicalWeight::new(rng.gen::<f32>() * 0.0001);
let new_weight = tr.weight.times(noise).unwrap_or(tr.weight);
self.fst
.emplace_tr(s, tr.ilabel, tr.olabel, new_weight, tr.nextstate)
.unwrap_or_else(|e| panic!("Cannot create Tr: {}", e));
}
}
Ok(())
}
}
/// Returns an wFST corresponding to `fst_string` (deprecated).
#[pyfunction]
pub fn wfst_from_text_string(fst_string: &str) -> PyResult<WeightedFst> {
Ok(WeightedFst {
fst: VectorFst::from_text_string(fst_string)
.unwrap_or_else(|e| panic!("Cannot deserialize wFST: {}", e)),
})
}
/// Returns a wFST corresponding the one represented in the text file `path_text_fst` (deprecated).
#[pyfunction]
pub fn wfst_from_text_file(path_text_fst: &str) -> PyResult<WeightedFst> {
let fst_path = Path::new(path_text_fst);
Ok(WeightedFst {
fst: VectorFst::read_text(fst_path)
.unwrap_or_else(|e| panic!("Cannot read wFST at path {}: {}", path_text_fst, e)),
})
}
#[pymodule]
fn wfst4str(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_class::<SymTab>()?;
m.add_class::<WeightedFst>()?;
m.add_function(wrap_pyfunction!(wfst_from_text_string, m)?)?;
Ok(())
}
| 33.983657 | 117 | 0.516982 |
d9434488dae5393d42f668528c96d7462143e94d | 274 | pub mod api;
pub mod modles;
pub mod schema;
use chrono::{NaiveDateTime, Utc};
use diesel::pg::PgConnection;
pub use modles::PathExtractor;
pub type Repo = gotham_middleware_diesel::Repo<PgConnection>;
fn naivedate_now() -> NaiveDateTime {
Utc::now().naive_utc()
}
| 17.125 | 61 | 0.729927 |
76caf55c254a1906de32a696edf8c04f9dc61700 | 714 | //! Tests auto-converted from "sass-spec/spec/non_conformant/basic/54_adjacent_identifiers_with_hyphens.hrx"
#[test]
fn test() {
assert_eq!(
crate::rsass(
"input {\
\n outline: 5px auto -webkit-focus-ring-color;\
\n foo: random -hello-this-is-dog;\
\n bar: rando -two-or-more -things-that-start -with-hyphens;\
\n baz: foo - bar;\
\n}"
)
.unwrap(),
"input {\
\n outline: 5px auto -webkit-focus-ring-color;\
\n foo: random -hello-this-is-dog;\
\n bar: rando -two-or-more -things-that-start -with-hyphens;\
\n baz: foo-bar;\
\n}\
\n"
);
}
| 29.75 | 108 | 0.512605 |
1a2819b3dd226a05576b32aa46c2455974678625 | 2,734 | // hex encoder and decoder used by rust-protobuf unittests
use std::prelude::v1::*;
use std::char;
use sgx_types::*;
fn decode_hex_digit(digit: char) -> u8 {
match digit {
'0'...'9' => digit as u8 - '0' as u8,
'a'...'f' => digit as u8 - 'a' as u8 + 10,
'A'...'F' => digit as u8 - 'A' as u8 + 10,
_ => panic!(),
}
}
pub fn decode_spid(hex: &str) -> sgx_spid_t {
let mut spid = sgx_spid_t::default();
let hex = hex.trim();
if hex.len() < 16 * 2 {
println!("Input spid file len ({}) is incorrect!", hex.len());
return spid;
}
let decoded_vec = decode_hex(hex);
spid.id.copy_from_slice(&decoded_vec[..16]);
spid
}
pub fn decode_hex(hex: &str) -> Vec<u8> {
let mut r: Vec<u8> = Vec::new();
let mut chars = hex.chars().enumerate();
loop {
let (pos, first) = match chars.next() {
None => break,
Some(elt) => elt,
};
if first == ' ' {
continue;
}
let (_, second) = match chars.next() {
None => panic!("pos = {}d", pos),
Some(elt) => elt,
};
r.push((decode_hex_digit(first) << 4) | decode_hex_digit(second));
}
r
}
#[allow(unused)]
fn encode_hex_digit(digit: u8) -> char {
match char::from_digit(digit as u32, 16) {
Some(c) => c,
_ => panic!(),
}
}
#[allow(unused)]
fn encode_hex_byte(byte: u8) -> [char; 2] {
[encode_hex_digit(byte >> 4), encode_hex_digit(byte & 0x0Fu8)]
}
#[allow(unused)]
pub fn encode_hex(bytes: &[u8]) -> String {
let strs: Vec<String> = bytes
.iter()
.map(|byte| encode_hex_byte(*byte).iter().map(|c| *c).collect())
.collect();
strs.join(" ")
}
#[allow(unused)]
pub fn encode_hex_compact(bytes: &[u8]) -> String {
let strs: Vec<String> = bytes
.iter()
.map(|byte| encode_hex_byte(*byte).iter().map(|c| *c).collect())
.collect();
strs.join("")
}
#[cfg(test)]
mod test {
use super::decode_hex;
use super::encode_hex;
#[test]
fn test_decode_hex() {
assert_eq!(decode_hex(""), [].to_vec());
assert_eq!(decode_hex("00"), [0x00u8].to_vec());
assert_eq!(decode_hex("ff"), [0xffu8].to_vec());
assert_eq!(decode_hex("AB"), [0xabu8].to_vec());
assert_eq!(decode_hex("fa 19"), [0xfau8, 0x19].to_vec());
}
#[test]
fn test_encode_hex() {
assert_eq!("".to_string(), encode_hex(&[]));
assert_eq!("00".to_string(), encode_hex(&[0x00]));
assert_eq!("ab".to_string(), encode_hex(&[0xab]));
assert_eq!(
"01 a2 1a fe".to_string(),
encode_hex(&[0x01, 0xa2, 0x1a, 0xfe])
);
}
}
| 25.082569 | 74 | 0.525238 |
1a08099aa040ca1d05b10c32091a9e4212a9b1c5 | 1,069 | // 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.
// run-pass
#![allow(dead_code)]
trait A { fn a(&self) -> isize; }
trait B: A { fn b(&self) -> isize; }
trait C: A { fn c(&self) -> isize; }
struct S { bogus: () }
impl A for S { fn a(&self) -> isize { 10 } }
impl B for S { fn b(&self) -> isize { 20 } }
impl C for S { fn c(&self) -> isize { 30 } }
// Multiple type params, multiple levels of inheritance
fn f<X:A,Y:B,Z:C>(x: &X, y: &Y, z: &Z) {
assert_eq!(x.a(), 10);
assert_eq!(y.a(), 10);
assert_eq!(y.b(), 20);
assert_eq!(z.a(), 10);
assert_eq!(z.c(), 30);
}
pub fn main() {
let s = &S { bogus: () };
f(s, s, s);
}
| 28.891892 | 68 | 0.611787 |
e44205c2011ffabb1009f7990bdf887790305666 | 39,544 | use crate::{
config, id,
stake_state::{Authorized, Lockup, StakeAccount, StakeAuthorize, StakeState},
};
use log::*;
use num_derive::{FromPrimitive, ToPrimitive};
use serde_derive::{Deserialize, Serialize};
use solana_sdk::{
clock::{Epoch, UnixTimestamp},
decode_error::DecodeError,
feature_set,
instruction::{AccountMeta, Instruction, InstructionError},
keyed_account::{from_keyed_account, get_signers, next_keyed_account, KeyedAccount},
process_instruction::InvokeContext,
program_utils::limited_deserialize,
pubkey::Pubkey,
system_instruction,
sysvar::{self, clock::Clock, rent::Rent, stake_history::StakeHistory},
};
use thiserror::Error;
/// Reasons the stake might have had an error
#[derive(Error, Debug, Clone, PartialEq, FromPrimitive, ToPrimitive)]
pub enum StakeError {
#[error("not enough credits to redeem")]
NoCreditsToRedeem,
#[error("lockup has not yet expired")]
LockupInForce,
#[error("stake already deactivated")]
AlreadyDeactivated,
#[error("one re-delegation permitted per epoch")]
TooSoonToRedelegate,
#[error("split amount is more than is staked")]
InsufficientStake,
#[error("stake account with transient stake cannot be merged")]
MergeTransientStake,
#[error("stake account merge failed due to different authority, lockups or state")]
MergeMismatch,
#[error("custodian address not present")]
CustodianMissing,
#[error("custodian signature not present")]
CustodianSignatureMissing,
}
impl<E> DecodeError<E> for StakeError {
fn type_of() -> &'static str {
"StakeError"
}
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub enum StakeInstruction {
/// Initialize a stake with lockup and authorization information
///
/// # Account references
/// 0. [WRITE] Uninitialized stake account
/// 1. [] Rent sysvar
///
/// Authorized carries pubkeys that must sign staker transactions
/// and withdrawer transactions.
/// Lockup carries information about withdrawal restrictions
Initialize(Authorized, Lockup),
/// Authorize a key to manage stake or withdrawal
///
/// # Account references
/// 0. [WRITE] Stake account to be updated
/// 1. [] Clock sysvar
/// 2. [SIGNER] The stake or withdraw authority
/// 3. Optional: [SIGNER] Lockup authority, if updating StakeAuthorize::Withdrawer before
/// lockup expiration
Authorize(Pubkey, StakeAuthorize),
/// Delegate a stake to a particular vote account
///
/// # Account references
/// 0. [WRITE] Initialized stake account to be delegated
/// 1. [] Vote account to which this stake will be delegated
/// 2. [] Clock sysvar
/// 3. [] Stake history sysvar that carries stake warmup/cooldown history
/// 4. [] Address of config account that carries stake config
/// 5. [SIGNER] Stake authority
///
/// The entire balance of the staking account is staked. DelegateStake
/// can be called multiple times, but re-delegation is delayed
/// by one epoch
DelegateStake,
/// Split u64 tokens and stake off a stake account into another stake account.
///
/// # Account references
/// 0. [WRITE] Stake account to be split; must be in the Initialized or Stake state
/// 1. [WRITE] Uninitialized stake account that will take the split-off amount
/// 2. [SIGNER] Stake authority
Split(u64),
/// Withdraw unstaked lamports from the stake account
///
/// # Account references
/// 0. [WRITE] Stake account from which to withdraw
/// 1. [WRITE] Recipient account
/// 2. [] Clock sysvar
/// 3. [] Stake history sysvar that carries stake warmup/cooldown history
/// 4. [SIGNER] Withdraw authority
/// 5. Optional: [SIGNER] Lockup authority, if before lockup expiration
///
/// The u64 is the portion of the stake account balance to be withdrawn,
/// must be `<= StakeAccount.lamports - staked_lamports`.
Withdraw(u64),
/// Deactivates the stake in the account
///
/// # Account references
/// 0. [WRITE] Delegated stake account
/// 1. [] Clock sysvar
/// 2. [SIGNER] Stake authority
Deactivate,
/// Set stake lockup
///
/// # Account references
/// 0. [WRITE] Initialized stake account
/// 1. [SIGNER] Lockup authority
SetLockup(LockupArgs),
/// Merge two stake accounts.
///
/// Both accounts must have identical lockup and authority keys. A merge
/// is possible between two stakes in the following states with no additional
/// conditions:
///
/// * two deactivated stakes
/// * an inactive stake into an activating stake during its activation epoch
///
/// For the following cases, the voter pubkey and vote credits observed must match:
///
/// * two activated stakes
/// * two activating accounts that share an activation epoch, during the activation epoch
///
/// All other combinations of stake states will fail to merge, including all
/// "transient" states, where a stake is activating or deactivating with a
/// non-zero effective stake.
///
/// # Account references
/// 0. [WRITE] Destination stake account for the merge
/// 1. [WRITE] Source stake account for to merge. This account will be drained
/// 2. [] Clock sysvar
/// 3. [] Stake history sysvar that carries stake warmup/cooldown history
/// 4. [SIGNER] Stake authority
Merge,
/// Authorize a key to manage stake or withdrawal with a derived key
///
/// # Account references
/// 0. [WRITE] Stake account to be updated
/// 1. [SIGNER] Base key of stake or withdraw authority
/// 2. [] Clock sysvar
/// 3. Optional: [SIGNER] Lockup authority, if updating StakeAuthorize::Withdrawer before
/// lockup expiration
AuthorizeWithSeed(AuthorizeWithSeedArgs),
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq, Clone, Copy)]
pub struct LockupArgs {
pub unix_timestamp: Option<UnixTimestamp>,
pub epoch: Option<Epoch>,
pub custodian: Option<Pubkey>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct AuthorizeWithSeedArgs {
pub new_authorized_pubkey: Pubkey,
pub stake_authorize: StakeAuthorize,
pub authority_seed: String,
pub authority_owner: Pubkey,
}
fn initialize(stake_pubkey: &Pubkey, authorized: &Authorized, lockup: &Lockup) -> Instruction {
Instruction::new_with_bincode(
id(),
&StakeInstruction::Initialize(*authorized, *lockup),
vec![
AccountMeta::new(*stake_pubkey, false),
AccountMeta::new_readonly(sysvar::rent::id(), false),
],
)
}
pub fn create_account_with_seed(
from_pubkey: &Pubkey,
stake_pubkey: &Pubkey,
base: &Pubkey,
seed: &str,
authorized: &Authorized,
lockup: &Lockup,
lamports: u64,
) -> Vec<Instruction> {
vec![
system_instruction::create_account_with_seed(
from_pubkey,
stake_pubkey,
base,
seed,
lamports,
std::mem::size_of::<StakeState>() as u64,
&id(),
),
initialize(stake_pubkey, authorized, lockup),
]
}
pub fn create_account(
from_pubkey: &Pubkey,
stake_pubkey: &Pubkey,
authorized: &Authorized,
lockup: &Lockup,
lamports: u64,
) -> Vec<Instruction> {
vec![
system_instruction::create_account(
from_pubkey,
stake_pubkey,
lamports,
std::mem::size_of::<StakeState>() as u64,
&id(),
),
initialize(stake_pubkey, authorized, lockup),
]
}
fn _split(
stake_pubkey: &Pubkey,
authorized_pubkey: &Pubkey,
lamports: u64,
split_stake_pubkey: &Pubkey,
) -> Instruction {
let account_metas = vec![
AccountMeta::new(*stake_pubkey, false),
AccountMeta::new(*split_stake_pubkey, false),
AccountMeta::new_readonly(*authorized_pubkey, true),
];
Instruction::new_with_bincode(id(), &StakeInstruction::Split(lamports), account_metas)
}
pub fn split(
stake_pubkey: &Pubkey,
authorized_pubkey: &Pubkey,
lamports: u64,
split_stake_pubkey: &Pubkey,
) -> Vec<Instruction> {
vec![
system_instruction::create_account(
authorized_pubkey, // Sending 0, so any signer will suffice
split_stake_pubkey,
0,
std::mem::size_of::<StakeState>() as u64,
&id(),
),
_split(
stake_pubkey,
authorized_pubkey,
lamports,
split_stake_pubkey,
),
]
}
pub fn split_with_seed(
stake_pubkey: &Pubkey,
authorized_pubkey: &Pubkey,
lamports: u64,
split_stake_pubkey: &Pubkey, // derived using create_with_seed()
base: &Pubkey, // base
seed: &str, // seed
) -> Vec<Instruction> {
vec![
system_instruction::create_account_with_seed(
authorized_pubkey, // Sending 0, so any signer will suffice
split_stake_pubkey,
base,
seed,
0,
std::mem::size_of::<StakeState>() as u64,
&id(),
),
_split(
stake_pubkey,
authorized_pubkey,
lamports,
split_stake_pubkey,
),
]
}
pub fn merge(
destination_stake_pubkey: &Pubkey,
source_stake_pubkey: &Pubkey,
authorized_pubkey: &Pubkey,
) -> Vec<Instruction> {
let account_metas = vec![
AccountMeta::new(*destination_stake_pubkey, false),
AccountMeta::new(*source_stake_pubkey, false),
AccountMeta::new_readonly(sysvar::clock::id(), false),
AccountMeta::new_readonly(sysvar::stake_history::id(), false),
AccountMeta::new_readonly(*authorized_pubkey, true),
];
vec![Instruction::new_with_bincode(
id(),
&StakeInstruction::Merge,
account_metas,
)]
}
pub fn create_account_and_delegate_stake(
from_pubkey: &Pubkey,
stake_pubkey: &Pubkey,
vote_pubkey: &Pubkey,
authorized: &Authorized,
lockup: &Lockup,
lamports: u64,
) -> Vec<Instruction> {
let mut instructions = create_account(from_pubkey, stake_pubkey, authorized, lockup, lamports);
instructions.push(delegate_stake(
stake_pubkey,
&authorized.staker,
vote_pubkey,
));
instructions
}
pub fn create_account_with_seed_and_delegate_stake(
from_pubkey: &Pubkey,
stake_pubkey: &Pubkey,
base: &Pubkey,
seed: &str,
vote_pubkey: &Pubkey,
authorized: &Authorized,
lockup: &Lockup,
lamports: u64,
) -> Vec<Instruction> {
let mut instructions = create_account_with_seed(
from_pubkey,
stake_pubkey,
base,
seed,
authorized,
lockup,
lamports,
);
instructions.push(delegate_stake(
stake_pubkey,
&authorized.staker,
vote_pubkey,
));
instructions
}
pub fn authorize(
stake_pubkey: &Pubkey,
authorized_pubkey: &Pubkey,
new_authorized_pubkey: &Pubkey,
stake_authorize: StakeAuthorize,
custodian_pubkey: Option<&Pubkey>,
) -> Instruction {
let mut account_metas = vec![
AccountMeta::new(*stake_pubkey, false),
AccountMeta::new_readonly(sysvar::clock::id(), false),
AccountMeta::new_readonly(*authorized_pubkey, true),
];
if let Some(custodian_pubkey) = custodian_pubkey {
account_metas.push(AccountMeta::new_readonly(*custodian_pubkey, true));
}
Instruction::new_with_bincode(
id(),
&StakeInstruction::Authorize(*new_authorized_pubkey, stake_authorize),
account_metas,
)
}
pub fn authorize_with_seed(
stake_pubkey: &Pubkey,
authority_base: &Pubkey,
authority_seed: String,
authority_owner: &Pubkey,
new_authorized_pubkey: &Pubkey,
stake_authorize: StakeAuthorize,
custodian_pubkey: Option<&Pubkey>,
) -> Instruction {
let mut account_metas = vec![
AccountMeta::new(*stake_pubkey, false),
AccountMeta::new_readonly(*authority_base, true),
AccountMeta::new_readonly(sysvar::clock::id(), false),
];
if let Some(custodian_pubkey) = custodian_pubkey {
account_metas.push(AccountMeta::new_readonly(*custodian_pubkey, true));
}
let args = AuthorizeWithSeedArgs {
new_authorized_pubkey: *new_authorized_pubkey,
stake_authorize,
authority_seed,
authority_owner: *authority_owner,
};
Instruction::new_with_bincode(
id(),
&StakeInstruction::AuthorizeWithSeed(args),
account_metas,
)
}
pub fn delegate_stake(
stake_pubkey: &Pubkey,
authorized_pubkey: &Pubkey,
vote_pubkey: &Pubkey,
) -> Instruction {
let account_metas = vec![
AccountMeta::new(*stake_pubkey, false),
AccountMeta::new_readonly(*vote_pubkey, false),
AccountMeta::new_readonly(sysvar::clock::id(), false),
AccountMeta::new_readonly(sysvar::stake_history::id(), false),
AccountMeta::new_readonly(crate::config::id(), false),
AccountMeta::new_readonly(*authorized_pubkey, true),
];
Instruction::new_with_bincode(id(), &StakeInstruction::DelegateStake, account_metas)
}
pub fn withdraw(
stake_pubkey: &Pubkey,
withdrawer_pubkey: &Pubkey,
to_pubkey: &Pubkey,
lamports: u64,
custodian_pubkey: Option<&Pubkey>,
) -> Instruction {
let mut account_metas = vec![
AccountMeta::new(*stake_pubkey, false),
AccountMeta::new(*to_pubkey, false),
AccountMeta::new_readonly(sysvar::clock::id(), false),
AccountMeta::new_readonly(sysvar::stake_history::id(), false),
AccountMeta::new_readonly(*withdrawer_pubkey, true),
];
if let Some(custodian_pubkey) = custodian_pubkey {
account_metas.push(AccountMeta::new_readonly(*custodian_pubkey, true));
}
Instruction::new_with_bincode(id(), &StakeInstruction::Withdraw(lamports), account_metas)
}
pub fn deactivate_stake(stake_pubkey: &Pubkey, authorized_pubkey: &Pubkey) -> Instruction {
let account_metas = vec![
AccountMeta::new(*stake_pubkey, false),
AccountMeta::new_readonly(sysvar::clock::id(), false),
AccountMeta::new_readonly(*authorized_pubkey, true),
];
Instruction::new_with_bincode(id(), &StakeInstruction::Deactivate, account_metas)
}
pub fn set_lockup(
stake_pubkey: &Pubkey,
lockup: &LockupArgs,
custodian_pubkey: &Pubkey,
) -> Instruction {
let account_metas = vec![
AccountMeta::new(*stake_pubkey, false),
AccountMeta::new_readonly(*custodian_pubkey, true),
];
Instruction::new_with_bincode(id(), &StakeInstruction::SetLockup(*lockup), account_metas)
}
pub fn process_instruction(
_program_id: &Pubkey,
keyed_accounts: &[KeyedAccount],
data: &[u8],
invoke_context: &mut dyn InvokeContext,
) -> Result<(), InstructionError> {
trace!("process_instruction: {:?}", data);
trace!("keyed_accounts: {:?}", keyed_accounts);
let signers = get_signers(keyed_accounts);
let keyed_accounts = &mut keyed_accounts.iter();
let me = &next_keyed_account(keyed_accounts)?;
if me.owner()? != id() {
if invoke_context.is_feature_active(&feature_set::check_program_owner::id()) {
return Err(InstructionError::InvalidAccountOwner);
} else {
return Err(InstructionError::IncorrectProgramId);
}
}
match limited_deserialize(data)? {
StakeInstruction::Initialize(authorized, lockup) => me.initialize(
&authorized,
&lockup,
&from_keyed_account::<Rent>(next_keyed_account(keyed_accounts)?)?,
),
StakeInstruction::Authorize(authorized_pubkey, stake_authorize) => {
let require_custodian_for_locked_stake_authorize = invoke_context.is_feature_active(
&feature_set::require_custodian_for_locked_stake_authorize::id(),
);
if require_custodian_for_locked_stake_authorize {
let clock = from_keyed_account::<Clock>(next_keyed_account(keyed_accounts)?)?;
let _current_authority = next_keyed_account(keyed_accounts)?;
let custodian = keyed_accounts.next().map(|ka| ka.unsigned_key());
me.authorize(
&signers,
&authorized_pubkey,
stake_authorize,
require_custodian_for_locked_stake_authorize,
&clock,
custodian,
)
} else {
me.authorize(
&signers,
&authorized_pubkey,
stake_authorize,
require_custodian_for_locked_stake_authorize,
&Clock::default(),
None,
)
}
}
StakeInstruction::AuthorizeWithSeed(args) => {
let authority_base = next_keyed_account(keyed_accounts)?;
let require_custodian_for_locked_stake_authorize = invoke_context.is_feature_active(
&feature_set::require_custodian_for_locked_stake_authorize::id(),
);
if require_custodian_for_locked_stake_authorize {
let clock = from_keyed_account::<Clock>(next_keyed_account(keyed_accounts)?)?;
let custodian = keyed_accounts.next().map(|ka| ka.unsigned_key());
me.authorize_with_seed(
&authority_base,
&args.authority_seed,
&args.authority_owner,
&args.new_authorized_pubkey,
args.stake_authorize,
require_custodian_for_locked_stake_authorize,
&clock,
custodian,
)
} else {
me.authorize_with_seed(
&authority_base,
&args.authority_seed,
&args.authority_owner,
&args.new_authorized_pubkey,
args.stake_authorize,
require_custodian_for_locked_stake_authorize,
&Clock::default(),
None,
)
}
}
StakeInstruction::DelegateStake => {
let vote = next_keyed_account(keyed_accounts)?;
me.delegate(
&vote,
&from_keyed_account::<Clock>(next_keyed_account(keyed_accounts)?)?,
&from_keyed_account::<StakeHistory>(next_keyed_account(keyed_accounts)?)?,
&config::from_keyed_account(next_keyed_account(keyed_accounts)?)?,
&signers,
)
}
StakeInstruction::Split(lamports) => {
let split_stake = &next_keyed_account(keyed_accounts)?;
me.split(lamports, split_stake, &signers)
}
StakeInstruction::Merge => {
let source_stake = &next_keyed_account(keyed_accounts)?;
me.merge(
invoke_context,
source_stake,
&from_keyed_account::<Clock>(next_keyed_account(keyed_accounts)?)?,
&from_keyed_account::<StakeHistory>(next_keyed_account(keyed_accounts)?)?,
&signers,
)
}
StakeInstruction::Withdraw(lamports) => {
let to = &next_keyed_account(keyed_accounts)?;
me.withdraw(
lamports,
to,
&from_keyed_account::<Clock>(next_keyed_account(keyed_accounts)?)?,
&from_keyed_account::<StakeHistory>(next_keyed_account(keyed_accounts)?)?,
next_keyed_account(keyed_accounts)?,
keyed_accounts.next(),
)
}
StakeInstruction::Deactivate => me.deactivate(
&from_keyed_account::<Clock>(next_keyed_account(keyed_accounts)?)?,
&signers,
),
StakeInstruction::SetLockup(lockup) => me.set_lockup(&lockup, &signers),
}
}
#[cfg(test)]
mod tests {
use super::*;
use bincode::serialize;
use solana_sdk::{
account::{self, Account, AccountSharedData},
process_instruction::MockInvokeContext,
rent::Rent,
sysvar::stake_history::StakeHistory,
};
use std::cell::RefCell;
use std::str::FromStr;
fn create_default_account() -> RefCell<AccountSharedData> {
RefCell::new(AccountSharedData::default())
}
fn create_default_stake_account() -> RefCell<AccountSharedData> {
RefCell::new(AccountSharedData::from(Account {
owner: id(),
..Account::default()
}))
}
fn invalid_stake_state_pubkey() -> Pubkey {
Pubkey::from_str("BadStake11111111111111111111111111111111111").unwrap()
}
fn invalid_vote_state_pubkey() -> Pubkey {
Pubkey::from_str("BadVote111111111111111111111111111111111111").unwrap()
}
fn spoofed_stake_state_pubkey() -> Pubkey {
Pubkey::from_str("SpoofedStake1111111111111111111111111111111").unwrap()
}
fn spoofed_stake_program_id() -> Pubkey {
Pubkey::from_str("Spoofed111111111111111111111111111111111111").unwrap()
}
fn process_instruction(instruction: &Instruction) -> Result<(), InstructionError> {
let accounts: Vec<_> = instruction
.accounts
.iter()
.map(|meta| {
RefCell::new(if sysvar::clock::check_id(&meta.pubkey) {
account::create_account_shared_data(&sysvar::clock::Clock::default(), 1)
} else if sysvar::rewards::check_id(&meta.pubkey) {
account::create_account_shared_data(&sysvar::rewards::Rewards::new(0.0), 1)
} else if sysvar::stake_history::check_id(&meta.pubkey) {
account::create_account_shared_data(&StakeHistory::default(), 1)
} else if config::check_id(&meta.pubkey) {
config::create_account(0, &config::Config::default())
} else if sysvar::rent::check_id(&meta.pubkey) {
account::create_account_shared_data(&Rent::default(), 1)
} else if meta.pubkey == invalid_stake_state_pubkey() {
AccountSharedData::from(Account {
owner: id(),
..Account::default()
})
} else if meta.pubkey == invalid_vote_state_pubkey() {
AccountSharedData::from(Account {
owner: solana_vote_program::id(),
..Account::default()
})
} else if meta.pubkey == spoofed_stake_state_pubkey() {
AccountSharedData::from(Account {
owner: spoofed_stake_program_id(),
..Account::default()
})
} else {
AccountSharedData::from(Account {
owner: id(),
..Account::default()
})
})
})
.collect();
{
let keyed_accounts: Vec<_> = instruction
.accounts
.iter()
.zip(accounts.iter())
.map(|(meta, account)| KeyedAccount::new(&meta.pubkey, meta.is_signer, account))
.collect();
super::process_instruction(
&Pubkey::default(),
&keyed_accounts,
&instruction.data,
&mut MockInvokeContext::default(),
)
}
}
#[test]
fn test_stake_process_instruction() {
assert_eq!(
process_instruction(&initialize(
&Pubkey::default(),
&Authorized::default(),
&Lockup::default()
)),
Err(InstructionError::InvalidAccountData),
);
assert_eq!(
process_instruction(&authorize(
&Pubkey::default(),
&Pubkey::default(),
&Pubkey::default(),
StakeAuthorize::Staker,
None,
)),
Err(InstructionError::InvalidAccountData),
);
assert_eq!(
process_instruction(
&split(
&Pubkey::default(),
&Pubkey::default(),
100,
&invalid_stake_state_pubkey(),
)[1]
),
Err(InstructionError::InvalidAccountData),
);
assert_eq!(
process_instruction(
&merge(
&Pubkey::default(),
&invalid_stake_state_pubkey(),
&Pubkey::default(),
)[0]
),
Err(InstructionError::InvalidAccountData),
);
assert_eq!(
process_instruction(
&split_with_seed(
&Pubkey::default(),
&Pubkey::default(),
100,
&invalid_stake_state_pubkey(),
&Pubkey::default(),
"seed"
)[1]
),
Err(InstructionError::InvalidAccountData),
);
assert_eq!(
process_instruction(&delegate_stake(
&Pubkey::default(),
&Pubkey::default(),
&invalid_vote_state_pubkey(),
)),
Err(InstructionError::InvalidAccountData),
);
assert_eq!(
process_instruction(&withdraw(
&Pubkey::default(),
&Pubkey::default(),
&solana_sdk::pubkey::new_rand(),
100,
None,
)),
Err(InstructionError::InvalidAccountData),
);
assert_eq!(
process_instruction(&deactivate_stake(&Pubkey::default(), &Pubkey::default())),
Err(InstructionError::InvalidAccountData),
);
assert_eq!(
process_instruction(&set_lockup(
&Pubkey::default(),
&LockupArgs::default(),
&Pubkey::default()
)),
Err(InstructionError::InvalidAccountData),
);
}
#[test]
fn test_spoofed_stake_accounts() {
assert_eq!(
process_instruction(&initialize(
&spoofed_stake_state_pubkey(),
&Authorized::default(),
&Lockup::default()
)),
Err(InstructionError::InvalidAccountOwner),
);
assert_eq!(
process_instruction(&authorize(
&spoofed_stake_state_pubkey(),
&Pubkey::default(),
&Pubkey::default(),
StakeAuthorize::Staker,
None,
)),
Err(InstructionError::InvalidAccountOwner),
);
assert_eq!(
process_instruction(
&split(
&spoofed_stake_state_pubkey(),
&Pubkey::default(),
100,
&Pubkey::default(),
)[1]
),
Err(InstructionError::InvalidAccountOwner),
);
assert_eq!(
process_instruction(
&split(
&Pubkey::default(),
&Pubkey::default(),
100,
&spoofed_stake_state_pubkey(),
)[1]
),
Err(InstructionError::IncorrectProgramId),
);
assert_eq!(
process_instruction(
&merge(
&spoofed_stake_state_pubkey(),
&Pubkey::default(),
&Pubkey::default(),
)[0]
),
Err(InstructionError::InvalidAccountOwner),
);
assert_eq!(
process_instruction(
&merge(
&Pubkey::default(),
&spoofed_stake_state_pubkey(),
&Pubkey::default(),
)[0]
),
Err(InstructionError::IncorrectProgramId),
);
assert_eq!(
process_instruction(
&split_with_seed(
&spoofed_stake_state_pubkey(),
&Pubkey::default(),
100,
&Pubkey::default(),
&Pubkey::default(),
"seed"
)[1]
),
Err(InstructionError::InvalidAccountOwner),
);
assert_eq!(
process_instruction(&delegate_stake(
&spoofed_stake_state_pubkey(),
&Pubkey::default(),
&Pubkey::default(),
)),
Err(InstructionError::InvalidAccountOwner),
);
assert_eq!(
process_instruction(&withdraw(
&spoofed_stake_state_pubkey(),
&Pubkey::default(),
&solana_sdk::pubkey::new_rand(),
100,
None,
)),
Err(InstructionError::InvalidAccountOwner),
);
assert_eq!(
process_instruction(&deactivate_stake(
&spoofed_stake_state_pubkey(),
&Pubkey::default()
)),
Err(InstructionError::InvalidAccountOwner),
);
assert_eq!(
process_instruction(&set_lockup(
&spoofed_stake_state_pubkey(),
&LockupArgs::default(),
&Pubkey::default()
)),
Err(InstructionError::InvalidAccountOwner),
);
}
#[test]
fn test_stake_process_instruction_decode_bail() {
// these will not call stake_state, have bogus contents
// gets the "is_empty()" check
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&[],
&serialize(&StakeInstruction::Initialize(
Authorized::default(),
Lockup::default()
))
.unwrap(),
&mut MockInvokeContext::default()
),
Err(InstructionError::NotEnoughAccountKeys),
);
// no account for rent
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&[KeyedAccount::new(
&Pubkey::default(),
false,
&create_default_stake_account(),
)],
&serialize(&StakeInstruction::Initialize(
Authorized::default(),
Lockup::default()
))
.unwrap(),
&mut MockInvokeContext::default()
),
Err(InstructionError::NotEnoughAccountKeys),
);
// rent fails to deserialize
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&[
KeyedAccount::new(&Pubkey::default(), false, &create_default_stake_account()),
KeyedAccount::new(&sysvar::rent::id(), false, &create_default_account())
],
&serialize(&StakeInstruction::Initialize(
Authorized::default(),
Lockup::default()
))
.unwrap(),
&mut MockInvokeContext::default()
),
Err(InstructionError::InvalidArgument),
);
// fails to deserialize stake state
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&[
KeyedAccount::new(&Pubkey::default(), false, &create_default_stake_account()),
KeyedAccount::new(
&sysvar::rent::id(),
false,
&RefCell::new(account::create_account_shared_data(&Rent::default(), 0))
)
],
&serialize(&StakeInstruction::Initialize(
Authorized::default(),
Lockup::default()
))
.unwrap(),
&mut MockInvokeContext::default()
),
Err(InstructionError::InvalidAccountData),
);
// gets the first check in delegate, wrong number of accounts
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&[KeyedAccount::new(
&Pubkey::default(),
false,
&create_default_stake_account()
),],
&serialize(&StakeInstruction::DelegateStake).unwrap(),
&mut MockInvokeContext::default()
),
Err(InstructionError::NotEnoughAccountKeys),
);
// gets the sub-check for number of args
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&[KeyedAccount::new(
&Pubkey::default(),
false,
&create_default_stake_account()
)],
&serialize(&StakeInstruction::DelegateStake).unwrap(),
&mut MockInvokeContext::default()
),
Err(InstructionError::NotEnoughAccountKeys),
);
// gets the check non-deserialize-able account in delegate_stake
let mut bad_vote_account = create_default_account();
bad_vote_account.get_mut().owner = solana_vote_program::id();
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&[
KeyedAccount::new(&Pubkey::default(), true, &create_default_stake_account()),
KeyedAccount::new(&Pubkey::default(), false, &bad_vote_account),
KeyedAccount::new(
&sysvar::clock::id(),
false,
&RefCell::new(account::create_account_shared_data(
&sysvar::clock::Clock::default(),
1
))
),
KeyedAccount::new(
&sysvar::stake_history::id(),
false,
&RefCell::new(account::create_account_shared_data(
&sysvar::stake_history::StakeHistory::default(),
1
))
),
KeyedAccount::new(
&config::id(),
false,
&RefCell::new(config::create_account(0, &config::Config::default()))
),
],
&serialize(&StakeInstruction::DelegateStake).unwrap(),
&mut MockInvokeContext::default()
),
Err(InstructionError::InvalidAccountData),
);
// Tests 3rd keyed account is of correct type (Clock instead of rewards) in withdraw
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&[
KeyedAccount::new(&Pubkey::default(), false, &create_default_stake_account()),
KeyedAccount::new(&Pubkey::default(), false, &create_default_account()),
KeyedAccount::new(
&sysvar::rewards::id(),
false,
&RefCell::new(account::create_account_shared_data(
&sysvar::rewards::Rewards::new(0.0),
1
))
),
KeyedAccount::new(
&sysvar::stake_history::id(),
false,
&RefCell::new(account::create_account_shared_data(
&StakeHistory::default(),
1,
))
),
],
&serialize(&StakeInstruction::Withdraw(42)).unwrap(),
&mut MockInvokeContext::default()
),
Err(InstructionError::InvalidArgument),
);
// Tests correct number of accounts are provided in withdraw
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&[KeyedAccount::new(
&Pubkey::default(),
false,
&create_default_stake_account()
)],
&serialize(&StakeInstruction::Withdraw(42)).unwrap(),
&mut MockInvokeContext::default()
),
Err(InstructionError::NotEnoughAccountKeys),
);
// Tests 2nd keyed account is of correct type (Clock instead of rewards) in deactivate
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&[
KeyedAccount::new(&Pubkey::default(), false, &create_default_stake_account()),
KeyedAccount::new(
&sysvar::rewards::id(),
false,
&RefCell::new(account::create_account_shared_data(
&sysvar::rewards::Rewards::new(0.0),
1
))
),
],
&serialize(&StakeInstruction::Deactivate).unwrap(),
&mut MockInvokeContext::default()
),
Err(InstructionError::InvalidArgument),
);
// Tests correct number of accounts are provided in deactivate
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&[],
&serialize(&StakeInstruction::Deactivate).unwrap(),
&mut MockInvokeContext::default()
),
Err(InstructionError::NotEnoughAccountKeys),
);
}
#[test]
fn test_custom_error_decode() {
use num_traits::FromPrimitive;
fn pretty_err<T>(err: InstructionError) -> String
where
T: 'static + std::error::Error + DecodeError<T> + FromPrimitive,
{
if let InstructionError::Custom(code) = err {
let specific_error: T = T::decode_custom_error_to_enum(code).unwrap();
format!(
"{:?}: {}::{:?} - {}",
err,
T::type_of(),
specific_error,
specific_error,
)
} else {
"".to_string()
}
}
assert_eq!(
"Custom(0): StakeError::NoCreditsToRedeem - not enough credits to redeem",
pretty_err::<StakeError>(StakeError::NoCreditsToRedeem.into())
)
}
}
| 34.089655 | 99 | 0.543673 |
48164e6af09b12be109d3640ddb941a9b7fbe690 | 192 | extern crate gfx;
#[macro_use] extern crate gfx_macros;
#[derive(VertexData)]
struct Vertex {
pos: [u8; 4],
}
#[derive(ConstantBuffer)]
struct Constant {
transform: [[f32; 4]; 4],
}
| 14.769231 | 37 | 0.65625 |
763bc4c6cddb90028ab956064225984c7f40fcc6 | 662 | #![deny(rustdoc::invalid_codeblock_attributes)]
/// foo
//~^ ERROR
//~^^ ERROR
//~^^^ ERROR
///
/// ```compile-fail,compilefail,comPile_fail
/// boo
/// ```
pub fn foo() {}
/// bar
//~^ ERROR
//~^^ ERROR
//~^^^ ERROR
///
/// ```should-panic,shouldpanic,sHould_panic
/// boo
/// ```
pub fn bar() {}
/// foobar
//~^ ERROR
//~^^ ERROR
//~^^^ ERROR
///
/// ```no-run,norun,no_Run
/// boo
/// ```
pub fn foobar() {}
/// barfoo
//~^ ERROR
//~^^ ERROR
//~^^^ ERROR
///
/// ```allow-fail,allowfail,alLow_fail
/// boo
/// ```
pub fn barfoo() {}
/// b
//~^ ERROR
//~^^ ERROR
//~^^^ ERROR
///
/// ```test-harness,testharness,teSt_harness
/// boo
/// ```
pub fn b() {}
| 12.730769 | 47 | 0.510574 |
2687a2955e921b9baeeb04af59daabe2310433b0 | 3,918 | /*
* Nomad
*
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 1.1.4
* Contact: [email protected]
* Generated by: https://openapi-generator.tech
*/
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct ServiceCheck {
#[serde(rename = "AddressMode", skip_serializing_if = "Option::is_none")]
pub address_mode: Option<String>,
#[serde(rename = "Args", skip_serializing_if = "Option::is_none")]
pub args: Option<Vec<String>>,
#[serde(rename = "Body", skip_serializing_if = "Option::is_none")]
pub body: Option<String>,
#[serde(rename = "CheckRestart", skip_serializing_if = "Option::is_none")]
pub check_restart: Option<Box<crate::models::CheckRestart>>,
#[serde(rename = "Command", skip_serializing_if = "Option::is_none")]
pub command: Option<String>,
#[serde(rename = "Expose", skip_serializing_if = "Option::is_none")]
pub expose: Option<bool>,
#[serde(
rename = "FailuresBeforeCritical",
skip_serializing_if = "Option::is_none"
)]
pub failures_before_critical: Option<i32>,
#[serde(rename = "GRPCService", skip_serializing_if = "Option::is_none")]
pub grpc_service: Option<String>,
#[serde(rename = "GRPCUseTLS", skip_serializing_if = "Option::is_none")]
pub grpc_use_tls: Option<bool>,
#[serde(rename = "Header", skip_serializing_if = "Option::is_none")]
pub header: Option<::std::collections::HashMap<String, Vec<String>>>,
#[serde(rename = "Id", skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "InitialStatus", skip_serializing_if = "Option::is_none")]
pub initial_status: Option<String>,
#[serde(rename = "Interval", skip_serializing_if = "Option::is_none")]
pub interval: Option<i64>,
#[serde(rename = "Method", skip_serializing_if = "Option::is_none")]
pub method: Option<String>,
#[serde(rename = "Name", skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "OnUpdate", skip_serializing_if = "Option::is_none")]
pub on_update: Option<String>,
#[serde(rename = "Path", skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
#[serde(rename = "PortLabel", skip_serializing_if = "Option::is_none")]
pub port_label: Option<String>,
#[serde(rename = "Protocol", skip_serializing_if = "Option::is_none")]
pub protocol: Option<String>,
#[serde(
rename = "SuccessBeforePassing",
skip_serializing_if = "Option::is_none"
)]
pub success_before_passing: Option<i32>,
#[serde(rename = "TLSSkipVerify", skip_serializing_if = "Option::is_none")]
pub tls_skip_verify: Option<bool>,
#[serde(rename = "TaskName", skip_serializing_if = "Option::is_none")]
pub task_name: Option<String>,
#[serde(rename = "Timeout", skip_serializing_if = "Option::is_none")]
pub timeout: Option<i64>,
#[serde(rename = "Type", skip_serializing_if = "Option::is_none")]
pub _type: Option<String>,
}
impl ServiceCheck {
pub fn new() -> ServiceCheck {
ServiceCheck {
address_mode: None,
args: None,
body: None,
check_restart: None,
command: None,
expose: None,
failures_before_critical: None,
grpc_service: None,
grpc_use_tls: None,
header: None,
id: None,
initial_status: None,
interval: None,
method: None,
name: None,
on_update: None,
path: None,
port_label: None,
protocol: None,
success_before_passing: None,
tls_skip_verify: None,
task_name: None,
timeout: None,
_type: None,
}
}
}
| 39.575758 | 109 | 0.634763 |
c19694ab7687c4c4f3c84462d6c66de8c0b5b75f | 9,419 | //! An asynchronous, pipelined, PostgreSQL client.
//!
//! # Example
//!
//! ```no_run
//! use tokio_postgres::{NoTls, Error};
//!
//! # #[cfg(not(feature = "runtime"))] fn main() {}
//! # #[cfg(feature = "runtime")]
//! #[tokio::main] // By default, tokio_postgres uses the tokio crate as its runtime.
//! async fn main() -> Result<(), Error> {
//! // Connect to the database.
//! let (client, connection) =
//! tokio_postgres::connect("host=localhost user=postgres", NoTls).await?;
//!
//! // The connection object performs the actual communication with the database,
//! // so spawn it off to run on its own.
//! tokio::spawn(async move {
//! if let Err(e) = connection.await {
//! eprintln!("connection error: {}", e);
//! }
//! });
//!
//! // Now we can execute a simple statement that just returns its parameter.
//! let rows = client
//! .query("SELECT $1::TEXT", &[&"hello world"])
//! .await?;
//!
//! // And then check that we got back the same string we sent over.
//! let value: &str = rows[0].get(0);
//! assert_eq!(value, "hello world");
//!
//! Ok(())
//! }
//! ```
//!
//! # Behavior
//!
//! Calling a method like `Client::query` on its own does nothing. The associated request is not sent to the database
//! until the future returned by the method is first polled. Requests are executed in the order that they are first
//! polled, not in the order that their futures are created.
//!
//! # Pipelining
//!
//! The client supports *pipelined* requests. Pipelining can improve performance in use cases in which multiple,
//! independent queries need to be executed. In a traditional workflow, each query is sent to the server after the
//! previous query completes. In contrast, pipelining allows the client to send all of the queries to the server up
//! front, minimizing time spent by one side waiting for the other to finish sending data:
//!
//! ```not_rust
//! Sequential Pipelined
//! | Client | Server | | Client | Server |
//! |----------------|-----------------| |----------------|-----------------|
//! | send query 1 | | | send query 1 | |
//! | | process query 1 | | send query 2 | process query 1 |
//! | receive rows 1 | | | send query 3 | process query 2 |
//! | send query 2 | | | receive rows 1 | process query 3 |
//! | | process query 2 | | receive rows 2 | |
//! | receive rows 2 | | | receive rows 3 | |
//! | send query 3 | |
//! | | process query 3 |
//! | receive rows 3 | |
//! ```
//!
//! In both cases, the PostgreSQL server is executing the queries sequentially - pipelining just allows both sides of
//! the connection to work concurrently when possible.
//!
//! Pipelining happens automatically when futures are polled concurrently (for example, by using the futures `join`
//! combinator):
//!
//! ```rust
//! use futures::future;
//! use std::future::Future;
//! use tokio_postgres::{Client, Error, Statement};
//!
//! async fn pipelined_prepare(
//! client: &Client,
//! ) -> Result<(Statement, Statement), Error>
//! {
//! future::try_join(
//! client.prepare("SELECT * FROM foo"),
//! client.prepare("INSERT INTO bar (id, name) VALUES ($1, $2)")
//! ).await
//! }
//! ```
//!
//! # Runtime
//!
//! The client works with arbitrary `AsyncRead + AsyncWrite` streams. Convenience APIs are provided to handle the
//! connection process, but these are gated by the `runtime` Cargo feature, which is enabled by default. If disabled,
//! all dependence on the tokio runtime is removed.
//!
//! # SSL/TLS support
//!
//! TLS support is implemented via external libraries. `Client::connect` and `Config::connect` take a TLS implementation
//! as an argument. The `NoTls` type in this crate can be used when TLS is not required. Otherwise, the
//! `postgres-openssl` and `postgres-native-tls` crates provide implementations backed by the `openssl` and `native-tls`
//! crates, respectively.
//!
//! # Features
//!
//! The following features can be enabled from `Cargo.toml`:
//!
//! | Feature | Description | Extra dependencies | Default |
//! | ------- | ----------- | ------------------ | ------- |
//! | `runtime` | Enable convenience API for the connection process based on the `tokio` crate. | [tokio](https://crates.io/crates/tokio) 1.0 with the features `net` and `time` | yes |
//! | `with-bit-vec-0_6` | Enable support for the `bit-vec` crate. | [bit-vec](https://crates.io/crates/bit-vec) 0.6 | no |
//! | `with-chrono-0_4` | Enable support for the `chrono` crate. | [chrono](https://crates.io/crates/chrono) 0.4 | no |
//! | `with-eui48-0_4` | Enable support for the 0.4 version of the `eui48` crate. | [eui48](https://crates.io/crates/eui48) 0.4 | no |
//! | `with-eui48-1` | Enable support for the 1.0 version of the `eui48` crate. | [eui48](https://crates.io/crates/eui48) 1.0 | no |
//! | `with-geo-types-0_6` | Enable support for the 0.6 version of the `geo-types` crate. | [geo-types](https://crates.io/crates/geo-types/0.6.0) 0.6 | no |
//! | `with-geo-types-0_7` | Enable support for the 0.7 version of the `geo-types` crate. | [geo-types](https://crates.io/crates/geo-types/0.7.0) 0.7 | no |
//! | `with-serde_json-1` | Enable support for the `serde_json` crate. | [serde_json](https://crates.io/crates/serde_json) 1.0 | no |
//! | `with-uuid-0_8` | Enable support for the `uuid` crate. | [uuid](https://crates.io/crates/uuid) 0.8 | no |
//! | `with-time-0_2` | Enable support for the `time` crate. | [time](https://crates.io/crates/time) 0.2 | no |
#![doc(html_root_url = "https://docs.rs/tokio-postgres/0.7")]
#![warn(rust_2018_idioms, clippy::all, missing_docs)]
pub use crate::cancel_token::CancelToken;
pub use crate::client::Client;
pub use crate::config::Config;
pub use crate::connection::Connection;
pub use crate::copy_both::CopyBothDuplex;
pub use crate::copy_in::CopyInSink;
pub use crate::copy_out::CopyOutStream;
use crate::error::DbError;
pub use crate::error::Error;
pub use crate::generic_client::GenericClient;
pub use crate::portal::Portal;
pub use crate::query::RowStream;
pub use crate::row::{Row, SimpleQueryRow};
pub use crate::simple_query::SimpleQueryStream;
#[cfg(feature = "runtime")]
pub use crate::socket::Socket;
pub use crate::statement::{Column, Statement};
#[cfg(feature = "runtime")]
use crate::tls::MakeTlsConnect;
pub use crate::tls::NoTls;
pub use crate::to_statement::ToStatement;
pub use crate::transaction::Transaction;
pub use crate::transaction_builder::{IsolationLevel, TransactionBuilder};
use crate::types::ToSql;
pub mod binary_copy;
mod bind;
#[cfg(feature = "runtime")]
mod cancel_query;
mod cancel_query_raw;
mod cancel_token;
mod client;
mod codec;
pub mod config;
#[cfg(feature = "runtime")]
mod connect;
mod connect_raw;
#[cfg(feature = "runtime")]
mod connect_socket;
mod connect_tls;
mod connection;
mod copy_both;
mod copy_in;
mod copy_out;
pub mod error;
mod generic_client;
mod maybe_tls_stream;
mod portal;
mod prepare;
mod query;
pub mod row;
mod simple_query;
#[cfg(feature = "runtime")]
mod socket;
mod statement;
pub mod tls;
mod to_statement;
mod transaction;
mod transaction_builder;
pub mod types;
/// A convenience function which parses a connection string and connects to the database.
///
/// See the documentation for [`Config`] for details on the connection string format.
///
/// Requires the `runtime` Cargo feature (enabled by default).
///
/// [`Config`]: config/struct.Config.html
#[cfg(feature = "runtime")]
pub async fn connect<T>(
config: &str,
tls: T,
) -> Result<(Client, Connection<Socket, T::Stream>), Error>
where
T: MakeTlsConnect<Socket>,
{
let config = config.parse::<Config>()?;
config.connect(tls).await
}
/// An asynchronous notification.
#[derive(Clone, Debug)]
pub struct Notification {
process_id: i32,
channel: String,
payload: String,
}
impl Notification {
/// The process ID of the notifying backend process.
pub fn process_id(&self) -> i32 {
self.process_id
}
/// The name of the channel that the notify has been raised on.
pub fn channel(&self) -> &str {
&self.channel
}
/// The "payload" string passed from the notifying process.
pub fn payload(&self) -> &str {
&self.payload
}
}
/// An asynchronous message from the server.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum AsyncMessage {
/// A notice.
///
/// Notices use the same format as errors, but aren't "errors" per-se.
Notice(DbError),
/// A notification.
///
/// Connections can subscribe to notifications with the `LISTEN` command.
Notification(Notification),
}
/// Message returned by the `SimpleQuery` stream.
#[non_exhaustive]
pub enum SimpleQueryMessage {
/// A row of data.
Row(SimpleQueryRow),
/// A statement in the query has completed.
///
/// The number of rows modified or selected is returned.
CommandComplete(u64),
}
fn slice_iter<'a>(
s: &'a [&'a (dyn ToSql + Sync)],
) -> impl ExactSizeIterator<Item = &'a dyn ToSql> + 'a {
s.iter().map(|s| *s as _)
}
| 36.937255 | 184 | 0.634038 |
f531b585ddef8b8602cc44971035e278f6e1a393 | 644 | // 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.
#![feature(box_syntax)]
fn main() {
let x = Some(box 1i);
match x {
Some(ref y) => {
let _b = *y; //~ ERROR cannot move out
}
_ => {}
}
}
| 29.272727 | 68 | 0.656832 |
0e141ee1bd59babae0e271d28357d402381967a8 | 19,084 | #[cfg(test)]
use testing::run_test;
use ed25519::fe::*;
use ed25519::constants::*;
use std::ops::*;
// This is ge_p3 in the original source code
#[derive(Clone,Debug,PartialEq)]
pub struct Point {
pub x: FieldElement,
pub y: FieldElement,
pub z: FieldElement,
pub t: FieldElement
}
impl Point {
fn zero() -> Point
{
Point {
x: FieldElement::zero(),
y: FieldElement::one(),
z: FieldElement::one(),
t: FieldElement::zero(),
}
}
#[cfg(test)]
fn load_test_value(xs: &[u8]) -> Point {
assert!(xs.len() == 160);
Point {
x: test_from_bytes(&xs[0..40]),
y: test_from_bytes(&xs[40..80]),
z: test_from_bytes(&xs[80..120]),
t: test_from_bytes(&xs[120..])
}
}
/// Convert 32 bytes into an ED25519 point. This routine is not
/// statically timed, so don't use it if that's important to you.
pub fn from_bytes(s: &[u8]) -> Option<Point>
{
let hy = FieldElement::from_bytes(s);
let hz = FieldElement::one();
let mut u = hy.square();
let mut v = &u * &D;
u = &u - &hz; /* u = y^2-1 */
v += &hz;
let mut v3 = v.square();
v3 *= &v; /* v3 = v^3 */
let mut hx = v3.square();
hx *= &v;
hx *= &u; /* x = uv^7 */
hx = hx.pow22523(); /* x = (uv^7)^((q-5)/8) */
hx *= &v3;
hx *= &u; /* x = uv^3(uv^7)^((q-5)/8) */
let mut vxx = hx.square();
vxx *= &v;
let mut check = &vxx - &u; /* vx^2-u */
if check.isnonzero() {
check = &vxx + &u;
if check.isnonzero() {
return None;
}
hx *= &SQRTM1;
}
if hx.isnegative() != ((s[31] >> 7) == 1) {
hx = -&hx;
}
let ht = &hx * &hy;
return Some(Point{ x: hx, y: hy, z: hz, t: ht });
}
pub fn encode(&self) -> Vec<u8>
{
into_encoded_point(&self.x, &self.y, &self.z)
}
pub fn invert(&self) -> Point
{
Point {
x: -&self.x,
y: self.y.clone(),
z: self.z.clone(),
t: -&self.t,
}
}
}
const D: FieldElement = FieldElement {
value: [-10913610, 13857413, -15372611, 6949391, 114729,
-8787816, -6275908, -3247719, -18696448, -12055116]
};
const SQRTM1: FieldElement = FieldElement {
value: [-32595792, -7943725, 9377950, 3500415, 12389472,
-272473, -25146209, -2005654, 326686, 11406482]
};
#[cfg(test)]
#[test]
fn from_bytes_vartime() {
let fname = "testdata/ed25519/fbv.test";
run_test(fname.to_string(), 3, |case| {
let (nega, abytes) = case.get("a").unwrap();
let (negb, bbytes) = case.get("b").unwrap();
let (negc, cbytes) = case.get("c").unwrap();
assert!(!nega && !negb && !negc);
let target = Point::load_test_value(&cbytes);
let mine = Point::from_bytes(&abytes);
if bbytes.len() < cbytes.len() {
assert!(mine.is_none());
} else {
assert_eq!(target, mine.unwrap());
}
});
}
#[derive(Debug,PartialEq)]
pub struct Point2 {
pub x: FieldElement,
pub y: FieldElement,
pub z: FieldElement,
}
impl Point2 {
pub fn zero() -> Point2
{
Point2 {
x: FieldElement::zero(),
y: FieldElement::one(),
z: FieldElement::one()
}
}
#[cfg(test)]
fn load_test_value(xs: &[u8]) -> Point2 {
assert!(xs.len() == 120);
Point2 {
x: test_from_bytes(&xs[0..40]),
y: test_from_bytes(&xs[40..80]),
z: test_from_bytes(&xs[80..120]),
}
}
pub fn encode(&self) -> Vec<u8>
{
into_encoded_point(&self.x, &self.y, &self.z)
}
}
impl<'a> From<&'a Point> for Point2 {
fn from(p: &Point) -> Point2 {
Point2 {
x: p.x.clone(),
y: p.y.clone(),
z: p.z.clone(),
}
}
}
#[derive(Debug,PartialEq)]
pub struct PointP1P1 {
x: FieldElement,
y: FieldElement,
z: FieldElement,
t: FieldElement
}
impl PointP1P1 {
#[cfg(test)]
fn load_test_value(xs: &[u8]) -> PointP1P1 {
assert!(xs.len() == 160);
PointP1P1 {
x: test_from_bytes(&xs[0..40]),
y: test_from_bytes(&xs[40..80]),
z: test_from_bytes(&xs[80..120]),
t: test_from_bytes(&xs[120..])
}
}
}
#[derive(Debug,PartialEq)]
struct Cached {
yplusx: FieldElement,
yminusx: FieldElement,
z: FieldElement,
t2d: FieldElement
}
impl Cached
{
fn new() -> Cached
{
Cached {
yplusx: FieldElement::new(),
yminusx: FieldElement::new(),
z: FieldElement::new(),
t2d: FieldElement::new()
}
}
#[cfg(test)]
fn load_test_value(xs: &[u8]) -> Cached {
assert!(xs.len() == 160);
Cached {
yplusx: test_from_bytes(&xs[0..40]),
yminusx: test_from_bytes(&xs[40..80]),
z: test_from_bytes(&xs[80..120]),
t2d: test_from_bytes(&xs[120..])
}
}
}
const D2: FieldElement = FieldElement {
value: [-21827239, -5839606, -30745221, 13898782, 229458,
15978800, -12551817, -6495438, 29715968, 9444199]
};
impl<'a> From<&'a Point> for Cached
{
fn from(p: &Point) -> Cached
{
Cached {
yplusx: &p.y + &p.x,
yminusx: &p.y - &p.x,
z: p.z.clone(),
t2d: &p.t * &D2,
}
}
}
impl<'a> From<&'a PointP1P1> for Point2
{
fn from(p: &PointP1P1) -> Point2
{
Point2 {
x: &p.x * &p.t,
y: &p.y * &p.z,
z: &p.z * &p.t,
}
}
}
impl<'a> From<&'a PointP1P1> for Point
{
fn from(p: &PointP1P1) -> Point
{
Point {
x: &p.x * &p.t,
y: &p.y * &p.z,
z: &p.z * &p.t,
t: &p.x * &p.y,
}
}
}
#[cfg(test)]
#[test]
fn conversion() {
let fname = "testdata/ed25519/conversion.test";
run_test(fname.to_string(), 6, |case| {
let (nega, abytes) = case.get("a").unwrap();
let (negc, cbytes) = case.get("c").unwrap();
let (negt, tbytes) = case.get("t").unwrap();
let (nego, obytes) = case.get("o").unwrap();
let (negd, dbytes) = case.get("d").unwrap();
let (negb, bbytes) = case.get("b").unwrap();
let a = Point::load_test_value(&abytes);
let c = Cached::load_test_value(&cbytes);
let t = Point2::load_test_value(&tbytes);
let o = PointP1P1::load_test_value(&obytes);
let d = Point2::load_test_value(&dbytes);
let b = Point::load_test_value(&bbytes);
assert!(!nega && !negc && !negt && !nego && !negd && !negb);
let myc = Cached::from(&a);
assert_eq!(myc, c);
let myt = Point2::from(&a);
assert_eq!(myt, t);
let myo = a.double();
assert_eq!(myo, o);
let myd = Point2::from(&o);
assert_eq!(myd, d);
let myb = Point::from(&o);
assert_eq!(myb, b);
});
}
/* r = 2 * p */
impl Point2 {
fn double(&self) -> PointP1P1
{
let x0 = self.x.square();
let z0 = self.y.square();
let t0 = self.z.sq2();
let y0 = &self.x + &self.y;
let ry = &z0 + &x0;
let rz = &z0 - &x0;
let rx = &y0.square() - &ry;
let rt = &t0 - &rz;
PointP1P1 { x: rx, y: ry, z: rz, t: rt }
}
}
/* r = 2 * p */
impl Point {
fn double(&self) -> PointP1P1
{
Point2::from(self).double()
}
}
#[cfg(test)]
#[test]
fn double() {
let fname = "testdata/ed25519/pt_double.test";
run_test(fname.to_string(), 4, |case| {
let (nega, abytes) = case.get("a").unwrap();
let (negb, bbytes) = case.get("b").unwrap();
let (negc, cbytes) = case.get("c").unwrap();
let (negd, dbytes) = case.get("d").unwrap();
assert!(!nega && !negb && !negc && !negd);
let a = Point::load_test_value(abytes);
let b = PointP1P1::load_test_value(bbytes);
let c = Point2::load_test_value(cbytes);
let d = PointP1P1::load_test_value(dbytes);
let myb = a.double();
assert_eq!(myb, b);
let myd = c.double();
assert_eq!(myd, d);
});
}
impl<'a,'b> Add<&'a Precomp> for &'b Point
{
type Output = PointP1P1;
fn add(self, q: &Precomp) -> PointP1P1
{
let mut rx;
let mut ry;
let mut rz;
let mut rt;
rx = &self.y + &self.x;
ry = &self.y - &self.x;
rz = &rx * &q.yplusx;
ry *= &q.yminusx;
rt = &q.xy2d * &self.t;
let t0 = &self.z + &self.z;
rx = &rz - &ry;
ry += &rz;
rz = &t0 + &rt;
rt = &t0 - &rt;
PointP1P1 { x: rx, y: ry, z: rz, t: rt }
}
}
impl<'a,'b> Sub<&'a Precomp> for &'b Point
{
type Output = PointP1P1;
/* r = p - q */
fn sub(self, q: &Precomp) -> PointP1P1
{
let mut rx = &self.y + &self.x;
let mut ry = &self.y - &self.x;
let mut rz = &rx * &q.yminusx;
ry *= &q.yplusx;
let mut rt = &q.xy2d * &self.t;
let t0 = &self.z + &self.z;
rx = &rz - &ry;
ry += &rz;
rz = &t0 - &rt;
rt += &t0;
PointP1P1{ x: rx, y: ry, z: rz, t: rt }
}
}
#[cfg(test)]
#[test]
fn maddsub() {
let fname = "testdata/ed25519/maddsub.test";
run_test(fname.to_string(), 4, |case| {
let (nega, abytes) = case.get("a").unwrap();
let (negb, bbytes) = case.get("b").unwrap();
let (negc, cbytes) = case.get("c").unwrap();
let (negd, dbytes) = case.get("d").unwrap();
assert!(!nega && !negb && !negc && !negd);
let a = Point::load_test_value(abytes);
let b = PointP1P1::load_test_value(bbytes);
let c = Precomp::load_test_value(cbytes);
let d = PointP1P1::load_test_value(dbytes);
let myb = &a + &c;
assert_eq!(myb, b);
let myd = &a - &c;
assert_eq!(myd, d);
});
}
impl<'a,'b> Add<&'a Cached> for &'b Point
{
type Output = PointP1P1;
fn add(self, q: &Cached) -> PointP1P1
{
let mut rx;
let mut ry;
let mut rz;
let mut rt;
rx = &self.y + &self.x;
ry = &self.y - &self.x;
rz = &rx * &q.yplusx;
ry *= &q.yminusx;
rt = &q.t2d * &self.t;
rx = &self.z * &q.z;
let t0 = &rx + ℞
rx = &rz - &ry;
ry += &rz;
rz = &t0 + &rt;
rt = &t0 - &rt;
PointP1P1{ x: rx, y: ry, z: rz, t: rt }
}
}
impl<'a,'b> Sub<&'a Cached> for &'b Point
{
type Output = PointP1P1;
fn sub(self, q: &Cached) -> PointP1P1
{
let mut rx;
let mut ry;
let mut rz;
let mut rt;
rx = &self.y + &self.x;
ry = &self.y - &self.x;
rz = &rx * &q.yminusx;
ry *= &q.yplusx;
rt = &q.t2d * &self.t;
rx = &self.z * &q.z;
let t0 = &rx + ℞
rx = &rz - &ry;
ry += &rz;
rz = &t0 - &rt;
rt += &t0;
PointP1P1{ x: rx, y: ry, z: rz, t: rt }
}
}
#[cfg(test)]
#[test]
fn addsub() {
let fname = "testdata/ed25519/ptaddsub.test";
run_test(fname.to_string(), 4, |case| {
let (nega, abytes) = case.get("a").unwrap();
let (negb, bbytes) = case.get("b").unwrap();
let (negc, cbytes) = case.get("c").unwrap();
let (negd, dbytes) = case.get("d").unwrap();
assert!(!nega && !negb && !negc && !negd);
let a = Point::load_test_value(abytes);
let b = PointP1P1::load_test_value(bbytes);
let c = Cached::load_test_value(cbytes);
let d = PointP1P1::load_test_value(dbytes);
let myb = &a + &c;
assert_eq!(myb, b);
let myd = &a - &c;
assert_eq!(myd, d);
});
}
impl Point {
/* h = a * B
* where a = a[0]+256*a[1]+...+256^31 a[31]
* B is the Ed25519 base point (x,4/5) with x positive.
*
* Preconditions:
* a[31] <= 127 */
pub fn scalarmult_base(a: &[u8]) -> Point
{
let mut e: [i8; 64] = [0; 64];
for i in 0..32 {
e[2 * i + 0] = ((a[i] >> 0) & 15) as i8;
e[2 * i + 1] = ((a[i] >> 4) & 15) as i8;
}
/* each e[i] is between 0 and 15 */
/* e[63] is between 0 and 7 */
let mut carry = 0;
for i in 0..63 {
e[i] += carry;
carry = e[i] + 8;
carry >>= 4;
e[i] -= carry << 4;
}
e[63] += carry;
/* each e[i] is between -8 and 8 */
let mut r;
let mut t;
let mut h = Point::zero();
for i in &[1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63] {
t = Precomp::table_select(*i / 2, e[*i as usize]);
r = &h + &t;
h = Point::from(&r);
}
r = h.double();
let mut s = Point2::from(&r);
r = s.double();
s = Point2::from(&r);
r = s.double();
s = Point2::from(&r);
r = s.double();
h = Point::from(&r);
for i in &[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62] {
t = Precomp::table_select(*i / 2, e[*i as usize]);
r = &h + &t;
h = Point::from(&r);
}
h
}
}
#[cfg(test)]
#[test]
fn scalarmult_base() {
let fname = "testdata/ed25519/scalar_mult.test";
run_test(fname.to_string(), 2, |case| {
let (nega, abytes) = case.get("a").unwrap();
let (negb, bbytes) = case.get("b").unwrap();
assert!(!nega && !negb);
let b = Point::load_test_value(bbytes);
let mine = Point::scalarmult_base(&abytes);
assert_eq!(mine, b);
});
}
fn slide(r: &mut [i8], a: &[u8])
{
for i in 0..256 {
r[i] = (1 & (a[i >> 3] >> (i & 7))) as i8;
}
for i in 0..256 {
if r[i] != 0 {
let mut b = 1;
while (b <= 6) && ((i + b) < 256) {
if r[i + b] != 0 {
if r[i] + (r[i + b] << b) <= 15 {
r[i] += r[i + b] << b;
r[i + b] = 0;
} else if r[i] - (r[i + b] << b) >= -15 {
r[i] -= r[i + b] << b;
for k in (i+b)..256 {
if r[k] == 0 {
r[k] = 1;
break;
}
r[k] = 0;
}
} else {
break;
}
}
b += 1;
}
}
}
}
#[cfg(test)]
#[test]
fn helper_slide() {
let fname = "testdata/ed25519/slide.test";
run_test(fname.to_string(), 2, |case| {
let (nega, abytes) = case.get("a").unwrap();
let (negb, bbytes) = case.get("b").unwrap();
assert!(!nega && !negb);
let mut mine = [0; 256];
slide(&mut mine, &abytes);
for i in 0..256 {
assert_eq!(mine[i], bbytes[i] as i8);
}
});
}
impl Point2
{
/* r = a * A + b * B
* where a = a[0]+256*a[1]+...+256^31 a[31].
* and b = b[0]+256*b[1]+...+256^31 b[31].
* B is the Ed25519 base point (x,4/5) with x positive. */
#[allow(non_snake_case)]
pub fn double_scalarmult_vartime(a: &[u8], A: &Point, b: &[u8]) -> Point2
{
let mut aslide: [i8; 256] = [0; 256];
let mut bslide: [i8; 256] = [0; 256];
#[allow(non_snake_case)]
let mut Ai: [Cached; 8] = [Cached::new(), Cached::new(), Cached::new(), Cached::new(),
Cached::new(), Cached::new(), Cached::new(), Cached::new()];
#[allow(non_snake_case)]
slide(&mut aslide, &a);
slide(&mut bslide, &b);
Ai[0] = Cached::from(A);
let mut t = A.double();
let A2 = Point::from(&t);
t = &A2 + &Ai[0];
let mut u = Point::from(&t);
Ai[1] = Cached::from(&u);
t = &A2 + &Ai[1];
u = Point::from(&t);
Ai[2] = Cached::from(&u);
t = &A2 + &Ai[2];
u = Point::from(&t);
Ai[3] = Cached::from(&u);
t = &A2 + &Ai[3];
u = Point::from(&t);
Ai[4] = Cached::from(&u);
t = &A2 + &Ai[4];
u = Point::from(&t);
Ai[5] = Cached::from(&u);
t = &A2 + &Ai[5];
u = Point::from(&t);
Ai[6] = Cached::from(&u);
t = &A2 + &Ai[6];
u = Point::from(&t);
Ai[7] = Cached::from(&u);
let mut r = Point2::zero();
let mut i: i32 = 255;
loop {
if (aslide[i as usize] != 0) || (bslide[i as usize] != 0) {
break;
}
i -= 1;
if i < 0 {
break;
}
}
while i >= 0 {
t = r.double();
if aslide[i as usize] > 0 {
u = Point::from(&t);
let idx = (aslide[i as usize] / 2) as usize;
t = &u + &Ai[idx]
} else if aslide[i as usize] < 0 {
u = Point::from(&t);
let idx = ((-aslide[i as usize]) / 2) as usize;
t = &u - &Ai[idx];
}
if bslide[i as usize] > 0 {
u = Point::from(&t);
let idx = (bslide[i as usize] / 2) as usize;
t = &u + &BI[idx];
} else if bslide[i as usize] < 0 {
u = Point::from(&t);
let idx = ((-bslide[i as usize]) / 2) as usize;
t = &u - &BI[idx];
}
r = Point2::from(&t);
i -= 1;
}
r
}
}
#[cfg(test)]
#[test]
fn double_scalarmult() {
let fname = "testdata/ed25519/scalar_mult_gen.test";
run_test(fname.to_string(), 4, |case| {
let (nega, abytes) = case.get("a").unwrap();
let (negb, bbytes) = case.get("b").unwrap();
let (negc, cbytes) = case.get("c").unwrap();
let (negd, dbytes) = case.get("d").unwrap();
assert!(!nega && !negb && !negc && !negd);
let b = Point::load_test_value(bbytes);
let d = Point2::load_test_value(dbytes);
let mine = Point2::double_scalarmult_vartime(&abytes, &b, &cbytes);
assert_eq!(mine, d);
});
}
fn into_encoded_point(x: &FieldElement, y: &FieldElement, z: &FieldElement) -> Vec<u8>
{
let recip = z.invert();
let x_over_z = x * &recip;
let y_over_z = y * &recip;
let mut bytes = y_over_z.to_bytes();
let sign_bit = if x_over_z.isnegative() { 1 } else { 0 };
// The preceding computations must execute in constant time, but this
// doesn't need to.
bytes[31] ^= sign_bit << 7;
bytes
}
| 26 | 110 | 0.449224 |
4a0a8ffee17559df66ace8555825041697676f3e | 6,671 | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
//! Monitor a process.
//!
//! This module only supports **Linux** platform.
use std::sync::Mutex;
use lazy_static::lazy_static;
use crate::counter::Counter;
use crate::desc::Desc;
use crate::gauge::Gauge;
use crate::metrics::{Collector, Opts};
use crate::proto;
/// The `pid_t` data type represents process IDs.
pub use libc::pid_t;
/// Seven metrics per ProcessCollector.
const METRICS_NUMBER: usize = 7;
/// A collector which exports the current state of process metrics including
/// CPU, memory and file descriptor usage, thread count, as well as the process
/// start time for the given process id.
#[derive(Debug)]
pub struct ProcessCollector {
pid: pid_t,
descs: Vec<Desc>,
cpu_total: Mutex<Counter>,
open_fds: Gauge,
max_fds: Gauge,
vsize: Gauge,
rss: Gauge,
start_time: Gauge,
threads: Gauge,
}
impl ProcessCollector {
/// Create a `ProcessCollector` with the given process id and namespace.
pub fn new<S: Into<String>>(pid: pid_t, namespace: S) -> ProcessCollector {
let namespace = namespace.into();
let mut descs = Vec::new();
let cpu_total = Counter::with_opts(
Opts::new(
"process_cpu_seconds_total",
"Total user and system CPU time spent in \
seconds.",
)
.namespace(namespace.clone()),
)
.unwrap();
descs.extend(cpu_total.desc().into_iter().cloned());
let open_fds = Gauge::with_opts(
Opts::new("process_open_fds", "Number of open file descriptors.")
.namespace(namespace.clone()),
)
.unwrap();
descs.extend(open_fds.desc().into_iter().cloned());
let max_fds = Gauge::with_opts(
Opts::new(
"process_max_fds",
"Maximum number of open file descriptors.",
)
.namespace(namespace.clone()),
)
.unwrap();
descs.extend(max_fds.desc().into_iter().cloned());
let vsize = Gauge::with_opts(
Opts::new(
"process_virtual_memory_bytes",
"Virtual memory size in bytes.",
)
.namespace(namespace.clone()),
)
.unwrap();
descs.extend(vsize.desc().into_iter().cloned());
let rss = Gauge::with_opts(
Opts::new(
"process_resident_memory_bytes",
"Resident memory size in bytes.",
)
.namespace(namespace.clone()),
)
.unwrap();
descs.extend(rss.desc().into_iter().cloned());
let start_time = Gauge::with_opts(
Opts::new(
"process_start_time_seconds",
"Start time of the process since unix epoch \
in seconds.",
)
.namespace(namespace.clone()),
)
.unwrap();
descs.extend(start_time.desc().into_iter().cloned());
let threads = Gauge::with_opts(
Opts::new("process_threads", "Number of OS threads in the process.")
.namespace(namespace.clone()),
)
.unwrap();
descs.extend(threads.desc().into_iter().cloned());
ProcessCollector {
pid,
descs,
cpu_total: Mutex::new(cpu_total),
open_fds,
max_fds,
vsize,
rss,
start_time,
threads,
}
}
/// Return a `ProcessCollector` of the calling process.
pub fn for_self() -> ProcessCollector {
let pid = unsafe { libc::getpid() };
ProcessCollector::new(pid, "")
}
}
impl Collector for ProcessCollector {
fn desc(&self) -> Vec<&Desc> {
self.descs.iter().collect()
}
fn collect(&self) -> Vec<proto::MetricFamily> {
let p = match procfs::process::Process::new(self.pid) {
Ok(p) => p,
Err(..) => {
// we can't construct a Process object, so there's no stats to gather
return Vec::new();
}
};
// file descriptors
if let Ok(fd_count) = p.fd_count() {
self.open_fds.set(fd_count as f64);
}
if let Ok(limits) = p.limits() {
if let procfs::process::LimitValue::Value(max) = limits.max_open_files.soft_limit {
self.max_fds.set(max as f64)
}
}
// memory
self.vsize.set(p.stat.vsize as f64);
self.rss.set(p.stat.rss as f64 * *PAGESIZE);
// proc_start_time
if let Some(boot_time) = *BOOT_TIME {
self.start_time
.set(p.stat.starttime as f64 / *CLK_TCK + boot_time);
}
// cpu
let cpu_total_mfs = {
let cpu_total = self.cpu_total.lock().unwrap();
let total = (p.stat.utime + p.stat.stime) as f64 / *CLK_TCK;
let past = cpu_total.get();
let delta = total - past;
if delta > 0.0 {
cpu_total.inc_by(delta);
}
cpu_total.collect()
};
// threads
self.threads.set(p.stat.num_threads as f64);
// collect MetricFamilys.
let mut mfs = Vec::with_capacity(METRICS_NUMBER);
mfs.extend(cpu_total_mfs);
mfs.extend(self.open_fds.collect());
mfs.extend(self.max_fds.collect());
mfs.extend(self.vsize.collect());
mfs.extend(self.rss.collect());
mfs.extend(self.start_time.collect());
mfs.extend(self.threads.collect());
mfs
}
}
lazy_static! {
// getconf CLK_TCK
static ref CLK_TCK: f64 = {
unsafe {
libc::sysconf(libc::_SC_CLK_TCK) as f64
}
};
// getconf PAGESIZE
static ref PAGESIZE: f64 = {
unsafe {
libc::sysconf(libc::_SC_PAGESIZE) as f64
}
};
}
lazy_static! {
static ref BOOT_TIME: Option<f64> = procfs::boot_time_secs().ok().map(|i| i as f64);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::metrics::Collector;
use crate::registry;
#[test]
fn test_process_collector() {
let pc = ProcessCollector::for_self();
{
// Seven metrics per process collector.
let descs = pc.desc();
assert_eq!(descs.len(), super::METRICS_NUMBER);
let mfs = pc.collect();
assert_eq!(mfs.len(), super::METRICS_NUMBER);
}
let r = registry::Registry::new();
let res = r.register(Box::new(pc));
assert!(res.is_ok());
}
}
| 28.266949 | 95 | 0.542198 |
abed831350fc31f87c8aa946f4fa14ca6b6c8247 | 519 | use bdf_parser::BdfFont;
use bdf_to_mono::{bdf_to_bitmap, Encoding};
use std::{io::Write, str::FromStr};
fn main() {
let bdf_file = std::env::args().nth(1).expect("missing BDF file argument");
let bdf = std::fs::read_to_string(&bdf_file).expect("couldn't open BDF file");
let font = BdfFont::from_str(&bdf).expect("couldn't parse BDF file");
// TODO: make encoding configurable
let bitmap = bdf_to_bitmap(&font, Encoding::Ascii).unwrap();
std::io::stdout().write_all(&bitmap.data).unwrap()
}
| 34.6 | 82 | 0.680154 |
50ac84260f6b128ee8ed68cde257f8933b0ac743 | 902 | #![feature(test)]
extern crate chrono;
extern crate memento;
extern crate test;
use chrono::{TimeZone, Utc};
use memento::{FetchRequest, MementoFileReader};
use test::Bencher;
#[bench]
fn benchmark_memento_file_reader_read_header(b: &mut Bencher) {
let reader = MementoFileReader::new();
b.iter(|| reader.read_header("tests/upper_01.wsp"));
}
#[bench]
fn benchmark_memento_file_reader_read_database(b: &mut Bencher) {
let reader = MementoFileReader::new();
b.iter(|| reader.read_database("tests/upper_01.wsp"));
}
#[bench]
fn benchmark_memento_file_reader_read_range(b: &mut Bencher) {
let from = Utc.timestamp(1502089980, 0);
let until = Utc.timestamp(1502259660, 0);
let now = Utc.timestamp(1502864800, 0);
let request = FetchRequest::new(from, until, now);
let reader = MementoFileReader::new();
b.iter(|| reader.read("tests/upper_01.wsp", &request));
}
| 28.1875 | 65 | 0.711752 |
2200e90f2b72c0a675aea724425948895a7f077a | 9,128 | use makepad_render::*;
use crate::scrollbar::*;
use crate::scrollview::*;
use crate::tab::*;
use crate::widgetstyle::*;
#[derive(Clone)]
pub struct TabControl {
pub tabs_view: ScrollView,
pub tabs: Elements<usize, Tab, Tab>,
pub drag_tab_view: View,
pub drag_tab: Tab,
pub page_view: View,
pub hover: Quad,
//pub tab_fill_color: ColorId,
pub tab_fill: Quad,
pub animator: Animator,
pub _dragging_tab: Option<(FingerMoveEvent, usize)>,
pub _tab_id_alloc: usize,
pub _tab_now_selected: Option<usize>,
pub _tab_last_selected:Option<usize>,
pub _focussed: bool
}
#[derive(Clone, PartialEq)]
pub enum TabControlEvent {
None,
TabDragMove {fe: FingerMoveEvent, tab_id: usize},
TabDragEnd {fe: FingerUpEvent, tab_id: usize},
TabSelect {tab_id: usize},
TabClose {tab_id: usize}
}
impl TabControl {
pub fn new(cx: &mut Cx) -> Self {
Self {
tabs_view: ScrollView {
scroll_h: Some(ScrollBar {
bar_size: 8.0,
smoothing: Some(0.15),
use_vertical_finger_scroll: true,
..ScrollBar::new(cx)
}),
..ScrollView::new(cx)
},
page_view: View::new(cx),
tabs: Elements::new(Tab::new(cx)),
drag_tab: Tab {
z: 10.,
..Tab::new(cx)
},
drag_tab_view: View {
is_overlay: true,
..View::new(cx)
},
hover: Quad {
color: pick!(purple).get(cx),
..Quad::new(cx)
},
//tab_fill_color: Color_bg_normal::id(),
tab_fill: Quad::new(cx),
animator: Animator::default(),
_dragging_tab: None,
_tab_now_selected:None,
_tab_last_selected:None,
_focussed: false,
_tab_id_alloc: 0
}
}
pub fn handle_tab_control(&mut self, cx: &mut Cx, event: &mut Event) -> TabControlEvent {
let mut tab_control_event = TabControlEvent::None;
self.tabs_view.handle_scroll_view(cx, event);
for (id, tab) in self.tabs.enumerate() {
match tab.handle_tab(cx, event) {
TabEvent::Select => {
self.page_view.redraw_view_area(cx);
// deselect the other tabs
tab_control_event = TabControlEvent::TabSelect {tab_id: *id}
},
TabEvent::DragMove(fe) => {
self._dragging_tab = Some((fe.clone(), *id));
// flag our view as dirty, to trigger
//cx.redraw_child_area(Area::All);
self.tabs_view.redraw_view_area(cx);
self.drag_tab_view.redraw_view_area(cx);
tab_control_event = TabControlEvent::TabDragMove {fe: fe, tab_id: *id};
},
TabEvent::DragEnd(fe) => {
self._dragging_tab = None;
self.drag_tab_view.redraw_view_area(cx);
tab_control_event = TabControlEvent::TabDragEnd {fe, tab_id: *id};
},
TabEvent::Closing => { // this tab is closing. select the visible one
if tab._is_selected { // only do anything if we are selected
let next_sel = if *id == self._tab_id_alloc - 1 { // last id
if *id > 0 {
*id - 1
}
else {
*id
}
}
else {
*id + 1
};
if *id != next_sel {
tab_control_event = TabControlEvent::TabSelect {tab_id: next_sel};
}
}
},
TabEvent::Close => {
// Sooooo someone wants to close the tab
tab_control_event = TabControlEvent::TabClose {tab_id: *id};
},
_ => ()
}
};
match tab_control_event {
TabControlEvent::TabSelect {tab_id} => {
self._focussed = true;
for (id, tab) in self.tabs.enumerate() {
if tab_id != *id {
tab.set_tab_selected(cx, false);
tab.set_tab_focus(cx, true);
}
}
},
TabControlEvent::TabClose {..} => { // needed to clear animation state
self.tabs.clear(cx, | _, _ | ());
},
_ => ()
};
tab_control_event
}
pub fn tab_control_style()->StyleId{uid!()}
pub fn style(cx:&mut Cx, opt:&StyleOptions){
cx.begin_style(Self::tab_control_style());
ScrollBar::bar_size().set(cx, 8. * opt.scale.powf(0.5));
cx.end_style();
}
pub fn get_tab_rects(&mut self, cx: &Cx) -> Vec<Rect> {
let mut rects = Vec::new();
for tab in self.tabs.iter() {
rects.push(tab.get_tab_rect(cx))
}
return rects
}
pub fn set_tab_control_focus(&mut self, cx: &mut Cx, focus: bool) {
self._focussed = focus;
for tab in self.tabs.iter() {
tab.set_tab_focus(cx, focus);
}
}
pub fn get_tabs_view_rect(&mut self, cx: &Cx) -> Rect {
self.tabs_view.get_rect(cx)
}
pub fn get_content_drop_rect(&mut self, cx: &Cx) -> Rect {
let pr = self.page_view.get_rect(cx);
// we now need to change the y and the new height
Rect {
x: pr.x,
y: pr.y,
w: pr.w,
h: pr.h
}
}
// data free APIs for the win!
pub fn begin_tabs(&mut self, cx: &mut Cx) -> ViewRedraw {
//cx.begin_turtle(&Layout{
if let Err(_) = self.tabs_view.begin_view(cx, Layout {
walk:Walk::wh(Width::Fill, Height::Compute),
..Layout::default()
}) {
return Err(())
}
self._tab_now_selected = None;
self._tab_id_alloc = 0;
Ok(())
}
pub fn get_draw_tab(&mut self, cx: &mut Cx, label: &str, selected: bool, closeable: bool)->&mut Tab{
let new_tab = self.tabs.get(self._tab_id_alloc).is_none();
let tab = self.tabs.get_draw(cx, self._tab_id_alloc, | _cx, tmpl | tmpl.clone());
if selected{
self._tab_now_selected = Some(self._tab_id_alloc);
}
self._tab_id_alloc += 1;
tab.label = label.to_string();
tab.is_closeable = closeable;
if new_tab {
tab.set_tab_state(cx, selected, self._focussed);
}
else { // animate the tabstate
tab.set_tab_selected(cx, selected);
}
tab
}
pub fn draw_tab(&mut self, cx: &mut Cx, label: &str, selected: bool, closeable: bool) {
let tab = self.get_draw_tab(cx, label, selected, closeable);
tab.draw_tab(cx);
}
pub fn end_tabs(&mut self, cx: &mut Cx) {
self.tab_fill.color = Theme::color_bg_normal().get(cx);
self.tab_fill.draw_quad(cx, Walk::wh(Width::Fill, Height::Fill));
self.tabs.sweep(cx, | _, _ | ());
if let Some((fe, id)) = &self._dragging_tab {
if let Ok(()) = self.drag_tab_view.begin_view(cx, Layout::abs_origin_zero()) {
self.drag_tab.abs_origin = Some(Vec2 {x: fe.abs.x - fe.rel_start.x, y: fe.abs.y - fe.rel_start.y});
let origin_tab = self.tabs.get_draw(cx, *id, | _cx, tmpl | tmpl.clone());
self.drag_tab.label = origin_tab.label.clone();
self.drag_tab.is_closeable = origin_tab.is_closeable;
self.drag_tab.draw_tab(cx);
self.drag_tab_view.end_view(cx);
}
}
cx.begin_style(Self::tab_control_style());
self.tabs_view.end_view(cx);
cx.end_style();
if self._tab_now_selected != self._tab_last_selected{
// lets scroll the thing into view
if let Some(tab_id) = self._tab_now_selected{
if let Some(tab) = self.tabs.get(tab_id){
let tab_rect = tab._bg_area.get_rect(cx);
self.tabs_view.scroll_into_view_abs(cx, tab_rect);
}
}
self._tab_last_selected = self._tab_now_selected;
}
}
pub fn begin_tab_page(&mut self, cx: &mut Cx) -> ViewRedraw {
cx.turtle_new_line();
self.page_view.begin_view(cx, Layout::default())
}
pub fn end_tab_page(&mut self, cx: &mut Cx) {
self.page_view.end_view(cx);
//cx.end_turtle(Area::Empty);
// if we are in draggable tab state,
// draw our draggable tab
}
}
| 34.97318 | 115 | 0.498138 |
1ccecb85265d3ba78f2cf7b39a109712d4d3d355 | 3,275 | use super::{connectors, errors, settings};
use base64;
use std::collections::HashMap;
pub struct AccessChecker {
sa: HashMap<String, String>,
cba: HashMap<String, String>,
cba_common: Option<String>,
}
impl AccessChecker {
pub fn get_basic_authorization_token(user: &String, password: &String) -> String {
format!(
"Basic {}",
base64::encode(&format!("{}:{}", user, password))
)
}
pub fn get_client_basic_authorization_token(
&self,
service_name: &String,
) -> connectors::Result<String> {
if self.cba.contains_key(service_name) {
Ok(self.cba.get(service_name).unwrap().clone())
} else if self.cba_common.is_some() {
Ok(self.cba_common.as_ref().unwrap().clone())
} else {
return Err(errors::UnknownServiceNameError.into());
}
}
pub async fn _from_app_settings(
access: &settings::Access,
) -> connectors::Result<AccessChecker> {
let mut sa: HashMap<String, String> = HashMap::new();
for item in &access.authentication.server {
sa.insert(
AccessChecker::get_basic_authorization_token(&item.0, &item.1),
item.0.to_string(),
);
}
debug!("{} server users", sa.len());
let mut cba: HashMap<String, String> = HashMap::new();
let mut cba_common = None;
for item in &access.authentication.client {
let token =
AccessChecker::get_basic_authorization_token(&item.usr_name, &item.usr_password);
if item.service_name == "*" {
cba_common = Some(token.clone());
}
cba.insert(token, item.service_name.to_string());
}
debug!("{} client users", cba.len());
Ok(AccessChecker {
sa: sa,
cba: cba,
cba_common: cba_common,
})
}
pub async fn from_data_connector(
dc: &connectors::DataConnector,
authentication: &settings::Authentication,
) -> connectors::Result<AccessChecker> {
let items = dc.usr.get(None).await?;
let mut server_authorization: HashMap<String, String> = HashMap::new();
for item in items {
server_authorization.insert(
AccessChecker::get_basic_authorization_token(&item.usr_name, &item.usr_password),
item.usr_name,
);
}
debug!("{} server users", server_authorization.len());
let mut cba: HashMap<String, String> = HashMap::new();
let mut cba_common = None;
for item in &authentication.client {
let token =
AccessChecker::get_basic_authorization_token(&item.usr_name, &item.usr_password);
if item.service_name == "*" {
cba_common = Some(token.clone());
}
cba.insert(token, item.service_name.to_string());
}
debug!("{} client users", cba.len());
Ok(AccessChecker {
sa: server_authorization,
cba: cba,
cba_common: cba_common,
})
}
pub fn is_authorized_by_header(&self, header: &str) -> bool {
*&self.sa.contains_key(header)
}
}
| 34.114583 | 97 | 0.566718 |
feaeb70c3bb5c5a9cc82499bd9524ea9d40a0d04 | 194 | use super::schema_type;
rpc_enum! {
SchemaType,
schema_type::Type,
schema_type,
"schema type",
"schema_type_enum",
[
DocumentStorage,
Timeseries
]
}
| 13.857143 | 24 | 0.587629 |
21e405ac0af447e997e802877c228289809787fe | 255,385 | #![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use super::{models, API_VERSION};
#[derive(Clone)]
pub struct Client {
endpoint: String,
credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>,
scopes: Vec<String>,
pipeline: azure_core::Pipeline,
}
#[derive(Clone)]
pub struct ClientBuilder {
credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>,
endpoint: Option<String>,
scopes: Option<Vec<String>>,
}
pub const DEFAULT_ENDPOINT: &str = azure_core::resource_manager_endpoint::AZURE_PUBLIC_CLOUD;
impl ClientBuilder {
pub fn new(credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>) -> Self {
Self {
credential,
endpoint: None,
scopes: None,
}
}
pub fn endpoint(mut self, endpoint: impl Into<String>) -> Self {
self.endpoint = Some(endpoint.into());
self
}
pub fn scopes(mut self, scopes: &[&str]) -> Self {
self.scopes = Some(scopes.iter().map(|scope| (*scope).to_owned()).collect());
self
}
pub fn build(self) -> Client {
let endpoint = self.endpoint.unwrap_or_else(|| DEFAULT_ENDPOINT.to_owned());
let scopes = self.scopes.unwrap_or_else(|| vec![format!("{}/", endpoint)]);
Client::new(endpoint, self.credential, scopes)
}
}
impl Client {
pub(crate) fn endpoint(&self) -> &str {
self.endpoint.as_str()
}
pub(crate) fn token_credential(&self) -> &dyn azure_core::auth::TokenCredential {
self.credential.as_ref()
}
pub(crate) fn scopes(&self) -> Vec<&str> {
self.scopes.iter().map(String::as_str).collect()
}
pub(crate) async fn send(&self, request: impl Into<azure_core::Request>) -> Result<azure_core::Response, azure_core::Error> {
let mut context = azure_core::Context::default();
let mut request = request.into();
self.pipeline.send(&mut context, &mut request).await
}
pub fn new(
endpoint: impl Into<String>,
credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>,
scopes: Vec<String>,
) -> Self {
let endpoint = endpoint.into();
let pipeline = azure_core::Pipeline::new(
option_env!("CARGO_PKG_NAME"),
option_env!("CARGO_PKG_VERSION"),
azure_core::ClientOptions::default(),
Vec::new(),
Vec::new(),
);
Self {
endpoint,
credential,
scopes,
pipeline,
}
}
pub fn clusters(&self) -> clusters::Client {
clusters::Client(self.clone())
}
pub fn functions(&self) -> functions::Client {
functions::Client(self.clone())
}
pub fn inputs(&self) -> inputs::Client {
inputs::Client(self.clone())
}
pub fn operations(&self) -> operations::Client {
operations::Client(self.clone())
}
pub fn outputs(&self) -> outputs::Client {
outputs::Client(self.clone())
}
pub fn private_endpoints(&self) -> private_endpoints::Client {
private_endpoints::Client(self.clone())
}
pub fn streaming_jobs(&self) -> streaming_jobs::Client {
streaming_jobs::Client(self.clone())
}
pub fn subscriptions(&self) -> subscriptions::Client {
subscriptions::Client(self.clone())
}
pub fn transformations(&self) -> transformations::Client {
transformations::Client(self.clone())
}
}
#[non_exhaustive]
#[derive(Debug, thiserror :: Error)]
#[allow(non_camel_case_types)]
pub enum Error {
#[error(transparent)]
Functions_Get(#[from] functions::get::Error),
#[error(transparent)]
Functions_CreateOrReplace(#[from] functions::create_or_replace::Error),
#[error(transparent)]
Functions_Update(#[from] functions::update::Error),
#[error(transparent)]
Functions_Delete(#[from] functions::delete::Error),
#[error(transparent)]
Functions_ListByStreamingJob(#[from] functions::list_by_streaming_job::Error),
#[error(transparent)]
Functions_Test(#[from] functions::test::Error),
#[error(transparent)]
Functions_RetrieveDefaultDefinition(#[from] functions::retrieve_default_definition::Error),
#[error(transparent)]
Inputs_Get(#[from] inputs::get::Error),
#[error(transparent)]
Inputs_CreateOrReplace(#[from] inputs::create_or_replace::Error),
#[error(transparent)]
Inputs_Update(#[from] inputs::update::Error),
#[error(transparent)]
Inputs_Delete(#[from] inputs::delete::Error),
#[error(transparent)]
Inputs_ListByStreamingJob(#[from] inputs::list_by_streaming_job::Error),
#[error(transparent)]
Inputs_Test(#[from] inputs::test::Error),
#[error(transparent)]
Outputs_Get(#[from] outputs::get::Error),
#[error(transparent)]
Outputs_CreateOrReplace(#[from] outputs::create_or_replace::Error),
#[error(transparent)]
Outputs_Update(#[from] outputs::update::Error),
#[error(transparent)]
Outputs_Delete(#[from] outputs::delete::Error),
#[error(transparent)]
Outputs_ListByStreamingJob(#[from] outputs::list_by_streaming_job::Error),
#[error(transparent)]
Outputs_Test(#[from] outputs::test::Error),
#[error(transparent)]
StreamingJobs_Get(#[from] streaming_jobs::get::Error),
#[error(transparent)]
StreamingJobs_CreateOrReplace(#[from] streaming_jobs::create_or_replace::Error),
#[error(transparent)]
StreamingJobs_Update(#[from] streaming_jobs::update::Error),
#[error(transparent)]
StreamingJobs_Delete(#[from] streaming_jobs::delete::Error),
#[error(transparent)]
StreamingJobs_ListByResourceGroup(#[from] streaming_jobs::list_by_resource_group::Error),
#[error(transparent)]
StreamingJobs_List(#[from] streaming_jobs::list::Error),
#[error(transparent)]
StreamingJobs_Start(#[from] streaming_jobs::start::Error),
#[error(transparent)]
StreamingJobs_Stop(#[from] streaming_jobs::stop::Error),
#[error(transparent)]
Transformations_Get(#[from] transformations::get::Error),
#[error(transparent)]
Transformations_CreateOrReplace(#[from] transformations::create_or_replace::Error),
#[error(transparent)]
Transformations_Update(#[from] transformations::update::Error),
#[error(transparent)]
Subscriptions_ListQuotas(#[from] subscriptions::list_quotas::Error),
#[error(transparent)]
Subscriptions_TestQuery(#[from] subscriptions::test_query::Error),
#[error(transparent)]
Subscriptions_CompileQuery(#[from] subscriptions::compile_query::Error),
#[error(transparent)]
Subscriptions_SampleInput(#[from] subscriptions::sample_input::Error),
#[error(transparent)]
Subscriptions_TestInput(#[from] subscriptions::test_input::Error),
#[error(transparent)]
Subscriptions_TestOutput(#[from] subscriptions::test_output::Error),
#[error(transparent)]
Operations_List(#[from] operations::list::Error),
#[error(transparent)]
Clusters_Get(#[from] clusters::get::Error),
#[error(transparent)]
Clusters_CreateOrUpdate(#[from] clusters::create_or_update::Error),
#[error(transparent)]
Clusters_Update(#[from] clusters::update::Error),
#[error(transparent)]
Clusters_Delete(#[from] clusters::delete::Error),
#[error(transparent)]
Clusters_ListBySubscription(#[from] clusters::list_by_subscription::Error),
#[error(transparent)]
Clusters_ListByResourceGroup(#[from] clusters::list_by_resource_group::Error),
#[error(transparent)]
Clusters_ListStreamingJobs(#[from] clusters::list_streaming_jobs::Error),
#[error(transparent)]
PrivateEndpoints_Get(#[from] private_endpoints::get::Error),
#[error(transparent)]
PrivateEndpoints_CreateOrUpdate(#[from] private_endpoints::create_or_update::Error),
#[error(transparent)]
PrivateEndpoints_Delete(#[from] private_endpoints::delete::Error),
#[error(transparent)]
PrivateEndpoints_ListByCluster(#[from] private_endpoints::list_by_cluster::Error),
}
pub mod functions {
use super::{models, API_VERSION};
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn get(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
function_name: impl Into<String>,
) -> get::Builder {
get::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
function_name: function_name.into(),
}
}
pub fn create_or_replace(
&self,
function: impl Into<models::Function>,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
function_name: impl Into<String>,
) -> create_or_replace::Builder {
create_or_replace::Builder {
client: self.0.clone(),
function: function.into(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
function_name: function_name.into(),
if_match: None,
if_none_match: None,
}
}
pub fn update(
&self,
function: impl Into<models::Function>,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
function_name: impl Into<String>,
) -> update::Builder {
update::Builder {
client: self.0.clone(),
function: function.into(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
function_name: function_name.into(),
if_match: None,
}
}
pub fn delete(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
function_name: impl Into<String>,
) -> delete::Builder {
delete::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
function_name: function_name.into(),
}
}
pub fn list_by_streaming_job(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
) -> list_by_streaming_job::Builder {
list_by_streaming_job::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
select: None,
}
}
pub fn test(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
function_name: impl Into<String>,
) -> test::Builder {
test::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
function_name: function_name.into(),
function: None,
}
}
pub fn retrieve_default_definition(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
function_name: impl Into<String>,
) -> retrieve_default_definition::Builder {
retrieve_default_definition::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
function_name: function_name.into(),
function_retrieve_default_definition_parameters: None,
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) function_name: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Function, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/functions/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name,
&self.function_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Function =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod create_or_replace {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::Function),
Created201(models::Function),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) function: models::Function,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) function_name: String,
pub(crate) if_match: Option<String>,
pub(crate) if_none_match: Option<String>,
}
impl Builder {
pub fn if_match(mut self, if_match: impl Into<String>) -> Self {
self.if_match = Some(if_match.into());
self
}
pub fn if_none_match(mut self, if_none_match: impl Into<String>) -> Self {
self.if_none_match = Some(if_none_match.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/functions/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name,
&self.function_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.function).map_err(Error::Serialize)?;
if let Some(if_match) = &self.if_match {
req_builder = req_builder.header("If-Match", if_match);
}
if let Some(if_none_match) = &self.if_none_match {
req_builder = req_builder.header("If-None-Match", if_none_match);
}
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Function =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::CREATED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Function =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Created201(rsp_value))
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod update {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) function: models::Function,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) function_name: String,
pub(crate) if_match: Option<String>,
}
impl Builder {
pub fn if_match(mut self, if_match: impl Into<String>) -> Self {
self.if_match = Some(if_match.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Function, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/functions/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name,
&self.function_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PATCH);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.function).map_err(Error::Serialize)?;
if let Some(if_match) = &self.if_match {
req_builder = req_builder.header("If-Match", if_match);
}
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Function =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod delete {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) function_name: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/functions/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name,
&self.function_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::DELETE);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => Ok(Response::Ok200),
http::StatusCode::NO_CONTENT => Ok(Response::NoContent204),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod list_by_streaming_job {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) select: Option<String>,
}
impl Builder {
pub fn select(mut self, select: impl Into<String>) -> Self {
self.select = Some(select.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::FunctionListResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/functions",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(select) = &self.select {
url.query_pairs_mut().append_pair("$select", select);
}
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::FunctionListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod test {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::ResourceTestStatus),
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) function_name: String,
pub(crate) function: Option<models::Function>,
}
impl Builder {
pub fn function(mut self, function: impl Into<models::Function>) -> Self {
self.function = Some(function.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/functions/{}/test",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name,
&self.function_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = if let Some(function) = &self.function {
req_builder = req_builder.header("content-type", "application/json");
azure_core::to_json(function).map_err(Error::Serialize)?
} else {
azure_core::EMPTY_BODY
};
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ResourceTestStatus =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod retrieve_default_definition {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) function_name: String,
pub(crate) function_retrieve_default_definition_parameters: Option<models::FunctionRetrieveDefaultDefinitionParameters>,
}
impl Builder {
pub fn function_retrieve_default_definition_parameters(
mut self,
function_retrieve_default_definition_parameters: impl Into<models::FunctionRetrieveDefaultDefinitionParameters>,
) -> Self {
self.function_retrieve_default_definition_parameters = Some(function_retrieve_default_definition_parameters.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Function, Error>> {
Box::pin(async move {
let url_str = & format ! ("{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/functions/{}/retrieveDefaultDefinition" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . job_name , & self . function_name) ;
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = if let Some(function_retrieve_default_definition_parameters) =
&self.function_retrieve_default_definition_parameters
{
req_builder = req_builder.header("content-type", "application/json");
azure_core::to_json(function_retrieve_default_definition_parameters).map_err(Error::Serialize)?
} else {
azure_core::EMPTY_BODY
};
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Function =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
}
pub mod inputs {
use super::{models, API_VERSION};
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn get(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
input_name: impl Into<String>,
) -> get::Builder {
get::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
input_name: input_name.into(),
}
}
pub fn create_or_replace(
&self,
input: impl Into<models::Input>,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
input_name: impl Into<String>,
) -> create_or_replace::Builder {
create_or_replace::Builder {
client: self.0.clone(),
input: input.into(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
input_name: input_name.into(),
if_match: None,
if_none_match: None,
}
}
pub fn update(
&self,
input: impl Into<models::Input>,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
input_name: impl Into<String>,
) -> update::Builder {
update::Builder {
client: self.0.clone(),
input: input.into(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
input_name: input_name.into(),
if_match: None,
}
}
pub fn delete(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
input_name: impl Into<String>,
) -> delete::Builder {
delete::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
input_name: input_name.into(),
}
}
pub fn list_by_streaming_job(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
) -> list_by_streaming_job::Builder {
list_by_streaming_job::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
select: None,
}
}
pub fn test(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
input_name: impl Into<String>,
) -> test::Builder {
test::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
input_name: input_name.into(),
input: None,
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) input_name: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Input, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/inputs/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name,
&self.input_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Input =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod create_or_replace {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::Input),
Created201(models::Input),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) input: models::Input,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) input_name: String,
pub(crate) if_match: Option<String>,
pub(crate) if_none_match: Option<String>,
}
impl Builder {
pub fn if_match(mut self, if_match: impl Into<String>) -> Self {
self.if_match = Some(if_match.into());
self
}
pub fn if_none_match(mut self, if_none_match: impl Into<String>) -> Self {
self.if_none_match = Some(if_none_match.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/inputs/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name,
&self.input_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.input).map_err(Error::Serialize)?;
if let Some(if_match) = &self.if_match {
req_builder = req_builder.header("If-Match", if_match);
}
if let Some(if_none_match) = &self.if_none_match {
req_builder = req_builder.header("If-None-Match", if_none_match);
}
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Input =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::CREATED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Input =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Created201(rsp_value))
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod update {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) input: models::Input,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) input_name: String,
pub(crate) if_match: Option<String>,
}
impl Builder {
pub fn if_match(mut self, if_match: impl Into<String>) -> Self {
self.if_match = Some(if_match.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Input, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/inputs/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name,
&self.input_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PATCH);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.input).map_err(Error::Serialize)?;
if let Some(if_match) = &self.if_match {
req_builder = req_builder.header("If-Match", if_match);
}
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Input =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod delete {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) input_name: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/inputs/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name,
&self.input_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::DELETE);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => Ok(Response::Ok200),
http::StatusCode::NO_CONTENT => Ok(Response::NoContent204),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod list_by_streaming_job {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) select: Option<String>,
}
impl Builder {
pub fn select(mut self, select: impl Into<String>) -> Self {
self.select = Some(select.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::InputListResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/inputs",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(select) = &self.select {
url.query_pairs_mut().append_pair("$select", select);
}
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::InputListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod test {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::ResourceTestStatus),
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) input_name: String,
pub(crate) input: Option<models::Input>,
}
impl Builder {
pub fn input(mut self, input: impl Into<models::Input>) -> Self {
self.input = Some(input.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/inputs/{}/test",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name,
&self.input_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = if let Some(input) = &self.input {
req_builder = req_builder.header("content-type", "application/json");
azure_core::to_json(input).map_err(Error::Serialize)?
} else {
azure_core::EMPTY_BODY
};
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ResourceTestStatus =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
}
pub mod outputs {
use super::{models, API_VERSION};
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn get(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
output_name: impl Into<String>,
) -> get::Builder {
get::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
output_name: output_name.into(),
}
}
pub fn create_or_replace(
&self,
output: impl Into<models::Output>,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
output_name: impl Into<String>,
) -> create_or_replace::Builder {
create_or_replace::Builder {
client: self.0.clone(),
output: output.into(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
output_name: output_name.into(),
if_match: None,
if_none_match: None,
}
}
pub fn update(
&self,
output: impl Into<models::Output>,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
output_name: impl Into<String>,
) -> update::Builder {
update::Builder {
client: self.0.clone(),
output: output.into(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
output_name: output_name.into(),
if_match: None,
}
}
pub fn delete(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
output_name: impl Into<String>,
) -> delete::Builder {
delete::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
output_name: output_name.into(),
}
}
pub fn list_by_streaming_job(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
) -> list_by_streaming_job::Builder {
list_by_streaming_job::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
select: None,
}
}
pub fn test(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
output_name: impl Into<String>,
) -> test::Builder {
test::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
output_name: output_name.into(),
output: None,
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) output_name: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Output, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/outputs/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name,
&self.output_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Output =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod create_or_replace {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::Output),
Created201(models::Output),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) output: models::Output,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) output_name: String,
pub(crate) if_match: Option<String>,
pub(crate) if_none_match: Option<String>,
}
impl Builder {
pub fn if_match(mut self, if_match: impl Into<String>) -> Self {
self.if_match = Some(if_match.into());
self
}
pub fn if_none_match(mut self, if_none_match: impl Into<String>) -> Self {
self.if_none_match = Some(if_none_match.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/outputs/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name,
&self.output_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.output).map_err(Error::Serialize)?;
if let Some(if_match) = &self.if_match {
req_builder = req_builder.header("If-Match", if_match);
}
if let Some(if_none_match) = &self.if_none_match {
req_builder = req_builder.header("If-None-Match", if_none_match);
}
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Output =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::CREATED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Output =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Created201(rsp_value))
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod update {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) output: models::Output,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) output_name: String,
pub(crate) if_match: Option<String>,
}
impl Builder {
pub fn if_match(mut self, if_match: impl Into<String>) -> Self {
self.if_match = Some(if_match.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Output, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/outputs/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name,
&self.output_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PATCH);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.output).map_err(Error::Serialize)?;
if let Some(if_match) = &self.if_match {
req_builder = req_builder.header("If-Match", if_match);
}
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Output =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod delete {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) output_name: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/outputs/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name,
&self.output_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::DELETE);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => Ok(Response::Ok200),
http::StatusCode::NO_CONTENT => Ok(Response::NoContent204),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod list_by_streaming_job {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) select: Option<String>,
}
impl Builder {
pub fn select(mut self, select: impl Into<String>) -> Self {
self.select = Some(select.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::OutputListResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/outputs",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(select) = &self.select {
url.query_pairs_mut().append_pair("$select", select);
}
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::OutputListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod test {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::ResourceTestStatus),
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) output_name: String,
pub(crate) output: Option<models::Output>,
}
impl Builder {
pub fn output(mut self, output: impl Into<models::Output>) -> Self {
self.output = Some(output.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/outputs/{}/test",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name,
&self.output_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = if let Some(output) = &self.output {
req_builder = req_builder.header("content-type", "application/json");
azure_core::to_json(output).map_err(Error::Serialize)?
} else {
azure_core::EMPTY_BODY
};
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ResourceTestStatus =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
}
pub mod streaming_jobs {
use super::{models, API_VERSION};
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn get(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
) -> get::Builder {
get::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
expand: None,
}
}
pub fn create_or_replace(
&self,
streaming_job: impl Into<models::StreamingJob>,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
) -> create_or_replace::Builder {
create_or_replace::Builder {
client: self.0.clone(),
streaming_job: streaming_job.into(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
if_match: None,
if_none_match: None,
}
}
pub fn update(
&self,
streaming_job: impl Into<models::StreamingJob>,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
) -> update::Builder {
update::Builder {
client: self.0.clone(),
streaming_job: streaming_job.into(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
if_match: None,
}
}
pub fn delete(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
) -> delete::Builder {
delete::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
}
}
pub fn list_by_resource_group(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
) -> list_by_resource_group::Builder {
list_by_resource_group::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
expand: None,
}
}
pub fn list(&self, subscription_id: impl Into<String>) -> list::Builder {
list::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
expand: None,
}
}
pub fn start(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
) -> start::Builder {
start::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
start_job_parameters: None,
}
}
pub fn stop(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
) -> stop::Builder {
stop::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) expand: Option<String>,
}
impl Builder {
pub fn expand(mut self, expand: impl Into<String>) -> Self {
self.expand = Some(expand.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::StreamingJob, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(expand) = &self.expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::StreamingJob =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod create_or_replace {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::StreamingJob),
Created201(models::StreamingJob),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) streaming_job: models::StreamingJob,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) if_match: Option<String>,
pub(crate) if_none_match: Option<String>,
}
impl Builder {
pub fn if_match(mut self, if_match: impl Into<String>) -> Self {
self.if_match = Some(if_match.into());
self
}
pub fn if_none_match(mut self, if_none_match: impl Into<String>) -> Self {
self.if_none_match = Some(if_none_match.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.streaming_job).map_err(Error::Serialize)?;
if let Some(if_match) = &self.if_match {
req_builder = req_builder.header("If-Match", if_match);
}
if let Some(if_none_match) = &self.if_none_match {
req_builder = req_builder.header("If-None-Match", if_none_match);
}
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::StreamingJob =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::CREATED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::StreamingJob =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Created201(rsp_value))
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod update {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) streaming_job: models::StreamingJob,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) if_match: Option<String>,
}
impl Builder {
pub fn if_match(mut self, if_match: impl Into<String>) -> Self {
self.if_match = Some(if_match.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::StreamingJob, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PATCH);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.streaming_job).map_err(Error::Serialize)?;
if let Some(if_match) = &self.if_match {
req_builder = req_builder.header("If-Match", if_match);
}
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::StreamingJob =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod delete {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
NoContent204,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::DELETE);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => Ok(Response::Ok200),
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
http::StatusCode::NO_CONTENT => Ok(Response::NoContent204),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod list_by_resource_group {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) expand: Option<String>,
}
impl Builder {
pub fn expand(mut self, expand: impl Into<String>) -> Self {
self.expand = Some(expand.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::StreamingJobListResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(expand) = &self.expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::StreamingJobListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) expand: Option<String>,
}
impl Builder {
pub fn expand(mut self, expand: impl Into<String>) -> Self {
self.expand = Some(expand.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::StreamingJobListResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.StreamAnalytics/streamingjobs",
self.client.endpoint(),
&self.subscription_id
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(expand) = &self.expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::StreamingJobListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod start {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) start_job_parameters: Option<models::StartStreamingJobParameters>,
}
impl Builder {
pub fn start_job_parameters(mut self, start_job_parameters: impl Into<models::StartStreamingJobParameters>) -> Self {
self.start_job_parameters = Some(start_job_parameters.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/start",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = if let Some(start_job_parameters) = &self.start_job_parameters {
req_builder = req_builder.header("content-type", "application/json");
azure_core::to_json(start_job_parameters).map_err(Error::Serialize)?
} else {
azure_core::EMPTY_BODY
};
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => Ok(Response::Ok200),
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod stop {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/stop",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => Ok(Response::Ok200),
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
}
pub mod transformations {
use super::{models, API_VERSION};
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn get(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
transformation_name: impl Into<String>,
) -> get::Builder {
get::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
transformation_name: transformation_name.into(),
}
}
pub fn create_or_replace(
&self,
transformation: impl Into<models::Transformation>,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
transformation_name: impl Into<String>,
) -> create_or_replace::Builder {
create_or_replace::Builder {
client: self.0.clone(),
transformation: transformation.into(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
transformation_name: transformation_name.into(),
if_match: None,
if_none_match: None,
}
}
pub fn update(
&self,
transformation: impl Into<models::Transformation>,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
transformation_name: impl Into<String>,
) -> update::Builder {
update::Builder {
client: self.0.clone(),
transformation: transformation.into(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
transformation_name: transformation_name.into(),
if_match: None,
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) transformation_name: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Transformation, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/transformations/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name,
&self.transformation_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Transformation =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod create_or_replace {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::Transformation),
Created201(models::Transformation),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) transformation: models::Transformation,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) transformation_name: String,
pub(crate) if_match: Option<String>,
pub(crate) if_none_match: Option<String>,
}
impl Builder {
pub fn if_match(mut self, if_match: impl Into<String>) -> Self {
self.if_match = Some(if_match.into());
self
}
pub fn if_none_match(mut self, if_none_match: impl Into<String>) -> Self {
self.if_none_match = Some(if_none_match.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/transformations/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name,
&self.transformation_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.transformation).map_err(Error::Serialize)?;
if let Some(if_match) = &self.if_match {
req_builder = req_builder.header("If-Match", if_match);
}
if let Some(if_none_match) = &self.if_none_match {
req_builder = req_builder.header("If-None-Match", if_none_match);
}
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Transformation =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::CREATED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Transformation =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Created201(rsp_value))
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod update {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) transformation: models::Transformation,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) transformation_name: String,
pub(crate) if_match: Option<String>,
}
impl Builder {
pub fn if_match(mut self, if_match: impl Into<String>) -> Self {
self.if_match = Some(if_match.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Transformation, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.StreamAnalytics/streamingjobs/{}/transformations/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name,
&self.transformation_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PATCH);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.transformation).map_err(Error::Serialize)?;
if let Some(if_match) = &self.if_match {
req_builder = req_builder.header("If-Match", if_match);
}
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Transformation =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
}
pub mod subscriptions {
use super::{models, API_VERSION};
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn list_quotas(&self, location: impl Into<String>, subscription_id: impl Into<String>) -> list_quotas::Builder {
list_quotas::Builder {
client: self.0.clone(),
location: location.into(),
subscription_id: subscription_id.into(),
}
}
pub fn test_query(
&self,
test_query: impl Into<models::TestQuery>,
location: impl Into<String>,
subscription_id: impl Into<String>,
) -> test_query::Builder {
test_query::Builder {
client: self.0.clone(),
test_query: test_query.into(),
location: location.into(),
subscription_id: subscription_id.into(),
}
}
pub fn compile_query(
&self,
compile_query: impl Into<models::CompileQuery>,
location: impl Into<String>,
subscription_id: impl Into<String>,
) -> compile_query::Builder {
compile_query::Builder {
client: self.0.clone(),
compile_query: compile_query.into(),
location: location.into(),
subscription_id: subscription_id.into(),
}
}
pub fn sample_input(
&self,
sample_input: impl Into<models::SampleInput>,
location: impl Into<String>,
subscription_id: impl Into<String>,
) -> sample_input::Builder {
sample_input::Builder {
client: self.0.clone(),
sample_input: sample_input.into(),
location: location.into(),
subscription_id: subscription_id.into(),
}
}
pub fn test_input(
&self,
test_input: impl Into<models::TestInput>,
location: impl Into<String>,
subscription_id: impl Into<String>,
) -> test_input::Builder {
test_input::Builder {
client: self.0.clone(),
test_input: test_input.into(),
location: location.into(),
subscription_id: subscription_id.into(),
}
}
pub fn test_output(
&self,
test_output: impl Into<models::TestOutput>,
location: impl Into<String>,
subscription_id: impl Into<String>,
) -> test_output::Builder {
test_output::Builder {
client: self.0.clone(),
test_output: test_output.into(),
location: location.into(),
subscription_id: subscription_id.into(),
}
}
}
pub mod list_quotas {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) location: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(
self,
) -> futures::future::BoxFuture<'static, std::result::Result<models::SubscriptionQuotasListResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.StreamAnalytics/locations/{}/quotas",
self.client.endpoint(),
&self.subscription_id,
&self.location
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::SubscriptionQuotasListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod test_query {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::QueryTestingResult),
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) test_query: models::TestQuery,
pub(crate) location: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.StreamAnalytics/locations/{}/testQuery",
self.client.endpoint(),
&self.subscription_id,
&self.location
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.test_query).map_err(Error::Serialize)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::QueryTestingResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod compile_query {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) compile_query: models::CompileQuery,
pub(crate) location: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::QueryCompilationResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.StreamAnalytics/locations/{}/compileQuery",
self.client.endpoint(),
&self.subscription_id,
&self.location
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.compile_query).map_err(Error::Serialize)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::QueryCompilationResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod sample_input {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) sample_input: models::SampleInput,
pub(crate) location: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::SampleInputResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.StreamAnalytics/locations/{}/sampleInput",
self.client.endpoint(),
&self.subscription_id,
&self.location
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.sample_input).map_err(Error::Serialize)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::ACCEPTED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::SampleInputResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod test_input {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) test_input: models::TestInput,
pub(crate) location: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::TestDatasourceResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.StreamAnalytics/locations/{}/testInput",
self.client.endpoint(),
&self.subscription_id,
&self.location
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.test_input).map_err(Error::Serialize)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::ACCEPTED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::TestDatasourceResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod test_output {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) test_output: models::TestOutput,
pub(crate) location: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::TestDatasourceResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.StreamAnalytics/locations/{}/testOutput",
self.client.endpoint(),
&self.subscription_id,
&self.location
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.test_output).map_err(Error::Serialize)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::ACCEPTED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::TestDatasourceResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
}
pub mod operations {
use super::{models, API_VERSION};
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn list(&self) -> list::Builder {
list::Builder { client: self.0.clone() }
}
}
pub mod list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::OperationListResult, Error>> {
Box::pin(async move {
let url_str = &format!("{}/providers/Microsoft.StreamAnalytics/operations", self.client.endpoint(),);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::OperationListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
}
pub mod clusters {
use super::{models, API_VERSION};
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn get(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
) -> get::Builder {
get::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
}
}
pub fn create_or_update(
&self,
cluster: impl Into<models::Cluster>,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
) -> create_or_update::Builder {
create_or_update::Builder {
client: self.0.clone(),
cluster: cluster.into(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
if_match: None,
if_none_match: None,
}
}
pub fn update(
&self,
cluster: impl Into<models::Cluster>,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
) -> update::Builder {
update::Builder {
client: self.0.clone(),
cluster: cluster.into(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
if_match: None,
}
}
pub fn delete(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
) -> delete::Builder {
delete::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
}
}
pub fn list_by_subscription(&self, subscription_id: impl Into<String>) -> list_by_subscription::Builder {
list_by_subscription::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
}
}
pub fn list_by_resource_group(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
) -> list_by_resource_group::Builder {
list_by_resource_group::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
}
}
pub fn list_streaming_jobs(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
) -> list_streaming_jobs::Builder {
list_streaming_jobs::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Cluster, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StreamAnalytics/clusters/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Cluster =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod create_or_update {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::Cluster),
Created201(models::Cluster),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) cluster: models::Cluster,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) if_match: Option<String>,
pub(crate) if_none_match: Option<String>,
}
impl Builder {
pub fn if_match(mut self, if_match: impl Into<String>) -> Self {
self.if_match = Some(if_match.into());
self
}
pub fn if_none_match(mut self, if_none_match: impl Into<String>) -> Self {
self.if_none_match = Some(if_none_match.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StreamAnalytics/clusters/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.cluster).map_err(Error::Serialize)?;
if let Some(if_match) = &self.if_match {
req_builder = req_builder.header("If-Match", if_match);
}
if let Some(if_none_match) = &self.if_none_match {
req_builder = req_builder.header("If-None-Match", if_none_match);
}
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Cluster =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::CREATED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Cluster =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Created201(rsp_value))
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod update {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::Cluster),
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) cluster: models::Cluster,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) if_match: Option<String>,
}
impl Builder {
pub fn if_match(mut self, if_match: impl Into<String>) -> Self {
self.if_match = Some(if_match.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StreamAnalytics/clusters/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PATCH);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.cluster).map_err(Error::Serialize)?;
if let Some(if_match) = &self.if_match {
req_builder = req_builder.header("If-Match", if_match);
}
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Cluster =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod delete {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
NoContent204,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StreamAnalytics/clusters/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::DELETE);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => Ok(Response::Ok200),
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
http::StatusCode::NO_CONTENT => Ok(Response::NoContent204),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod list_by_subscription {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::ClusterListResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.StreamAnalytics/clusters",
self.client.endpoint(),
&self.subscription_id
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ClusterListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod list_by_resource_group {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::ClusterListResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StreamAnalytics/clusters",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ClusterListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod list_streaming_jobs {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::ClusterJobListResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StreamAnalytics/clusters/{}/listStreamingJobs",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ClusterJobListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
}
pub mod private_endpoints {
use super::{models, API_VERSION};
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn get(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
private_endpoint_name: impl Into<String>,
) -> get::Builder {
get::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
private_endpoint_name: private_endpoint_name.into(),
}
}
pub fn create_or_update(
&self,
private_endpoint: impl Into<models::PrivateEndpoint>,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
private_endpoint_name: impl Into<String>,
) -> create_or_update::Builder {
create_or_update::Builder {
client: self.0.clone(),
private_endpoint: private_endpoint.into(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
private_endpoint_name: private_endpoint_name.into(),
if_match: None,
if_none_match: None,
}
}
pub fn delete(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
private_endpoint_name: impl Into<String>,
) -> delete::Builder {
delete::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
private_endpoint_name: private_endpoint_name.into(),
}
}
pub fn list_by_cluster(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
) -> list_by_cluster::Builder {
list_by_cluster::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) private_endpoint_name: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::PrivateEndpoint, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StreamAnalytics/clusters/{}/privateEndpoints/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.private_endpoint_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::PrivateEndpoint =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod create_or_update {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::PrivateEndpoint),
Created201(models::PrivateEndpoint),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) private_endpoint: models::PrivateEndpoint,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) private_endpoint_name: String,
pub(crate) if_match: Option<String>,
pub(crate) if_none_match: Option<String>,
}
impl Builder {
pub fn if_match(mut self, if_match: impl Into<String>) -> Self {
self.if_match = Some(if_match.into());
self
}
pub fn if_none_match(mut self, if_none_match: impl Into<String>) -> Self {
self.if_none_match = Some(if_none_match.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StreamAnalytics/clusters/{}/privateEndpoints/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.private_endpoint_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.private_endpoint).map_err(Error::Serialize)?;
if let Some(if_match) = &self.if_match {
req_builder = req_builder.header("If-Match", if_match);
}
if let Some(if_none_match) = &self.if_none_match {
req_builder = req_builder.header("If-None-Match", if_none_match);
}
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::PrivateEndpoint =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::CREATED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::PrivateEndpoint =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Created201(rsp_value))
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod delete {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
NoContent204,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) private_endpoint_name: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StreamAnalytics/clusters/{}/privateEndpoints/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.private_endpoint_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::DELETE);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => Ok(Response::Ok200),
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
http::StatusCode::NO_CONTENT => Ok(Response::NoContent204),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod list_by_cluster {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::Error,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::PrivateEndpointListResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StreamAnalytics/clusters/{}/privateEndpoints",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::PrivateEndpointListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Error =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
}
| 50.322167 | 313 | 0.50992 |
8fd5613a8a87143196cce06991b359399015b53f | 2,518 | use bit_vec::BitVec;
#[cfg_attr(rustfmt, rustfmt_skip)]
const NEIGHBORS: &[(isize, isize)] = &[
(-1, -1), (0, -1), (1, -1),
(-1, 0), (1, 0),
(-1, 1), (0, 1), (1, 1),
];
#[derive(Debug)]
pub struct World {
pub width: usize,
pub height: usize,
data: BitVec,
}
impl World {
pub fn new(width: usize, height: usize) -> Self {
World {
width,
height,
data: BitVec::from_elem(width * height, false),
}
}
pub fn get(&self, x: usize, y: usize) -> bool {
self.assert_in_bounds(x, y);
self.data.get(y * self.width + x).unwrap()
}
pub fn set(&mut self, x: usize, y: usize, cell: bool) {
self.assert_in_bounds(x, y);
self.data.set(y * self.width + x, cell);
}
fn assert_in_bounds(&self, x: usize, y: usize) {
debug_assert!(
x < self.width,
"x out of bounds: the width is {} but the x is {}",
self.width,
x
);
debug_assert!(
y < self.height,
"y out of bounds: the height is {} but the y is {}",
self.height,
y
);
}
pub fn next_generation(&self) -> Self {
let mut next_world = World::new(self.width, self.height);
for y in 0..self.height {
for x in 0..self.width {
let cell = self.get(x, y);
let n = self.count_neighbors(x, y);
let next_cell = if cell { n >= 2 && n <= 3 } else { n == 3 };
next_world.set(x, y, next_cell);
}
}
next_world
}
fn count_neighbors(&self, x: usize, y: usize) -> u8 {
#[cfg_attr(rustfmt, rustfmt_skip)]
fn checked_add(n: usize, dir: isize, max: usize) -> Option<usize> {
if dir == 0 { Some(n) }
else if dir < 0 && n > 0 { Some(n - 1) }
else if dir > 0 && n < max - 1 { Some(n + 1) }
else { None }
}
let mut result = 0;
for (dx, dy) in NEIGHBORS {
let dx = checked_add(x, *dx, self.width);
let dy = checked_add(y, *dy, self.height);
match (dx, dy) {
(Some(dx), Some(dy)) if self.get(dx, dy) => result += 1,
_ => {}
}
}
result
}
pub fn render(&self) -> String {
let mut result = String::with_capacity((self.width + 1) * self.height);
for row in (0..self.height).map(|y| self.render_row(y)) {
result.push_str(&row);
result.push('\n');
}
result
}
pub fn render_row(&self, y: usize) -> String {
(0..self.width)
.map(|x| if self.get(x, y) { '#' } else { '~' })
.collect()
}
}
| 23.980952 | 75 | 0.509134 |
9086087db1f2b34940dd43ea69afa57e71258a39 | 3,725 | use crate::{
compilation::{context::CompilationContext, JSONSchema},
error::{error, no_error, CompilationError, ErrorIterator, ValidationError},
keywords::CompilationResult,
validator::Validate,
};
use serde_json::{Map, Value};
use std::f64::EPSILON;
pub(crate) struct MultipleOfFloatValidator {
multiple_of: f64,
}
impl MultipleOfFloatValidator {
#[inline]
pub(crate) fn compile(multiple_of: f64) -> CompilationResult {
Ok(Box::new(MultipleOfFloatValidator { multiple_of }))
}
}
impl Validate for MultipleOfFloatValidator {
fn is_valid(&self, _: &JSONSchema, instance: &Value) -> bool {
if let Value::Number(item) = instance {
let item = item.as_f64().expect("Always valid");
let remainder = (item / self.multiple_of) % 1.;
if !(remainder < EPSILON && remainder < (1. - EPSILON)) {
return false;
}
}
true
}
fn validate<'a>(&self, _: &'a JSONSchema, instance: &'a Value) -> ErrorIterator<'a> {
if let Value::Number(item) = instance {
let item = item.as_f64().expect("Always valid");
let remainder = (item / self.multiple_of) % 1.;
if !(remainder < EPSILON && remainder < (1. - EPSILON)) {
return error(ValidationError::multiple_of(instance, self.multiple_of));
}
}
no_error()
}
}
impl ToString for MultipleOfFloatValidator {
fn to_string(&self) -> String {
format!("multipleOf: {}", self.multiple_of)
}
}
pub(crate) struct MultipleOfIntegerValidator {
multiple_of: f64,
}
impl MultipleOfIntegerValidator {
#[inline]
pub(crate) fn compile(multiple_of: f64) -> CompilationResult {
Ok(Box::new(MultipleOfIntegerValidator { multiple_of }))
}
}
impl Validate for MultipleOfIntegerValidator {
fn is_valid(&self, _: &JSONSchema, instance: &Value) -> bool {
if let Value::Number(item) = instance {
let item = item.as_f64().expect("Always valid");
let is_multiple = if item.fract() == 0. {
(item % self.multiple_of) == 0.
} else {
let remainder = (item / self.multiple_of) % 1.;
remainder < EPSILON && remainder < (1. - EPSILON)
};
if !is_multiple {
return false;
}
}
true
}
fn validate<'a>(&self, _: &'a JSONSchema, instance: &'a Value) -> ErrorIterator<'a> {
if let Value::Number(item) = instance {
let item = item.as_f64().expect("Always valid");
let is_multiple = if item.fract() == 0. {
(item % self.multiple_of) == 0.
} else {
let remainder = (item / self.multiple_of) % 1.;
remainder < EPSILON && remainder < (1. - EPSILON)
};
if !is_multiple {
return error(ValidationError::multiple_of(instance, self.multiple_of));
}
}
no_error()
}
}
impl ToString for MultipleOfIntegerValidator {
fn to_string(&self) -> String {
format!("multipleOf: {}", self.multiple_of)
}
}
#[inline]
pub(crate) fn compile(
_: &Map<String, Value>,
schema: &Value,
_: &CompilationContext,
) -> Option<CompilationResult> {
if let Value::Number(multiple_of) = schema {
let multiple_of = multiple_of.as_f64().expect("Always valid");
if multiple_of.fract() == 0. {
Some(MultipleOfIntegerValidator::compile(multiple_of))
} else {
Some(MultipleOfFloatValidator::compile(multiple_of))
}
} else {
Some(Err(CompilationError::SchemaError))
}
}
| 31.567797 | 89 | 0.57557 |
1804925aeac187b6167f0b21e00850d37c826df1 | 2,174 | #[doc = "Reader of register OCMS"]
pub type R = crate::R<u32, super::OCMS>;
#[doc = "Writer for register OCMS"]
pub type W = crate::W<u32, super::OCMS>;
#[doc = "Register OCMS `reset()`'s with value 0"]
impl crate::ResetValue for super::OCMS {
#[inline(always)]
fn reset_value() -> Self::Ux { 0 }
}
#[doc = "Reader of field `SMSE`"]
pub type SMSE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SMSE`"]
pub struct SMSE_W<'a> { w: &'a mut W }
impl<'a> SMSE_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
}
}
#[doc = "Reader of field `SRSE`"]
pub type SRSE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SRSE`"]
pub struct SRSE_W<'a> { w: &'a mut W }
impl<'a> SRSE_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 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
impl R {
#[doc = "Bit 0 - Static Memory Controller Scrambling Enable"]
#[inline(always)]
pub fn smse(&self) -> SMSE_R { SMSE_R::new((self.bits & 0x01) != 0) }
#[doc = "Bit 1 - SRAM Scrambling Enable"]
#[inline(always)]
pub fn srse(&self) -> SRSE_R { SRSE_R::new(((self.bits >> 1) & 0x01) != 0) }
}
impl W {
#[doc = "Bit 0 - Static Memory Controller Scrambling Enable"]
#[inline(always)]
pub fn smse(&mut self) -> SMSE_W { SMSE_W { w: self } }
#[doc = "Bit 1 - SRAM Scrambling Enable"]
#[inline(always)]
pub fn srse(&mut self) -> SRSE_W { SRSE_W { w: self } }
} | 31.057143 | 84 | 0.566697 |
eff9f90a8619e29d4ae697d28a021b9d21e34cce | 14,363 | //! List of the accepted feature gates.
use crate::symbol::sym;
use super::{State, Feature};
macro_rules! declare_features {
($(
$(#[doc = $doc:tt])* (accepted, $feature:ident, $ver:expr, $issue:expr, None),
)+) => {
/// Those language feature has since been Accepted (it was once Active)
pub const ACCEPTED_FEATURES: &[Feature] = &[
$(
Feature {
state: State::Accepted,
name: sym::$feature,
since: $ver,
issue: $issue,
edition: None,
description: concat!($($doc,)*),
}
),+
];
}
}
declare_features! (
// -------------------------------------------------------------------------
// feature-group-start: for testing purposes
// -------------------------------------------------------------------------
/// A temporary feature gate used to enable parser extensions needed
/// to bootstrap fix for #5723.
(accepted, issue_5723_bootstrap, "1.0.0", None, None),
/// These are used to test this portion of the compiler,
/// they don't actually mean anything.
(accepted, test_accepted_feature, "1.0.0", None, None),
// -------------------------------------------------------------------------
// feature-group-end: for testing purposes
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// feature-group-start: accepted features
// -------------------------------------------------------------------------
/// Allows using associated `type`s in `trait`s.
(accepted, associated_types, "1.0.0", None, None),
/// Allows using assigning a default type to type parameters in algebraic data type definitions.
(accepted, default_type_params, "1.0.0", None, None),
// FIXME: explain `globs`.
(accepted, globs, "1.0.0", None, None),
/// Allows `macro_rules!` items.
(accepted, macro_rules, "1.0.0", None, None),
/// Allows use of `&foo[a..b]` as a slicing syntax.
(accepted, slicing_syntax, "1.0.0", None, None),
/// Allows struct variants `Foo { baz: u8, .. }` in enums (RFC 418).
(accepted, struct_variant, "1.0.0", None, None),
/// Allows indexing tuples.
(accepted, tuple_indexing, "1.0.0", None, None),
/// Allows the use of `if let` expressions.
(accepted, if_let, "1.0.0", None, None),
/// Allows the use of `while let` expressions.
(accepted, while_let, "1.0.0", None, None),
/// Allows using `#![no_std]`.
(accepted, no_std, "1.6.0", None, None),
/// Allows overloading augmented assignment operations like `a += b`.
(accepted, augmented_assignments, "1.8.0", Some(28235), None),
/// Allows empty structs and enum variants with braces.
(accepted, braced_empty_structs, "1.8.0", Some(29720), None),
/// Allows `#[deprecated]` attribute.
(accepted, deprecated, "1.9.0", Some(29935), None),
/// Allows macros to appear in the type position.
(accepted, type_macros, "1.13.0", Some(27245), None),
/// Allows use of the postfix `?` operator in expressions.
(accepted, question_mark, "1.13.0", Some(31436), None),
/// Allows `..` in tuple (struct) patterns.
(accepted, dotdot_in_tuple_patterns, "1.14.0", Some(33627), None),
/// Allows some increased flexibility in the name resolution rules,
/// especially around globs and shadowing (RFC 1560).
(accepted, item_like_imports, "1.15.0", Some(35120), None),
/// Allows using `Self` and associated types in struct expressions and patterns.
(accepted, more_struct_aliases, "1.16.0", Some(37544), None),
/// Allows elision of `'static` lifetimes in `static`s and `const`s.
(accepted, static_in_const, "1.17.0", Some(35897), None),
/// Allows field shorthands (`x` meaning `x: x`) in struct literal expressions.
(accepted, field_init_shorthand, "1.17.0", Some(37340), None),
/// Allows the definition recursive static items.
(accepted, static_recursion, "1.17.0", Some(29719), None),
/// Allows `pub(restricted)` visibilities (RFC 1422).
(accepted, pub_restricted, "1.18.0", Some(32409), None),
/// Allows `#![windows_subsystem]`.
(accepted, windows_subsystem, "1.18.0", Some(37499), None),
/// Allows `break {expr}` with a value inside `loop`s.
(accepted, loop_break_value, "1.19.0", Some(37339), None),
/// Allows numeric fields in struct expressions and patterns.
(accepted, relaxed_adts, "1.19.0", Some(35626), None),
/// Allows coercing non capturing closures to function pointers.
(accepted, closure_to_fn_coercion, "1.19.0", Some(39817), None),
/// Allows attributes on struct literal fields.
(accepted, struct_field_attributes, "1.20.0", Some(38814), None),
/// Allows the definition of associated constants in `trait` or `impl` blocks.
(accepted, associated_consts, "1.20.0", Some(29646), None),
/// Allows usage of the `compile_error!` macro.
(accepted, compile_error, "1.20.0", Some(40872), None),
/// Allows code like `let x: &'static u32 = &42` to work (RFC 1414).
(accepted, rvalue_static_promotion, "1.21.0", Some(38865), None),
/// Allows `Drop` types in constants (RFC 1440).
(accepted, drop_types_in_const, "1.22.0", Some(33156), None),
/// Allows the sysV64 ABI to be specified on all platforms
/// instead of just the platforms on which it is the C ABI.
(accepted, abi_sysv64, "1.24.0", Some(36167), None),
/// Allows `repr(align(16))` struct attribute (RFC 1358).
(accepted, repr_align, "1.25.0", Some(33626), None),
/// Allows '|' at beginning of match arms (RFC 1925).
(accepted, match_beginning_vert, "1.25.0", Some(44101), None),
/// Allows nested groups in `use` items (RFC 2128).
(accepted, use_nested_groups, "1.25.0", Some(44494), None),
/// Allows indexing into constant arrays.
(accepted, const_indexing, "1.26.0", Some(29947), None),
/// Allows using `a..=b` and `..=b` as inclusive range syntaxes.
(accepted, inclusive_range_syntax, "1.26.0", Some(28237), None),
/// Allows `..=` in patterns (RFC 1192).
(accepted, dotdoteq_in_patterns, "1.26.0", Some(28237), None),
/// Allows `fn main()` with return types which implements `Termination` (RFC 1937).
(accepted, termination_trait, "1.26.0", Some(43301), None),
/// Allows implementing `Clone` for closures where possible (RFC 2132).
(accepted, clone_closures, "1.26.0", Some(44490), None),
/// Allows implementing `Copy` for closures where possible (RFC 2132).
(accepted, copy_closures, "1.26.0", Some(44490), None),
/// Allows `impl Trait` in function arguments.
(accepted, universal_impl_trait, "1.26.0", Some(34511), None),
/// Allows `impl Trait` in function return types.
(accepted, conservative_impl_trait, "1.26.0", Some(34511), None),
/// Allows using the `u128` and `i128` types.
(accepted, i128_type, "1.26.0", Some(35118), None),
/// Allows default match binding modes (RFC 2005).
(accepted, match_default_bindings, "1.26.0", Some(42640), None),
/// Allows `'_` placeholder lifetimes.
(accepted, underscore_lifetimes, "1.26.0", Some(44524), None),
/// Allows attributes on lifetime/type formal parameters in generics (RFC 1327).
(accepted, generic_param_attrs, "1.27.0", Some(48848), None),
/// Allows `cfg(target_feature = "...")`.
(accepted, cfg_target_feature, "1.27.0", Some(29717), None),
/// Allows `#[target_feature(...)]`.
(accepted, target_feature, "1.27.0", None, None),
/// Allows using `dyn Trait` as a syntax for trait objects.
(accepted, dyn_trait, "1.27.0", Some(44662), None),
/// Allows `#[must_use]` on functions, and introduces must-use operators (RFC 1940).
(accepted, fn_must_use, "1.27.0", Some(43302), None),
/// Allows use of the `:lifetime` macro fragment specifier.
(accepted, macro_lifetime_matcher, "1.27.0", Some(34303), None),
/// Allows `#[test]` functions where the return type implements `Termination` (RFC 1937).
(accepted, termination_trait_test, "1.27.0", Some(48854), None),
/// Allows the `#[global_allocator]` attribute.
(accepted, global_allocator, "1.28.0", Some(27389), None),
/// Allows `#[repr(transparent)]` attribute on newtype structs.
(accepted, repr_transparent, "1.28.0", Some(43036), None),
/// Allows procedural macros in `proc-macro` crates.
(accepted, proc_macro, "1.29.0", Some(38356), None),
/// Allows `foo.rs` as an alternative to `foo/mod.rs`.
(accepted, non_modrs_mods, "1.30.0", Some(44660), None),
/// Allows use of the `:vis` macro fragment specifier
(accepted, macro_vis_matcher, "1.30.0", Some(41022), None),
/// Allows importing and reexporting macros with `use`,
/// enables macro modularization in general.
(accepted, use_extern_macros, "1.30.0", Some(35896), None),
/// Allows keywords to be escaped for use as identifiers.
(accepted, raw_identifiers, "1.30.0", Some(48589), None),
/// Allows attributes scoped to tools.
(accepted, tool_attributes, "1.30.0", Some(44690), None),
/// Allows multi-segment paths in attributes and derives.
(accepted, proc_macro_path_invoc, "1.30.0", Some(38356), None),
/// Allows all literals in attribute lists and values of key-value pairs.
(accepted, attr_literals, "1.30.0", Some(34981), None),
/// Allows inferring outlives requirements (RFC 2093).
(accepted, infer_outlives_requirements, "1.30.0", Some(44493), None),
/// Allows annotating functions conforming to `fn(&PanicInfo) -> !` with `#[panic_handler]`.
/// This defines the behavior of panics.
(accepted, panic_handler, "1.30.0", Some(44489), None),
/// Allows `#[used]` to preserve symbols (see llvm.used).
(accepted, used, "1.30.0", Some(40289), None),
/// Allows `crate` in paths.
(accepted, crate_in_paths, "1.30.0", Some(45477), None),
/// Allows resolving absolute paths as paths from other crates.
(accepted, extern_absolute_paths, "1.30.0", Some(44660), None),
/// Allows access to crate names passed via `--extern` through prelude.
(accepted, extern_prelude, "1.30.0", Some(44660), None),
/// Allows parentheses in patterns.
(accepted, pattern_parentheses, "1.31.0", Some(51087), None),
/// Allows the definition of `const fn` functions.
(accepted, min_const_fn, "1.31.0", Some(53555), None),
/// Allows scoped lints.
(accepted, tool_lints, "1.31.0", Some(44690), None),
/// Allows lifetime elision in `impl` headers. For example:
/// + `impl<I:Iterator> Iterator for &mut Iterator`
/// + `impl Debug for Foo<'_>`
(accepted, impl_header_lifetime_elision, "1.31.0", Some(15872), None),
/// Allows `extern crate foo as bar;`. This puts `bar` into extern prelude.
(accepted, extern_crate_item_prelude, "1.31.0", Some(55599), None),
/// Allows use of the `:literal` macro fragment specifier (RFC 1576).
(accepted, macro_literal_matcher, "1.32.0", Some(35625), None),
/// Allows use of `?` as the Kleene "at most one" operator in macros.
(accepted, macro_at_most_once_rep, "1.32.0", Some(48075), None),
/// Allows `Self` struct constructor (RFC 2302).
(accepted, self_struct_ctor, "1.32.0", Some(51994), None),
/// Allows `Self` in type definitions (RFC 2300).
(accepted, self_in_typedefs, "1.32.0", Some(49303), None),
/// Allows `use x::y;` to search `x` in the current scope.
(accepted, uniform_paths, "1.32.0", Some(53130), None),
/// Allows integer match exhaustiveness checking (RFC 2591).
(accepted, exhaustive_integer_patterns, "1.33.0", Some(50907), None),
/// Allows `use path as _;` and `extern crate c as _;`.
(accepted, underscore_imports, "1.33.0", Some(48216), None),
/// Allows `#[repr(packed(N))]` attribute on structs.
(accepted, repr_packed, "1.33.0", Some(33158), None),
/// Allows irrefutable patterns in `if let` and `while let` statements (RFC 2086).
(accepted, irrefutable_let_patterns, "1.33.0", Some(44495), None),
/// Allows calling `const unsafe fn` inside `unsafe` blocks in `const fn` functions.
(accepted, min_const_unsafe_fn, "1.33.0", Some(55607), None),
/// Allows let bindings, assignments and destructuring in `const` functions and constants.
/// As long as control flow is not implemented in const eval, `&&` and `||` may not be used
/// at the same time as let bindings.
(accepted, const_let, "1.33.0", Some(48821), None),
/// Allows `#[cfg_attr(predicate, multiple, attributes, here)]`.
(accepted, cfg_attr_multi, "1.33.0", Some(54881), None),
/// Allows top level or-patterns (`p | q`) in `if let` and `while let`.
(accepted, if_while_or_patterns, "1.33.0", Some(48215), None),
/// Allows `cfg(target_vendor = "...")`.
(accepted, cfg_target_vendor, "1.33.0", Some(29718), None),
/// Allows `extern crate self as foo;`.
/// This puts local crate root into extern prelude under name `foo`.
(accepted, extern_crate_self, "1.34.0", Some(56409), None),
/// Allows arbitrary delimited token streams in non-macro attributes.
(accepted, unrestricted_attribute_tokens, "1.34.0", Some(55208), None),
/// Allows paths to enum variants on type aliases including `Self`.
(accepted, type_alias_enum_variants, "1.37.0", Some(49683), None),
/// Allows using `#[repr(align(X))]` on enums with equivalent semantics
/// to wrapping an enum in a wrapper struct with `#[repr(align(X))]`.
(accepted, repr_align_enum, "1.37.0", Some(57996), None),
/// Allows `const _: TYPE = VALUE`.
(accepted, underscore_const_names, "1.37.0", Some(54912), None),
/// Allows free and inherent `async fn`s, `async` blocks, and `<expr>.await` expressions.
(accepted, async_await, "1.39.0", Some(50547), None),
/// Allows mixing bind-by-move in patterns and references to those identifiers in guards.
(accepted, bind_by_move_pattern_guards, "1.39.0", Some(15287), None),
// -------------------------------------------------------------------------
// feature-group-end: accepted features
// -------------------------------------------------------------------------
);
| 57.223108 | 100 | 0.618603 |
e6bfe1459025968c8eeac8f459a63ecba36a2f65 | 1,133 | // structs1.rs
// Address all the TODOs to make the tests pass!
// I AM NOT DONE
struct ColorClassicStruct {
// TODO: Something goes here
name: String,
hex: String,
}
struct ColorTupleStruct(/* TODO: Something goes here */ String, String);
#[derive(Debug)]
struct UnitStruct;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classic_c_structs() {
// TODO: Instantiate a classic c struct!
let green = ColorClassicStruct {
name: String::from("green"),
hex: String::from("#00FF00"),
};
assert_eq!(green.name, "green");
assert_eq!(green.hex, "#00FF00");
}
#[test]
fn tuple_structs() {
// TODO: Instantiate a tuple struct!
let green = (String::from("green"), String::from("#00FF00"));
assert_eq!(green.0, "green");
assert_eq!(green.1, "#00FF00");
}
#[test]
fn unit_structs() {
// TODO: Instantiate a unit struct!
let unit_struct = UnitStruct;
let message = format!("{:?}s are fun!", unit_struct);
assert_eq!(message, "UnitStructs are fun!");
}
}
| 22.215686 | 72 | 0.572816 |
dee281c811da55d0e555626709fee99588a5d58e | 388 | //! Primitives and methods for accessing and working with item metadata.
pub mod item_paths;
pub mod new_schema;
pub mod plexer;
pub mod processor;
pub mod schema;
pub use self::plexer::{Error as PlexerError, Plexer};
pub use self::processor::Error as ProcessorError;
pub use self::schema::{Arity, Schema};
pub use self::new_schema::Metadata;
pub(crate) use self::schema::SchemaRepr;
| 24.25 | 72 | 0.760309 |
698277df11ee53ee9eda445a768f9d5e5fea9f59 | 600 | //3456789a123456789b123456789c123456789d123456789e123456789f123456789g123456789h
//
// pure rust program arguments
// https://rustbyexample.com/std_misc/arg.html
// https://doc.rust-lang.org/book/second-edition/ch12-03-improving-error-handling-and-modularity.html
//
const TRY_HELP_MSG: &str = "Try --help for help.";
fn main() {
match cmp_pure_rust::one::create_conf() {
Ok(args) => {
println!("{:?}", args);
}
Err(err) => {
eprintln!("{}\n{}", err, TRY_HELP_MSG);
std::process::exit(1);
}
}
std::process::exit(0);
}
| 27.272727 | 101 | 0.613333 |
8a0eeb1ee88f69b08832141a5b4f4b7b2a1466df | 498 | // PNG Pong
//
// Copyright © 2019-2020 Jeron Aldaron Lau
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// https://apache.org/licenses/LICENSE-2.0>, or the Zlib License, <LICENSE-ZLIB
// or http://opensource.org/licenses/Zlib>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//! PNG file decoding
mod chunks;
mod error;
mod steps;
pub use chunks::Chunks;
pub use error::{Error, Result};
pub use steps::Steps;
| 26.210526 | 80 | 0.720884 |
752d5f0771b3c1f52ad2a9fe810fa96bee0c6441 | 3,133 | use bevy::prelude::*;
use crate::property::{self, PropertyAccess, PropertyName, PropertyUpdateEvent, PropertyValue};
/// This example illustrates how to create a button that changes color and text based on its interaction state.
pub struct ButtonPlugin;
impl Plugin for ButtonPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<ButtonMaterials>()
.add_system(property_toggle_button_system.system());
// .add_system(toggle_button_text_system.exclusive_system());
}
}
pub struct ButtonMaterials {
pub normal: Handle<ColorMaterial>,
pub hovered: Handle<ColorMaterial>,
pub pressed: Handle<ColorMaterial>,
}
impl FromWorld for ButtonMaterials {
fn from_world(world: &mut World) -> Self {
let mut materials = world.get_resource_mut::<Assets<ColorMaterial>>().unwrap();
ButtonMaterials {
normal: materials.add(Color::rgb(0.02, 0.02, 0.02).into()),
hovered: materials.add(Color::rgb(0.05, 0.05, 0.05).into()),
pressed: materials.add(Color::rgb(0.1, 0.5, 0.1).into()),
}
}
}
pub struct ToggleButton {
pub property_name: String,
pub on_text: String,
pub off_text: String,
}
fn property_toggle_button_system(
button_materials: Res<ButtonMaterials>,
mut property_update_events: EventWriter<property::PropertyUpdateEvent>,
query: Query<(&PropertyAccess, &ToggleButton, &Children), Changed<PropertyAccess>>,
mut interaction_query: Query<
(
&Interaction,
&mut Handle<ColorMaterial>,
&PropertyName,
&PropertyAccess,
),
(Changed<Interaction>, With<ToggleButton>),
>,
mut text_query: Query<&mut Text>,
) {
for (interaction, mut material, property_name, property_access) in interaction_query.iter_mut()
{
match *interaction {
Interaction::Clicked => {
let v = if let PropertyValue::Bool(v) = property_access.cache {
v
} else {
false
};
let new_value = PropertyValue::Bool(!v);
println!("send update: {} {:?}", property_name.0, new_value);
property_update_events
.send(PropertyUpdateEvent::new(property_name.0.clone(), new_value));
*material = button_materials.pressed.clone();
}
Interaction::Hovered => {
*material = button_materials.hovered.clone();
}
Interaction::None => {
*material = button_materials.normal.clone();
}
}
}
for (access, toggle_button, children) in query.iter() {
println!("change detected: {:?}", access.cache);
let mut text = text_query.get_mut(children[0]).unwrap();
let is_on = if let PropertyValue::Bool(v) = access.cache {
v
} else {
false
};
text.sections[0].value = if is_on {
&toggle_button.on_text
} else {
&toggle_button.off_text
}
.clone();
}
}
| 32.978947 | 111 | 0.589531 |
0a1f881a150e49fe8204b4ec38e4b88eb787035b | 9,326 | use crate::{database::entity::files, util::GIT_VERSION};
use actix_http::Uri;
use clap::Parser;
use colored::*;
use config::StorageConfig;
use figlet_rs::FIGfont;
use indicatif::{ProgressBar, ProgressStyle};
use models::MessageResponse;
use sea_orm::{ConnectOptions, Database, EntityTrait};
use sqlx::{migrate::Migrator, postgres::PgPoolOptions};
use state::State;
use tokio::fs;
use util::file::IMAGE_EXTS;
use std::{convert::TryInto, ffi::OsStr, path::Path, time::Duration};
use actix_web::{
http::StatusCode,
middleware::Logger,
web::{self, Data},
App, HttpRequest, HttpServer,
};
use actix_files::NamedFile;
use lettre::{transport::smtp::authentication::Credentials, AsyncSmtpTransport, Tokio1Executor};
use storage::{local::LocalProvider, s3::S3Provider, StorageProvider};
#[macro_use]
extern crate lazy_static;
extern crate argon2;
extern crate dotenv;
extern crate env_logger;
mod config;
mod database;
mod models;
mod routes;
mod state;
mod storage;
mod util;
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Args {
/// Regenerate image thumbnails
#[clap(short, long, takes_value = false)]
generate_thumbnails: bool,
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// Setup actix log
std::env::set_var("RUST_LOG", "actix_web=info,backpack=info,sqlx=error");
env_logger::init();
let fig_font = FIGfont::from_content(include_str!("./resources/small.flf")).unwrap();
let figure = fig_font.convert("Backpack").unwrap();
println!("{}", figure.to_string().purple());
println!(
"Running Backpack on version: {}",
GIT_VERSION.to_string().yellow()
);
let config = config::Config::new();
let args = Args::parse();
// Create a SQLx pool for running migrations
let migrator_pool = PgPoolOptions::new()
.max_connections(1)
.connect(&config.database_url)
.await
.expect("Could not initialize migrator connection");
let migrator = Migrator::new(Path::new("migrations")).await.unwrap();
migrator
.run(&migrator_pool)
.await
.map_err(|e| anyhow::anyhow!(e.to_string()))
.unwrap();
migrator_pool.close().await;
let mut opt = ConnectOptions::new(config.database_url.clone());
opt.max_connections(100)
.min_connections(5)
.connect_timeout(Duration::from_secs(8))
.idle_timeout(Duration::from_secs(8))
.max_lifetime(Duration::from_secs(8))
.sqlx_logging(true);
let database = Database::connect(opt).await.unwrap();
log::info!("Connected to the database");
let storage: Box<dyn StorageProvider> = match &config.storage_provider {
StorageConfig::Local(v) => {
if !v.path.exists() {
fs::create_dir(&v.path).await.expect(&format!(
"Unable to create {} directory",
v.path.to_str().unwrap_or("storage")
));
}
// Thumbnail directory
let mut thumb_path = v.path.clone();
thumb_path.push("thumb");
if !thumb_path.exists() {
fs::create_dir(&thumb_path)
.await
.expect("Unable to create thumbnail directory");
}
Box::new(LocalProvider::new(v.path.clone()))
}
StorageConfig::S3(v) => Box::new(S3Provider::new(
&v.bucket,
&v.access_key,
&v.secret_key,
v.region.clone(),
)),
};
let smtp_client = match config.smtp_config {
Some(smtp_config) => {
let creds = Credentials::new(smtp_config.username.clone(), smtp_config.password);
Some((
AsyncSmtpTransport::<Tokio1Executor>::relay(&smtp_config.server)
.unwrap()
.credentials(creds)
.build(),
smtp_config.username,
))
}
None => None,
};
// Get setting as single boolean before client gets moved
let smtp_enabled = smtp_client.is_some();
let invite_only = config.invite_only;
let api_state = Data::new(state::State {
database,
storage,
jwt_key: config.jwt_key,
smtp_client,
base_url: config.base_url.parse::<Uri>().unwrap(),
storage_url: config.storage_url,
// Convert MB to bytes
file_size_limit: config.file_size_limit * 1000 * 1000,
invite_only: config.invite_only,
});
// If the generate thumbnails flag is enabled
if args.generate_thumbnails {
generate_thumbnails(&api_state).await.unwrap();
return Ok(());
}
let storage_path = match &config.storage_provider {
StorageConfig::Local(v) => {
if v.serve {
Some(v.path.clone())
} else {
None
}
}
_ => None,
};
log::info!(
"Starting webserver on port {}",
config.port.to_string().yellow()
);
HttpServer::new(move || {
let base_storage_path = storage_path.clone();
App::new()
.wrap(Logger::default())
.app_data(api_state.clone())
.service(
web::scope("/api/")
.service(routes::user::get_routes(smtp_enabled))
.service(routes::auth::get_routes())
.service(routes::application::get_routes())
.service(routes::file::get_routes())
.service(routes::admin::get_routes(invite_only))
.service(routes::get_routes()),
)
// Error handler when json body deserialization failed
.app_data(web::JsonConfig::default().error_handler(|_, _| {
actix_web::Error::from(models::MessageResponse::bad_request())
}))
.default_service(web::to(move |req: HttpRequest| {
let storage_path = base_storage_path.clone();
async move {
if let Some(v) = &storage_path {
let mut file_path = v.clone();
// Request path after the root
let path_end = req.path().trim_start_matches('/');
// Make sure request path isn't empty
// This would attempt to send the directory (and fail) otherwise
if !path_end.eq("") {
// Sanitize the path to prevent walking to another directory
file_path.push(path_end.replace("..", ""));
if let Ok(v) = NamedFile::open(&file_path) {
return v.into_response(&req);
}
}
}
MessageResponse::new(StatusCode::NOT_FOUND, "Resource was not found!")
.http_response()
}
}))
})
.bind(("0.0.0.0", config.port))?
.run()
.await
}
async fn generate_thumbnails(state: &Data<State>) -> anyhow::Result<()> {
log::info!("Regenerating image thumbnails");
let files = files::Entity::find().all(&state.database).await?;
let image_files: Vec<files::Model> = files
.iter()
.filter(|file| {
let extension = Path::new(&file.name)
.extension()
.and_then(OsStr::to_str)
.unwrap_or("");
IMAGE_EXTS
.into_iter()
.any(|ext| ext.eq(&extension.to_uppercase()))
})
.map(|v| v.clone())
.collect();
log::info!(
"{} files to generate",
image_files.len().to_string().yellow()
);
let progress = ProgressBar::new(image_files.len().try_into().unwrap());
progress.set_style(
ProgressStyle::default_bar()
.template(&format!(
"{}{{elapsed_precise}}{} {{bar:40.cyan/blue}} {{pos:>2}}/{{len:2}} {{msg}}",
"[".bright_black(),
"]".bright_black()
))
.progress_chars("##-"),
);
for file in image_files {
let extension = Path::new(&file.name)
.extension()
.and_then(OsStr::to_str)
.unwrap_or("");
if IMAGE_EXTS
.into_iter()
.any(|ext| ext.eq(&extension.to_uppercase()))
{
progress.set_message(file.name.clone());
progress.inc(1);
match state.storage.get_object(&file.name).await {
Ok(buf) => {
if let Err(err) = state
.storage
.put_object(
&format!("thumb/{}", file.name),
&util::file::get_thumbnail_image(&buf)?,
)
.await
{
log::error!("Error putting {}: {}", file.name, err)
}
}
Err(err) => log::error!("Error getting {}: {}", file.name, err),
}
}
}
progress.finish_with_message("Finished generating thumbnails");
Ok(())
}
| 31.295302 | 95 | 0.532168 |
e5b2ee0532150983511293378d98124f59c292b4 | 11,351 | ///! Aftermath_convert_log converts a Telamon logfile into a trace
///! file that can be loaded into the Aftermath trace analysis tool
///! from https://www.aftermath-tracing.com
use log::debug;
use std::collections::HashSet;
use std::io;
use std::path::PathBuf;
use std::time::Duration;
use structopt::StructOpt;
use telamon::explorer::eventlog::EventLog;
use telamon::explorer::mcts::{Event, Message, Policy};
use telamon::offline_analysis::aftermath::TraceWriter;
use telamon::offline_analysis::tree::CandidateTree;
#[derive(Debug, StructOpt)]
#[structopt(name = "aftermath_convert_log")]
struct Opt {
#[structopt(
parse(from_os_str),
short = "i",
long = "input",
default_value = "eventlog.tfrecord.gz"
)]
eventlog: PathBuf,
#[structopt(
parse(from_os_str),
short = "o",
long = "output",
default_value = "eventlog.ost"
)]
output: PathBuf,
#[structopt(long = "exclude-traces")]
///Disables conversion of Message::Trace messages
exclude_traces: bool,
#[structopt(long = "exclude-evaluations")]
///Disables conversion of Message::Evaluation messages
exclude_evaluations: bool,
}
#[allow(clippy::cognitive_complexity)]
fn main() -> io::Result<()> {
env_logger::try_init().unwrap();
let opt = Opt::from_args();
let mut tw = TraceWriter::new(&opt.output.as_path()).unwrap();
let mut thread_ids = HashSet::new();
let mut t = CandidateTree::new();
// Write file header and declare all Aftermath frame types used in
// the trace
tw.write_default_header()?;
tw.write_default_frame_ids()?;
// Process log messages
for record_bytes in EventLog::open(&opt.eventlog)?.records() {
match bincode::deserialize(&record_bytes?).unwrap() {
// Discovery of a new node
Message::Node {
id,
parent,
bound,
children,
discovery_time,
} => {
debug!("Node (ID {}) [discovery time: {:?}]", id, discovery_time);
t.extend(
id,
discovery_time,
parent,
bound.clone(),
&mut children.clone(),
);
}
// Series of timed events performed by one thread
Message::Trace { thread, events } => {
// ID of the node that was last selected by an action;
// The root node is implicitly selected at the start
// of a thread trace
let mut curr_node_id = t.get_root().id();
let thread_id = thread
.trim_start_matches("ThreadId")
.trim_matches(|p| p == '(' || p == ')')
.parse::<u32>()
.unwrap();
let mut trace_start: Option<Duration> = None;
let mut trace_end: Option<Duration> = None;
// If the thread is yet unknown, start a new Aftermath
// event collection for its events
if thread_ids.insert(thread_id) {
tw.write_event_collection(thread_id)?;
}
debug!("Trace (thread {}):", thread_id);
debug!(" Implicit SelectNode {}", curr_node_id);
for timed_event in &events {
let start = timed_event.start_time;
let end = timed_event.end_time;
// Set start timestamp of the thread trace to the
// beginning of the first event of the trace and
// the end timestamp to the end of the last event
if trace_start.is_none() {
trace_start = Some(start);
}
trace_end = Some(end);
match timed_event.value {
// Explicit selection of a candidate
Event::SelectNode(id) => {
curr_node_id = id;
if !opt.exclude_traces {
tw.write_candidate_select_action(
thread_id,
curr_node_id,
start,
end,
)?;
}
debug!(
" SelectNode {} [interval: {:?} to {:?}]",
curr_node_id, start, end
);
}
// Selection of a child of the current candidate
Event::SelectChild(idx, policy, ref selector) => {
let mut child_node =
t.get_node(curr_node_id).child(usize::from(idx)).unwrap();
match policy {
Policy::Bandit => {
child_node.declare_internal(end);
}
Policy::Default => {
child_node.declare_rollout(end);
}
}
if !opt.exclude_traces {
tw.write_candidate_select_child_action(
thread_id as u32,
curr_node_id,
selector,
u16::from(idx),
child_node.id(),
start,
end,
)?;
}
debug!(
" SelectChild [idx: {} -> ID: {}, policy: {:?}, interval: {:?} to {:?}]",
u16::from(idx), child_node.id(), policy, start, end
);
curr_node_id = child_node.id();
}
// Expansion of the current candidate
Event::Expand => {
t.get_node(curr_node_id).declare_internal(end);
if !opt.exclude_traces {
tw.write_candidate_expand_action(
thread_id as u32,
curr_node_id,
start,
end,
)?;
}
debug!(" Expand [interval: {:?} to {:?}]", start, end);
}
// Declaring the current candidate as a
// deadend
Event::Kill(cause) => {
t.get_node(curr_node_id).declare_deadend(end);
if !opt.exclude_traces {
tw.write_candidate_kill_action(
thread_id as u32,
curr_node_id,
start,
end,
&cause,
)?;
}
debug!(" Kill [interval: {:?} to {:?}]", start, end);
}
// Declaration of a child of the current
// candidate as a deadend
Event::KillChild(child_idx, cause) => {
let mut child = t
.get_node(curr_node_id)
.child(usize::from(child_idx))
.unwrap();
child.declare_deadend(end);
if !opt.exclude_traces {
tw.write_candidate_kill_action(
thread_id as u32,
child.id(),
start,
end,
&cause,
)?;
}
debug!(
" KillChild [idx: {} -> ID: {}, interval: {:?} to {:?}]",
u16::from(child_idx),
child.id(),
start,
end
);
}
// Declaration of the current candidate as an
// implementation
Event::Implementation {} => {
t.get_node(curr_node_id).declare_implementation(end);
if !opt.exclude_traces {
tw.write_candidate_mark_implementation_action(
thread_id as u32,
curr_node_id,
start,
end,
)?;
}
debug!(
" Implementation [interval: {:?} to {:?}]",
start, end
);
}
}
}
// Write trace event only if trace has at least one event
if let Some(trace_start_ts) = trace_start {
if !opt.exclude_traces {
tw.write_trace_action(
thread_id as u32,
trace_start_ts,
trace_end.unwrap(),
)?;
}
}
}
// Execution of an implementation
Message::Evaluation {
id,
value,
result_time,
} => {
if value.is_some() {
t.get_node(id).set_score(value.unwrap());
}
if !opt.exclude_evaluations {
tw.write_candidate_evaluate_action(id, result_time, value)?;
}
}
}
}
if !opt.exclude_traces {
let mut thread_ids_vec = Vec::<u32>::new();
for thr in thread_ids.iter() {
thread_ids_vec.push(*thr);
}
thread_ids_vec.sort();
// Write hierarchy of threads represented by a flat Aftermath
// hierarchy composed of one virtual root thread with one
// child per thread
tw.write_hierarchy(&thread_ids_vec)?;
// Write event mappings associating event collections with
// hierarchy nodes
tw.write_event_mappings(&thread_ids_vec)?;
}
// Write the reconstructed candidate tree
tw.write_candidates(&t)?;
Ok(())
}
| 36.973941 | 106 | 0.393798 |
14372955408fb1a2eca5b5a9c40e5a51a4b625ed | 5,345 | use engine_shared::newtypes::Blake2bHash;
use super::*;
use crate::{
error::{self, in_memory},
trie_store::operations::{scan, TrieScan},
};
fn check_scan<'a, R, S, E>(
correlation_id: CorrelationId,
environment: &'a R,
store: &S,
root_hash: &Blake2bHash,
key: &[u8],
) -> Result<(), E>
where
R: TransactionSource<'a, Handle = S::Handle>,
S: TrieStore<TestKey, TestValue>,
S::Error: From<R::Error> + std::fmt::Debug,
E: From<R::Error> + From<S::Error> + From<contract_ffi::bytesrepr::Error>,
{
let txn: R::ReadTransaction = environment.create_read_txn()?;
let root = store
.get(&txn, &root_hash)?
.expect("check_scan received an invalid root hash");
let TrieScan { mut tip, parents } = scan::<TestKey, TestValue, R::ReadTransaction, S, E>(
correlation_id,
&txn,
store,
key,
&root,
)?;
for (index, parent) in parents.into_iter().rev() {
let expected_tip_hash = {
let tip_bytes = tip.to_bytes().unwrap();
Blake2bHash::new(&tip_bytes)
};
match parent {
Trie::Leaf { .. } => panic!("parents should not contain any leaves"),
Trie::Node { pointer_block } => {
let pointer_tip_hash = pointer_block[<usize>::from(index)].map(|ptr| *ptr.hash());
assert_eq!(Some(expected_tip_hash), pointer_tip_hash);
tip = Trie::Node { pointer_block };
}
Trie::Extension { affix, pointer } => {
let pointer_tip_hash = pointer.hash().to_owned();
assert_eq!(expected_tip_hash, pointer_tip_hash);
tip = Trie::Extension { affix, pointer };
}
}
}
assert_eq!(root, tip);
txn.commit()?;
Ok(())
}
mod partial_tries {
use super::*;
#[test]
fn lmdb_scans_from_n_leaf_partial_trie_had_expected_results() {
for generator in &TEST_TRIE_GENERATORS {
let correlation_id = CorrelationId::new();
let (root_hash, tries) = generator().unwrap();
let context = LmdbTestContext::new(&tries).unwrap();
for leaf in TEST_LEAVES.iter() {
let leaf_bytes = leaf.to_bytes().unwrap();
check_scan::<_, _, error::Error>(
correlation_id,
&context.environment,
&context.store,
&root_hash,
&leaf_bytes,
)
.unwrap()
}
}
}
#[test]
fn in_memory_scans_from_n_leaf_partial_trie_had_expected_results() {
for generator in &TEST_TRIE_GENERATORS {
let correlation_id = CorrelationId::new();
let (root_hash, tries) = generator().unwrap();
let context = InMemoryTestContext::new(&tries).unwrap();
for leaf in TEST_LEAVES.iter() {
let leaf_bytes = leaf.to_bytes().unwrap();
check_scan::<_, _, in_memory::Error>(
correlation_id,
&context.environment,
&context.store,
&root_hash,
&leaf_bytes,
)
.unwrap()
}
}
}
}
mod full_tries {
use super::*;
#[test]
fn lmdb_scans_from_n_leaf_full_trie_had_expected_results() {
let correlation_id = CorrelationId::new();
let context = LmdbTestContext::new(EMPTY_HASHED_TEST_TRIES).unwrap();
let mut states: Vec<Blake2bHash> = Vec::new();
for (state_index, generator) in TEST_TRIE_GENERATORS.iter().enumerate() {
let (root_hash, tries) = generator().unwrap();
context.update(&tries).unwrap();
states.push(root_hash);
for state in &states[..state_index] {
for leaf in TEST_LEAVES.iter() {
let leaf_bytes = leaf.to_bytes().unwrap();
check_scan::<_, _, error::Error>(
correlation_id,
&context.environment,
&context.store,
state,
&leaf_bytes,
)
.unwrap()
}
}
}
}
#[test]
fn in_memory_scans_from_n_leaf_full_trie_had_expected_results() {
let correlation_id = CorrelationId::new();
let context = InMemoryTestContext::new(EMPTY_HASHED_TEST_TRIES).unwrap();
let mut states: Vec<Blake2bHash> = Vec::new();
for (state_index, generator) in TEST_TRIE_GENERATORS.iter().enumerate() {
let (root_hash, tries) = generator().unwrap();
context.update(&tries).unwrap();
states.push(root_hash);
for state in &states[..state_index] {
for leaf in TEST_LEAVES.iter() {
let leaf_bytes = leaf.to_bytes().unwrap();
check_scan::<_, _, in_memory::Error>(
correlation_id,
&context.environment,
&context.store,
state,
&leaf_bytes,
)
.unwrap()
}
}
}
}
}
| 33.198758 | 98 | 0.513564 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.