use alloc::vec::Vec;
use crate::allocation::AllocationError;
use crate::bytes::PayloadByteCount;
use crate::inspect::{RuleAction, RuleAnchor, RulePosition, RuleRepeat, RuleView};
use crate::materialized::{MaterializedBytes, OwnedRuleWitnessPayloadDomain};
use crate::source::SourceLineNumber;
#[derive(Debug, PartialEq, Eq)]
pub struct OwnedRulePayload {
bytes: MaterializedBytes<OwnedRuleWitnessPayloadDomain>,
}
impl OwnedRulePayload {
#[must_use]
pub fn as_slice(&self) -> &[u8] {
self.bytes.as_slice()
}
#[must_use]
pub fn into_raw_bytes(self) -> Vec<u8> {
self.bytes.into_raw_bytes()
}
#[must_use]
pub fn byte_count(&self) -> PayloadByteCount {
PayloadByteCount::new(self.bytes.len())
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.bytes.is_empty()
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct OwnedRuleWitness {
position: RulePosition,
line_number: SourceLineNumber,
repeat: RuleRepeat,
anchor: RuleAnchor,
lhs: OwnedRulePayload,
action: RuleAction<OwnedRulePayload>,
}
impl OwnedRuleWitness {
pub(crate) fn from_rule_view(rule: RuleView<'_>) -> Result<Self, AllocationError> {
let lhs = materialize_owned_rule_payload(rule.lhs())?;
let action = match rule.action() {
RuleAction::Replace(payload) => {
RuleAction::Replace(materialize_owned_rule_payload(payload)?)
}
RuleAction::MoveStart(payload) => {
RuleAction::MoveStart(materialize_owned_rule_payload(payload)?)
}
RuleAction::MoveEnd(payload) => {
RuleAction::MoveEnd(materialize_owned_rule_payload(payload)?)
}
RuleAction::Return(payload) => {
RuleAction::Return(materialize_owned_rule_payload(payload)?)
}
};
Ok(Self {
position: rule.position(),
line_number: rule.line_number(),
repeat: rule.repeat(),
anchor: rule.anchor(),
lhs,
action,
})
}
#[must_use]
pub const fn position(&self) -> RulePosition {
self.position
}
#[must_use]
pub const fn line_number(&self) -> SourceLineNumber {
self.line_number
}
#[must_use]
pub const fn repeat(&self) -> RuleRepeat {
self.repeat
}
#[must_use]
pub const fn anchor(&self) -> RuleAnchor {
self.anchor
}
#[must_use]
pub const fn lhs(&self) -> &OwnedRulePayload {
&self.lhs
}
#[must_use]
pub const fn action(&self) -> &RuleAction<OwnedRulePayload> {
&self.action
}
}
fn materialize_owned_rule_payload(
payload: crate::inspect::PayloadView<'_>,
) -> Result<OwnedRulePayload, AllocationError> {
Ok(OwnedRulePayload {
bytes: MaterializedBytes::from_owned_rule_payload(payload)?,
})
}