Skip to main content

amaru_kernel/cardano/
ordered_redeemer.rs

1// Copyright 2025 PRAGMA
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::{borrow::Cow, cmp::Ordering, ops::Deref};
16
17use crate::{AsIndex, Redeemer};
18
19/// A type that provides Ord and PartialOrd instance on redeemers, to allow storing them in binary
20/// trees in a controlled order (that matches Haskell's implementation).
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct OrderedRedeemer<'a>(Cow<'a, Redeemer>);
23
24impl Ord for OrderedRedeemer<'_> {
25    fn cmp(&self, other: &Self) -> Ordering {
26        match self.tag.as_index().cmp(&other.tag.as_index()) {
27            by_tag @ Ordering::Less | by_tag @ Ordering::Greater => by_tag,
28            Ordering::Equal => self.index.cmp(&other.index),
29        }
30    }
31}
32
33impl PartialOrd for OrderedRedeemer<'_> {
34    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
35        Some(self.cmp(other))
36    }
37}
38
39impl Deref for OrderedRedeemer<'_> {
40    type Target = Redeemer;
41
42    fn deref(&self) -> &Self::Target {
43        &self.0
44    }
45}
46
47impl<'a> From<Cow<'a, Redeemer>> for OrderedRedeemer<'a> {
48    fn from(value: Cow<'a, Redeemer>) -> Self {
49        Self(value)
50    }
51}
52
53impl From<Redeemer> for OrderedRedeemer<'static> {
54    fn from(value: Redeemer) -> Self {
55        Self(Cow::Owned(value))
56    }
57}
58
59impl<'a> From<&'a Redeemer> for OrderedRedeemer<'a> {
60    fn from(value: &'a Redeemer) -> Self {
61        Self(Cow::Borrowed(value))
62    }
63}