linera_witty/type_traits/implementations/
log.rs1use std::borrow::Cow;
7
8use frunk::{hlist_pat, HList};
9use log::Level;
10
11use crate::{
12 GuestPointer, InstanceWithMemory, Layout, Memory, Runtime, RuntimeError, RuntimeMemory,
13 WitLoad, WitStore, WitType,
14};
15
16impl WitType for Level {
17 const SIZE: u32 = 1;
18
19 type Layout = HList![i8];
20 type Dependencies = HList![];
21
22 fn wit_type_name() -> Cow<'static, str> {
23 "log-level".into()
24 }
25
26 fn wit_type_declaration() -> Cow<'static, str> {
27 concat!(
28 " enum log-level {\n",
29 " error,\n",
30 " warn,\n",
31 " info,\n",
32 " debug,\n",
33 " trace,\n",
34 " }\n",
35 )
36 .into()
37 }
38}
39
40impl WitLoad for Level {
41 fn load<Instance>(
42 memory: &Memory<'_, Instance>,
43 location: GuestPointer,
44 ) -> Result<Self, RuntimeError>
45 where
46 Instance: InstanceWithMemory,
47 <Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
48 {
49 match u8::load(memory, location)? {
50 0 => Ok(Level::Error),
51 1 => Ok(Level::Warn),
52 2 => Ok(Level::Info),
53 3 => Ok(Level::Debug),
54 4 => Ok(Level::Trace),
55 _ => unreachable!("Invalid log level"),
56 }
57 }
58
59 fn lift_from<Instance>(
60 hlist_pat![discriminant]: <Self::Layout as Layout>::Flat,
61 _memory: &Memory<'_, Instance>,
62 ) -> Result<Self, RuntimeError>
63 where
64 Instance: InstanceWithMemory,
65 <Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
66 {
67 match discriminant {
68 0 => Ok(Level::Error),
69 1 => Ok(Level::Warn),
70 2 => Ok(Level::Info),
71 3 => Ok(Level::Debug),
72 4 => Ok(Level::Trace),
73 _ => unreachable!("Invalid log level"),
74 }
75 }
76}
77
78impl WitStore for Level {
79 fn store<Instance>(
80 &self,
81 memory: &mut Memory<'_, Instance>,
82 location: GuestPointer,
83 ) -> Result<(), RuntimeError>
84 where
85 Instance: InstanceWithMemory,
86 <Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
87 {
88 let discriminant: i8 = match self {
89 Level::Error => 0,
90 Level::Warn => 1,
91 Level::Info => 2,
92 Level::Debug => 3,
93 Level::Trace => 4,
94 };
95
96 discriminant.store(memory, location)
97 }
98
99 fn lower<Instance>(
100 &self,
101 memory: &mut Memory<'_, Instance>,
102 ) -> Result<<Self::Layout as Layout>::Flat, RuntimeError>
103 where
104 Instance: InstanceWithMemory,
105 <Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
106 {
107 let discriminant: i8 = match self {
108 Level::Error => 0,
109 Level::Warn => 1,
110 Level::Info => 2,
111 Level::Debug => 3,
112 Level::Trace => 4,
113 };
114
115 discriminant.lower(memory)
116 }
117}