alma 0.1.1

A Bevy-native modal text editor with Vim-style navigation.
Documentation
//! Guest decode limits derived from runtime policy.

use crate::plugin::ValidatedPluginRuntimeLimits;
use std::{
    fmt::{Debug, Formatter},
    num::NonZeroU64,
};

/// Decode limits derived from validated runtime policy.
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct GuestDecodeLimits {
    /// Guest string byte cap.
    string_bytes: NonZeroU64,
    /// Guest payload byte cap.
    payload_bytes: NonZeroU64,
    /// Guest scalar count cap.
    count: NonZeroU64,
}

impl GuestDecodeLimits {
    /// Uses validated runtime policy for all guest-owned byte fields.
    #[must_use]
    pub const fn from_validated_runtime(limits: ValidatedPluginRuntimeLimits) -> Self {
        let max_message_bytes = limits.max_message_byte_limit();
        Self {
            string_bytes: max_message_bytes,
            payload_bytes: max_message_bytes,
            count: max_message_bytes,
        }
    }

    /// Builds explicit limits from already-validated non-zero caps.
    #[must_use]
    pub const fn new(
        max_string_bytes: NonZeroU64,
        max_payload_bytes: NonZeroU64,
        max_count: NonZeroU64,
    ) -> Self {
        Self {
            string_bytes: max_string_bytes,
            payload_bytes: max_payload_bytes,
            count: max_count,
        }
    }

    /// Returns the maximum accepted string bytes.
    #[must_use]
    pub const fn max_string_bytes(self) -> u64 {
        self.string_bytes.get()
    }

    /// Returns the maximum accepted payload bytes.
    #[must_use]
    pub const fn max_payload_bytes(self) -> u64 {
        self.payload_bytes.get()
    }

    /// Returns the maximum accepted payload bytes as a non-zero proof.
    #[must_use]
    pub(in crate::plugin) const fn max_payload_byte_limit(self) -> NonZeroU64 {
        self.payload_bytes
    }

    /// Returns the maximum accepted scalar count.
    #[must_use]
    pub const fn max_count(self) -> u64 {
        self.count.get()
    }
}

impl Default for GuestDecodeLimits {
    fn default() -> Self {
        Self::from_validated_runtime(ValidatedPluginRuntimeLimits::default())
    }
}

impl Debug for GuestDecodeLimits {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("GuestDecodeLimits")
            .field("string_bytes", &self.max_string_bytes())
            .field("payload_bytes", &self.max_payload_bytes())
            .field("count", &self.max_count())
            .finish()
    }
}