Merge pull request #49 from TheBlueMatt/main
[ldk-c-bindings] / lightning-c-bindings / src / lightning / util / logger.rs
1 // This file is Copyright its original authors, visible in version control
2 // history and in the source files from which this was generated.
3 //
4 // This file is licensed under the license available in the LICENSE or LICENSE.md
5 // file in the root of this repository or, if no such file exists, the same
6 // license as that which applies to the original source files from which this
7 // source was automatically generated.
8
9 //! Log traits live here, which are called throughout the library to provide useful information for
10 //! debugging purposes.
11 //!
12 //! There is currently 2 ways to filter log messages. First one, by using compilation features, e.g \"max_level_off\".
13 //! The second one, client-side by implementing check against Record Level field.
14 //! Each module may have its own Logger or share one.
15
16 use std::str::FromStr;
17 use std::ffi::c_void;
18 use core::convert::Infallible;
19 use bitcoin::hashes::Hash;
20 use crate::c_types::*;
21
22 /// An enum representing the available verbosity levels of the logger.
23 #[must_use]
24 #[derive(Clone)]
25 #[repr(C)]
26 pub enum Level {
27         /// Designates very low priority, often extremely verbose, information
28         Trace,
29         /// Designates lower priority information
30         Debug,
31         /// Designates useful information
32         Info,
33         /// Designates hazardous situations
34         Warn,
35         /// Designates very serious errors
36         Error,
37 }
38 use lightning::util::logger::Level as nativeLevel;
39 impl Level {
40         #[allow(unused)]
41         pub(crate) fn to_native(&self) -> nativeLevel {
42                 match self {
43                         Level::Trace => nativeLevel::Trace,
44                         Level::Debug => nativeLevel::Debug,
45                         Level::Info => nativeLevel::Info,
46                         Level::Warn => nativeLevel::Warn,
47                         Level::Error => nativeLevel::Error,
48                 }
49         }
50         #[allow(unused)]
51         pub(crate) fn into_native(self) -> nativeLevel {
52                 match self {
53                         Level::Trace => nativeLevel::Trace,
54                         Level::Debug => nativeLevel::Debug,
55                         Level::Info => nativeLevel::Info,
56                         Level::Warn => nativeLevel::Warn,
57                         Level::Error => nativeLevel::Error,
58                 }
59         }
60         #[allow(unused)]
61         pub(crate) fn from_native(native: &nativeLevel) -> Self {
62                 match native {
63                         nativeLevel::Trace => Level::Trace,
64                         nativeLevel::Debug => Level::Debug,
65                         nativeLevel::Info => Level::Info,
66                         nativeLevel::Warn => Level::Warn,
67                         nativeLevel::Error => Level::Error,
68                 }
69         }
70         #[allow(unused)]
71         pub(crate) fn native_into(native: nativeLevel) -> Self {
72                 match native {
73                         nativeLevel::Trace => Level::Trace,
74                         nativeLevel::Debug => Level::Debug,
75                         nativeLevel::Info => Level::Info,
76                         nativeLevel::Warn => Level::Warn,
77                         nativeLevel::Error => Level::Error,
78                 }
79         }
80 }
81 /// Creates a copy of the Level
82 #[no_mangle]
83 pub extern "C" fn Level_clone(orig: &Level) -> Level {
84         orig.clone()
85 }
86 #[no_mangle]
87 /// Utility method to constructs a new Trace-variant Level
88 pub extern "C" fn Level_trace() -> Level {
89         Level::Trace}
90 #[no_mangle]
91 /// Utility method to constructs a new Debug-variant Level
92 pub extern "C" fn Level_debug() -> Level {
93         Level::Debug}
94 #[no_mangle]
95 /// Utility method to constructs a new Info-variant Level
96 pub extern "C" fn Level_info() -> Level {
97         Level::Info}
98 #[no_mangle]
99 /// Utility method to constructs a new Warn-variant Level
100 pub extern "C" fn Level_warn() -> Level {
101         Level::Warn}
102 #[no_mangle]
103 /// Utility method to constructs a new Error-variant Level
104 pub extern "C" fn Level_error() -> Level {
105         Level::Error}
106 /// Checks if two Levels contain equal inner contents.
107 /// This ignores pointers and is_owned flags and looks at the values in fields.
108 #[no_mangle]
109 pub extern "C" fn Level_eq(a: &Level, b: &Level) -> bool {
110         if &a.to_native() == &b.to_native() { true } else { false }
111 }
112 /// Checks if two Levels contain equal inner contents.
113 #[no_mangle]
114 pub extern "C" fn Level_hash(o: &Level) -> u64 {
115         // Note that we'd love to use std::collections::hash_map::DefaultHasher but it's not in core
116         #[allow(deprecated)]
117         let mut hasher = core::hash::SipHasher::new();
118         std::hash::Hash::hash(&o.to_native(), &mut hasher);
119         std::hash::Hasher::finish(&hasher)
120 }
121 /// Returns the most verbose logging level.
122 #[must_use]
123 #[no_mangle]
124 pub extern "C" fn Level_max() -> crate::lightning::util::logger::Level {
125         let mut ret = lightning::util::logger::Level::max();
126         crate::lightning::util::logger::Level::native_into(ret)
127 }
128
129
130 use lightning::util::logger::Record as nativeRecordImport;
131 pub(crate) type nativeRecord = nativeRecordImport<'static>;
132
133 /// A Record, unit of logging output with Metadata to enable filtering
134 /// Module_path, file, line to inform on log's source
135 #[must_use]
136 #[repr(C)]
137 pub struct Record {
138         /// A pointer to the opaque Rust object.
139
140         /// Nearly everywhere, inner must be non-null, however in places where
141         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
142         pub inner: *mut nativeRecord,
143         /// Indicates that this is the only struct which contains the same pointer.
144
145         /// Rust functions which take ownership of an object provided via an argument require
146         /// this to be true and invalidate the object pointed to by inner.
147         pub is_owned: bool,
148 }
149
150 impl Drop for Record {
151         fn drop(&mut self) {
152                 if self.is_owned && !<*mut nativeRecord>::is_null(self.inner) {
153                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
154                 }
155         }
156 }
157 /// Frees any resources used by the Record, if is_owned is set and inner is non-NULL.
158 #[no_mangle]
159 pub extern "C" fn Record_free(this_obj: Record) { }
160 #[allow(unused)]
161 /// Used only if an object of this type is returned as a trait impl by a method
162 pub(crate) extern "C" fn Record_free_void(this_ptr: *mut c_void) {
163         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeRecord); }
164 }
165 #[allow(unused)]
166 impl Record {
167         pub(crate) fn get_native_ref(&self) -> &'static nativeRecord {
168                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
169         }
170         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeRecord {
171                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
172         }
173         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
174         pub(crate) fn take_inner(mut self) -> *mut nativeRecord {
175                 assert!(self.is_owned);
176                 let ret = ObjOps::untweak_ptr(self.inner);
177                 self.inner = std::ptr::null_mut();
178                 ret
179         }
180 }
181 /// The verbosity level of the message.
182 #[no_mangle]
183 pub extern "C" fn Record_get_level(this_ptr: &Record) -> crate::lightning::util::logger::Level {
184         let mut inner_val = &mut this_ptr.get_native_mut_ref().level;
185         crate::lightning::util::logger::Level::from_native(inner_val)
186 }
187 /// The verbosity level of the message.
188 #[no_mangle]
189 pub extern "C" fn Record_set_level(this_ptr: &mut Record, mut val: crate::lightning::util::logger::Level) {
190         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.level = val.into_native();
191 }
192 /// The message body.
193 #[no_mangle]
194 pub extern "C" fn Record_get_args(this_ptr: &Record) -> crate::c_types::Str {
195         let mut inner_val = &mut this_ptr.get_native_mut_ref().args;
196         inner_val.as_str().into()
197 }
198 /// The message body.
199 #[no_mangle]
200 pub extern "C" fn Record_set_args(this_ptr: &mut Record, mut val: crate::c_types::Str) {
201         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.args = val.into_string();
202 }
203 /// The module path of the message.
204 #[no_mangle]
205 pub extern "C" fn Record_get_module_path(this_ptr: &Record) -> crate::c_types::Str {
206         let mut inner_val = &mut this_ptr.get_native_mut_ref().module_path;
207         inner_val.into()
208 }
209 /// The module path of the message.
210 #[no_mangle]
211 pub extern "C" fn Record_set_module_path(this_ptr: &mut Record, mut val: crate::c_types::Str) {
212         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.module_path = val.into_str();
213 }
214 /// The source file containing the message.
215 #[no_mangle]
216 pub extern "C" fn Record_get_file(this_ptr: &Record) -> crate::c_types::Str {
217         let mut inner_val = &mut this_ptr.get_native_mut_ref().file;
218         inner_val.into()
219 }
220 /// The source file containing the message.
221 #[no_mangle]
222 pub extern "C" fn Record_set_file(this_ptr: &mut Record, mut val: crate::c_types::Str) {
223         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.file = val.into_str();
224 }
225 /// The line containing the message.
226 #[no_mangle]
227 pub extern "C" fn Record_get_line(this_ptr: &Record) -> u32 {
228         let mut inner_val = &mut this_ptr.get_native_mut_ref().line;
229         *inner_val
230 }
231 /// The line containing the message.
232 #[no_mangle]
233 pub extern "C" fn Record_set_line(this_ptr: &mut Record, mut val: u32) {
234         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.line = val;
235 }
236 impl Clone for Record {
237         fn clone(&self) -> Self {
238                 Self {
239                         inner: if <*mut nativeRecord>::is_null(self.inner) { std::ptr::null_mut() } else {
240                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
241                         is_owned: true,
242                 }
243         }
244 }
245 #[allow(unused)]
246 /// Used only if an object of this type is returned as a trait impl by a method
247 pub(crate) extern "C" fn Record_clone_void(this_ptr: *const c_void) -> *mut c_void {
248         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRecord)).clone() })) as *mut c_void
249 }
250 #[no_mangle]
251 /// Creates a copy of the Record
252 pub extern "C" fn Record_clone(orig: &Record) -> Record {
253         orig.clone()
254 }
255 /// A trait encapsulating the operations required of a logger
256 #[repr(C)]
257 pub struct Logger {
258         /// An opaque pointer which is passed to your function implementations as an argument.
259         /// This has no meaning in the LDK, and can be NULL or any other value.
260         pub this_arg: *mut c_void,
261         /// Logs the `Record`
262         pub log: extern "C" fn (this_arg: *const c_void, record: &crate::lightning::util::logger::Record),
263         /// Frees any resources associated with this object given its this_arg pointer.
264         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
265         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
266 }
267 unsafe impl Send for Logger {}
268 unsafe impl Sync for Logger {}
269 #[no_mangle]
270 pub(crate) extern "C" fn Logger_clone_fields(orig: &Logger) -> Logger {
271         Logger {
272                 this_arg: orig.this_arg,
273                 log: Clone::clone(&orig.log),
274                 free: Clone::clone(&orig.free),
275         }
276 }
277
278 use lightning::util::logger::Logger as rustLogger;
279 impl rustLogger for Logger {
280         fn log(&self, mut record: &lightning::util::logger::Record) {
281                 (self.log)(self.this_arg, &crate::lightning::util::logger::Record { inner: unsafe { ObjOps::nonnull_ptr_to_inner((record as *const lightning::util::logger::Record<'_, >) as *mut _) }, is_owned: false })
282         }
283 }
284
285 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
286 // directly as a Deref trait in higher-level structs:
287 impl std::ops::Deref for Logger {
288         type Target = Self;
289         fn deref(&self) -> &Self {
290                 self
291         }
292 }
293 /// Calls the free function if one is set
294 #[no_mangle]
295 pub extern "C" fn Logger_free(this_ptr: Logger) { }
296 impl Drop for Logger {
297         fn drop(&mut self) {
298                 if let Some(f) = self.free {
299                         f(self.this_arg);
300                 }
301         }
302 }