Skip to main content

macroonz_compiler/kind/
type_contract.rs

1//! The compiler-owned roster contracts and how a disposition-set completion refusal reads.
2
3use super::types::{
4    Answer, CanonicalContent, Destination, DispositionSetError, NoQuestions, Question, Role,
5    SoleRole,
6};
7use crate::identity::encode_bytes;
8use core::fmt;
9
10/// One row's position in its roster, or the roster's length where the roster does not carry it.
11pub(super) fn slot_in<T: Copy + Eq>(roster: &[T], row: T) -> u16 {
12    let position = roster
13        .iter()
14        .position(|other| *other == row)
15        .unwrap_or(roster.len());
16    u16::try_from(position).unwrap_or(u16::MAX)
17}
18
19/// Find one roster row by the name its declaration assigned it.
20pub(crate) fn roster_row<Row: Copy>(
21    roster: &[Row],
22    name: fn(Row) -> &'static str,
23    sought: &str,
24) -> Option<Row> {
25    roster.iter().copied().find(|row| name(*row) == sought)
26}
27
28impl CanonicalContent for () {
29    fn encode_content_into(&self, _into: &mut Vec<u8>) {}
30}
31
32impl CanonicalContent for &'static str {
33    fn encode_content_into(&self, into: &mut Vec<u8>) {
34        encode_bytes(self.as_bytes(), into);
35    }
36}
37
38impl Role for SoleRole {
39    const ALL: &'static [Self] = &[Self::Sole];
40
41    fn name(self) -> &'static str {
42        "sole"
43    }
44
45    fn destination(self) -> Destination {
46        Destination::DeclarationSite
47    }
48}
49
50impl Question for NoQuestions {
51    const ALL: &'static [Self] = &[];
52
53    type Answer = Self;
54
55    fn name(self) -> &'static str {
56        match self {}
57    }
58}
59
60impl Answer for NoQuestions {
61    type Question = Self;
62
63    fn question(&self) -> Self {
64        match *self {}
65    }
66
67    fn encode_into(&self, _into: &mut Vec<u8>) {
68        match *self {}
69    }
70
71    fn human(&self) -> String {
72        match *self {}
73    }
74}
75
76impl fmt::Display for DispositionSetError {
77    fn fmt(&self, into: &mut fmt::Formatter<'_>) -> fmt::Result {
78        match self {
79            Self::CountMismatch { expected, observed } => write!(
80                into,
81                "the kind set declares {expected} names but its disposition record surrendered {observed} rows"
82            ),
83            Self::KindMismatch { expected, observed } => write!(
84                into,
85                "the kind set declares `{expected}` at this position but its disposition record surrendered `{observed}`"
86            ),
87        }
88    }
89}
90
91impl core::error::Error for DispositionSetError {}