Struct gstd::Reservations

source ·
pub struct Reservations(/* private fields */);
Expand description

Reservation manager.

The manager is used to control multiple gas reservations across executions. It can be used when you only care about reserved amounts and not concrete ReservationIds.

§Examples

Create gas reservations inside init and use them inside handle.

use gstd::{msg, prelude::*, Reservations};

static mut RESERVATIONS: Reservations = Reservations::new();

#[no_mangle]
extern "C" fn init() {
    unsafe {
        RESERVATIONS
            .reserve(200_000, 50)
            .expect("failed to reserve gas");
        RESERVATIONS
            .reserve(100_000, 100)
            .expect("failed to reserve gas");
        RESERVATIONS
            .reserve(50_000, 30)
            .expect("failed to reserve gas");
    }
}

#[no_mangle]
extern "C" fn handle() {
    let reservation = unsafe { RESERVATIONS.try_take_reservation(100_000) };
    if let Some(reservation) = reservation {
        msg::send_bytes_from_reservation(
            reservation.id(),
            msg::source(),
            "send_bytes_from_reservation",
            0,
        )
        .expect("Failed to send message from reservation");
    } else {
        msg::send_bytes(msg::source(), "send_bytes", 0).expect("Failed to send message");
    }
}

§See also

  • ReservationId is used to reserve and unreserve gas for program execution later.
  • Reservation stores some additional data along with ReservationId.

Implementations§

source§

impl Reservations

source

pub const fn new() -> Self

Create a new Reservations struct.

source

pub fn reserve(&mut self, amount: u64, duration: u32) -> Result<()>

Reserve the amount of gas for further usage.

duration is the block count within which the reservation must be used.

§Underlying logics

Executes for O(logN)..O(N), where N is a number of stored reservations.

All the reservations are kept sorted by amount in ascending order(when amount is the same, they’re sorted by time when they expire) when inserted, so the closer inserted element to the beginning of the underlying Vec the closer execution time will be to O(N).

Also, when the underlying Vec will allocate new memory the attempt to clean expired reservations occurs to avoid memory allocations.

source

pub fn try_take_reservation(&mut self, amount: u64) -> Option<Reservation>

Find the appropriate reservation with reserved amount greater than or equal to amount.

If such a reservation is found, Reservation is returned.

§Underlying logics

Executes for O(logN)..O(N), where N is amount of stored reservations. When there’s many expired reservations execution time is closer to O(N).

All the reservations are sorted by their amount and then by the time when they’ll expire (both are in ascending order) in underlying Vec, so when one’s trying to take reservation, reservation with the least possible amount is found and if it’s already expired, the search to the end of underlying Vec occurs. After that, all the expired reservations that were found in process of search are cleaned out.

§See also
  • ReservationId is used to reserve and unreserve gas amount for program execution later.
  • Reservation stores some additional data along with ReservationId.
source

pub fn count_valid(&self) -> usize

Returns an amount of the stored reservations that aren’t expired at this time.

Executes for O(N) where N is amount of stored reservations.

source

pub fn count_all(&self) -> usize

Returns an amount of all the stored reservations (including expired).

Trait Implementations§

source§

impl Clone for Reservations

source§

fn clone(&self) -> Reservations

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Reservations

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for Reservations

source§

fn decode<__CodecInputEdqy: Input>( __codec_input_edqy: &mut __CodecInputEdqy, ) -> Result<Self, Error>

Attempt to deserialise the value from input.
§

fn decode_into<I>( input: &mut I, dst: &mut MaybeUninit<Self>, ) -> Result<DecodeFinished, Error>
where I: Input,

Attempt to deserialize the value from input into a pre-allocated piece of memory. Read more
§

fn skip<I>(input: &mut I) -> Result<(), Error>
where I: Input,

Attempt to skip the encoded value from input. Read more
§

fn encoded_fixed_size() -> Option<usize>

Returns the fixed encoded size of the type. Read more
source§

impl Default for Reservations

source§

fn default() -> Reservations

Returns the “default value” for a type. Read more
source§

impl Encode for Reservations

source§

fn size_hint(&self) -> usize

If possible give a hint of expected size of the encoding. Read more
source§

fn encode_to<__CodecOutputEdqy: Output + ?Sized>( &self, __codec_dest_edqy: &mut __CodecOutputEdqy, )

Convert self to a slice and append it to the destination.
source§

fn encode(&self) -> Vec<u8>

Convert self to an owned vector.
source§

fn using_encoded<__CodecOutputReturn, __CodecUsingEncodedCallback: FnOnce(&[u8]) -> __CodecOutputReturn>( &self, f: __CodecUsingEncodedCallback, ) -> __CodecOutputReturn

Convert self to a slice and then invoke the given closure with it.
§

fn encoded_size(&self) -> usize

Calculates the encoded size. Read more
source§

impl Hash for Reservations

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl TypeInfo for Reservations

§

type Identity = Reservations

The type identifying for which type info is provided. Read more
source§

fn type_info() -> Type

Returns the static type identifier for Self.
source§

impl EncodeLike for Reservations

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where T: Clone,

source§

default unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
§

impl<T> DecodeAll for T
where T: Decode,

§

fn decode_all(input: &mut &[u8]) -> Result<T, Error>

Decode Self and consume all of the given input data. Read more
§

impl<T> DecodeLimit for T
where T: Decode,

§

fn decode_all_with_depth_limit( limit: u32, input: &mut &[u8], ) -> Result<T, Error>

Decode Self and consume all of the given input data. Read more
§

fn decode_with_depth_limit<I>(limit: u32, input: &mut I) -> Result<T, Error>
where I: Input,

Decode Self with the given maximum recursion depth and advance input by the number of bytes consumed. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> KeyedVec for T
where T: Codec,

§

fn to_keyed_vec(&self, prepend_key: &[u8]) -> Vec<u8>

Return an encoding of Self prepended by given slice.
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<S> Codec for S
where S: Decode + Encode,

§

impl<T> EncodeLike<&&T> for T
where T: Encode,

§

impl<T> EncodeLike<&T> for T
where T: Encode,

§

impl<T> EncodeLike<&mut T> for T
where T: Encode,

§

impl<T> EncodeLike<Arc<T>> for T
where T: Encode,

§

impl<T> EncodeLike<Box<T>> for T
where T: Encode,

§

impl<'a, T> EncodeLike<Cow<'a, T>> for T
where T: ToOwned + Encode,

§

impl<T> EncodeLike<Rc<T>> for T
where T: Encode,

§

impl<S> FullCodec for S
where S: Decode + FullEncode,

§

impl<S> FullEncode for S
where S: Encode + EncodeLike,

§

impl<T> JsonSchemaMaybe for T

§

impl<T> StaticTypeInfo for T
where T: TypeInfo + 'static,