1use extism_convert::{FromBytes, Json, ToBytes};
2use serde::{Deserialize, Serialize};
34use crate::ValueKind;
56#[derive(Clone, Serialize, Deserialize, FromBytes, ToBytes)]
7#[encoding(Json)]
8pub struct TranslationResult {
9pub val: ValueRepr,
10pub subfields: Vec<SubFieldTranslationResult>,
11pub kind: ValueKind,
12}
1314/// The representation of the value, compound values can be
15/// be represented by the repr of their subfields
16#[derive(Clone, Serialize, Deserialize)]
17pub enum ValueRepr {
18 Bit(char),
19/// The value is `.0` raw bits, and can be translated by further translators
20Bits(u64, String),
21/// The value is exactly the specified string
22String(String),
23/// Represent the value as (f1, f2, f3...)
24Tuple,
25/// Represent the value as {f1: v1, f2: v2, f3: v3...}
26Struct,
27/// Represent as a spade-like enum with the specified field being shown.
28 /// The index is the index of the option which is currently selected, the name is
29 /// the name of that option to avoid having to look that up
30Enum {
31 idx: usize,
32 name: String,
33 },
34/// Represent the value as [f1, f2, f3...]
35Array,
36/// The variable value is not present. This is used to draw variables which are
37 /// validated by other variables.
38NotPresent,
39}
4041#[derive(Clone, Serialize, Deserialize)]
42pub struct SubFieldFlatTranslationResult {
43pub names: Vec<String>,
44pub value: Option<TranslatedValue>,
45}
4647// A tree of format results for a variable, to be flattened into `SubFieldFlatTranslationResult`s
48pub struct HierFormatResult {
49pub names: Vec<String>,
50pub this: Option<TranslatedValue>,
51/// A list of subfields of arbitrary depth, flattened to remove hierarchy.
52 /// i.e. `{a: {b: 0}, c: 0}` is flattened to `vec![a: {b: 0}, [a, b]: 0, c: 0]`
53pub fields: Vec<HierFormatResult>,
54}
5556impl HierFormatResult {
57pub fn collect_into(self, into: &mut Vec<SubFieldFlatTranslationResult>) {
58 into.push(SubFieldFlatTranslationResult {
59 names: self.names,
60 value: self.this,
61 });
62self.fields.into_iter().for_each(|r| r.collect_into(into));
63 }
64}
6566#[derive(Clone, Serialize, Deserialize)]
67pub struct SubFieldTranslationResult {
68pub name: String,
69pub result: TranslationResult,
70}
7172impl SubFieldTranslationResult {
73pub fn new(name: impl ToString, result: TranslationResult) -> Self {
74 SubFieldTranslationResult {
75 name: name.to_string(),
76 result,
77 }
78 }
79}
8081#[derive(Clone, PartialEq, Serialize, Deserialize)]
82pub struct TranslatedValue {
83pub value: String,
84pub kind: ValueKind,
85}
8687impl TranslatedValue {
88pub fn from_basic_translate(result: (String, ValueKind)) -> Self {
89 TranslatedValue {
90 value: result.0,
91 kind: result.1,
92 }
93 }
9495pub fn new(value: impl ToString, kind: ValueKind) -> Self {
96 TranslatedValue {
97 value: value.to_string(),
98 kind,
99 }
100 }
101}