wifi-caddy 0.1.0

Platform-agnostic config storage traits, HTTP config portal, and form generation for WiFi configuration managers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
//! Config storage traits and types (load/store, group API, form generation).
//!
//! Implementations are generated by the wifi-caddy-proc derive macro.

#![warn(missing_docs)]
#![allow(async_fn_in_trait)]

extern crate alloc;

use alloc::string::String;
use core::fmt;

/// Error type for config storage operations.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ConfigError {
    /// Buffer too small for serialization
    BufferTooSmall(usize),
    /// Invalid UTF-8 in string data
    Utf8,
    /// Invalid data for type conversion
    InvalidData,
    /// Backend storage error
    Backend,
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ConfigError::BufferTooSmall(n) => write!(f, "buffer too small: need {} bytes", n),
            ConfigError::Utf8 => write!(f, "invalid UTF-8"),
            ConfigError::InvalidData => write!(f, "invalid data"),
            ConfigError::Backend => write!(f, "backend storage error"),
        }
    }
}

/// Maximum size for a stored value (used by default implementations).
pub const MAX_VALUE_SIZE: usize = 256;

/// Backend abstraction for config key-value storage.
///
/// Implement only `get_bytes` and `store_bytes`; the typed accessors are
/// provided via default implementations using `ConfigValue`.
/// Keys are 64-bit hashes of field names for stability across struct changes.
#[allow(async_fn_in_trait)]
pub trait ConfigStorage {
    /// Fetch raw bytes for a key. Writes into `buf`, returns `Some(len)` if
    /// found, `None` if not found.
    async fn load_bytes(&mut self, key: u64, buf: &mut [u8]) -> Result<Option<usize>, ConfigError>;

    /// Store raw bytes for a key.
    async fn store_bytes(&mut self, key: u64, bytes: &[u8]) -> Result<(), ConfigError>;

    /// Fetch a value of type `T` for a key. Returns `None` if not found.
    async fn get_value<T: ConfigValue>(&mut self, key: u64) -> Result<Option<T>, ConfigError> {
        let mut buf = [0u8; MAX_VALUE_SIZE];
        match self.load_bytes(key, &mut buf).await? {
            Some(len) => Ok(Some(T::from_bytes(&buf[..len])?)),
            None => Ok(None),
        }
    }

    /// Store a value of type `T` for a key.
    async fn set_value<T: ConfigValue>(&mut self, key: u64, value: &T) -> Result<(), ConfigError> {
        let mut buf = [0u8; MAX_VALUE_SIZE];
        let len = value.to_bytes(&mut buf)?;
        self.store_bytes(key, &buf[..len]).await
    }
}

/// Trait for config types that can be loaded from and stored to ConfigStorage.
///
/// Implementations are typically generated by the ConfigStore derive macro.
#[doc(hidden)]
#[allow(async_fn_in_trait)]
pub trait ConfigLoadStore {
    /// Load config from storage. Missing keys use default values.
    async fn load_from<S: ConfigStorage>(storage: &mut S) -> Result<Self, ConfigError>
    where
        Self: Sized;

    /// Store config to storage.
    async fn store_to<S: ConfigStorage>(&self, storage: &mut S) -> Result<(), ConfigError>;
}

/// Trait for the "changed set" returned by `set_group_json` / `set_field`.
/// Allows the HTTP layer to persist only when something changed (e.g. `!changed.is_empty()`).
#[doc(hidden)]
pub trait ConfigChangedSet {
    /// Returns true if no variants are in the set.
    fn is_empty(&self) -> bool;
}

impl<T: enumset::EnumSetType> ConfigChangedSet for enumset::EnumSet<T> {
    fn is_empty(&self) -> bool {
        enumset::EnumSet::is_empty(self)
    }
}

/// Trait for config types that expose named groups as JSON for GET/set for POST.
///
/// Implementations are generated by the wifi-caddy-proc derive.
#[doc(hidden)]
pub trait ConfigApi {
    /// Error type for get/set (e.g. serialization or unknown group).
    type Error: core::fmt::Display;

    /// Type representing which config "kinds" changed (e.g. `EnumSet<ConfigChange>`).
    /// Only variants for fields whose value actually changed are included.
    type ChangedSet: ConfigChangedSet;

    /// Serialize the given group into JSON; write into `buf`, return byte count.
    fn get_group_json(&self, group: &str, buf: &mut [u8]) -> Result<usize, Self::Error>;

    /// Parse `json`, apply to this config for the given group, and return the set of
    /// variants that actually changed (compare current vs new per field before applying).
    fn set_group_json(&mut self, group: &str, json: &str) -> Result<Self::ChangedSet, Self::Error>;

    /// Set a single field by key. Returns `Ok(Some(changed))` with the set of variants
    /// that changed (at most one), or `Ok(None)` if key/value invalid. Only includes
    /// a variant when the value actually changed.
    fn set_field(
        &mut self,
        key: &str,
        value: &str,
    ) -> Result<Option<Self::ChangedSet>, Self::Error>;
}

/// Trait for config types that support get-by-string-key (used by generic HTTP config UI).
#[doc(hidden)]
pub trait ConfigGet {
    /// Return the value for the given key, or `None` if unknown.
    fn get(&self, key: &str) -> Option<String>;
}

/// Kind of JS form save line for a config value (used in const segment arrays).
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum JsSaveKind {
    /// String: `formData.get(...) ?? ""`
    String = 0,
    /// Integer: `parseInt(formData.get(...), 10)`
    Int = 1,
    /// Float: `parseFloat(formData.get(...))`
    Float = 2,
}

/// Trait for config types that have generated form HTML and JavaScript.
///
/// Implementations are generated by the wifi-caddy-proc derive.
/// Returns const segment arrays so the response can be streamed without allocation.
#[doc(hidden)]
pub trait ConfigFormGen {
    /// Returns the list of page names (in order). Used for tab bar and multi-page UI.
    fn page_names() -> &'static [&'static str]
    where
        Self: Sized;

    /// Returns the form body HTML segments for the given group, or `None` if unknown.
    /// Segments are written directly to the response (no String allocation).
    fn html_segments_for_group(group: &str) -> Option<&'static [&'static str]>
    where
        Self: Sized;

    /// Returns the form JavaScript segments for the given group, or `None` if unknown.
    /// Segments are written directly to the response (no String allocation).
    fn js_segments_for_group(group: &str) -> Option<&'static [&'static str]>
    where
        Self: Sized;
}

/// Trait for types that can be stored and loaded from key-value config storage.
///
/// Uses little-endian byte order for numeric types and UTF-8 for strings.
pub trait ConfigValue: core::str::FromStr + core::fmt::Display {
    /// Return type for generated generic getters (e.g., `u32` vs `&'a String`).
    ///
    /// When the `#[derive(WifiCaddyConfig)]` macro generates getter methods for fields,
    /// it uses this associated type to determine the method's return type. This allows
    /// primitive types like `u32` to be returned by value (copied), while avoiding copies
    /// for complex types like `String` by returning a reference (`&'a String`).
    ///
    /// For a custom primitive `T`, set `type Getter<'a> = T;`.
    /// For a custom heap type `T`, set `type Getter<'a> = &'a T;`.
    type Getter<'a>
    where
        Self: 'a;

    /// Extract the getter return value from a reference to the type.
    ///
    /// The macro generates `config_storage::ConfigValue::to_getter(&self.field_name)`,
    /// ensuring it evaluates to `Self::Getter<'a>`.
    ///
    /// For a custom primitive `T`, return `*self`.
    /// For a custom heap type `T`, return `self`.
    fn to_getter<'a>(&'a self) -> Self::Getter<'a>;

    /// Serialize self into the buffer. Returns number of bytes written.
    fn to_bytes(&self, buf: &mut [u8]) -> Result<usize, ConfigError>;

    /// Deserialize from bytes.
    fn from_bytes(bytes: &[u8]) -> Result<Self, ConfigError>
    where
        Self: Sized;

    /// The default HTML input type when rendered in a form (e.g., "text", "number").
    const DEFAULT_INPUT_TYPE: &'static str = "number";

    /// Whether this type represents a floating point number (affects step attribute and JS save line).
    const IS_FLOAT: bool = false;

    /// JS form save kind for const segment arrays (which save line to emit).
    const JS_SAVE_KIND: JsSaveKind = JsSaveKind::Int;
}

impl ConfigValue for u8 {
    type Getter<'a> = u8;
    fn to_getter<'a>(&'a self) -> Self::Getter<'a> {
        *self
    }

    fn to_bytes(&self, buf: &mut [u8]) -> Result<usize, ConfigError> {
        if buf.is_empty() {
            return Err(ConfigError::BufferTooSmall(1));
        }
        buf[0] = *self;
        Ok(1)
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self, ConfigError> {
        if bytes.is_empty() {
            return Err(ConfigError::BufferTooSmall(1));
        }
        Ok(bytes[0])
    }
}

impl ConfigValue for u16 {
    type Getter<'a> = u16;
    fn to_getter<'a>(&'a self) -> Self::Getter<'a> {
        *self
    }

    fn to_bytes(&self, buf: &mut [u8]) -> Result<usize, ConfigError> {
        if buf.len() < 2 {
            return Err(ConfigError::BufferTooSmall(2));
        }
        buf[0..2].copy_from_slice(&self.to_le_bytes());
        Ok(2)
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self, ConfigError> {
        if bytes.len() < 2 {
            return Err(ConfigError::BufferTooSmall(2));
        }
        Ok(u16::from_le_bytes([bytes[0], bytes[1]]))
    }
}

impl ConfigValue for u32 {
    type Getter<'a> = u32;
    fn to_getter<'a>(&'a self) -> Self::Getter<'a> {
        *self
    }

    fn to_bytes(&self, buf: &mut [u8]) -> Result<usize, ConfigError> {
        if buf.len() < 4 {
            return Err(ConfigError::BufferTooSmall(4));
        }
        buf[0..4].copy_from_slice(&self.to_le_bytes());
        Ok(4)
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self, ConfigError> {
        if bytes.len() < 4 {
            return Err(ConfigError::BufferTooSmall(4));
        }
        Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
    }
}

impl ConfigValue for u64 {
    type Getter<'a> = u64;
    fn to_getter<'a>(&'a self) -> Self::Getter<'a> {
        *self
    }

    fn to_bytes(&self, buf: &mut [u8]) -> Result<usize, ConfigError> {
        if buf.len() < 8 {
            return Err(ConfigError::BufferTooSmall(8));
        }
        buf[0..8].copy_from_slice(&self.to_le_bytes());
        Ok(8)
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self, ConfigError> {
        if bytes.len() < 8 {
            return Err(ConfigError::BufferTooSmall(8));
        }
        Ok(u64::from_le_bytes([
            bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
        ]))
    }
}

impl ConfigValue for i16 {
    type Getter<'a> = i16;
    fn to_getter<'a>(&'a self) -> Self::Getter<'a> {
        *self
    }

    fn to_bytes(&self, buf: &mut [u8]) -> Result<usize, ConfigError> {
        if buf.len() < 2 {
            return Err(ConfigError::BufferTooSmall(2));
        }
        buf[0..2].copy_from_slice(&self.to_le_bytes());
        Ok(2)
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self, ConfigError> {
        if bytes.len() < 2 {
            return Err(ConfigError::BufferTooSmall(2));
        }
        Ok(i16::from_le_bytes([bytes[0], bytes[1]]))
    }
}

impl ConfigValue for i32 {
    type Getter<'a> = i32;
    fn to_getter<'a>(&'a self) -> Self::Getter<'a> {
        *self
    }

    fn to_bytes(&self, buf: &mut [u8]) -> Result<usize, ConfigError> {
        if buf.len() < 4 {
            return Err(ConfigError::BufferTooSmall(4));
        }
        buf[0..4].copy_from_slice(&self.to_le_bytes());
        Ok(4)
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self, ConfigError> {
        if bytes.len() < 4 {
            return Err(ConfigError::BufferTooSmall(4));
        }
        Ok(i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
    }
}

impl ConfigValue for i8 {
    type Getter<'a> = i8;
    fn to_getter<'a>(&'a self) -> Self::Getter<'a> {
        *self
    }

    fn to_bytes(&self, buf: &mut [u8]) -> Result<usize, ConfigError> {
        if buf.is_empty() {
            return Err(ConfigError::BufferTooSmall(1));
        }
        buf[0] = *self as u8;
        Ok(1)
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self, ConfigError> {
        if bytes.is_empty() {
            return Err(ConfigError::BufferTooSmall(1));
        }
        Ok(bytes[0] as i8)
    }
}

impl ConfigValue for i64 {
    type Getter<'a> = i64;
    fn to_getter<'a>(&'a self) -> Self::Getter<'a> {
        *self
    }

    fn to_bytes(&self, buf: &mut [u8]) -> Result<usize, ConfigError> {
        if buf.len() < 8 {
            return Err(ConfigError::BufferTooSmall(8));
        }
        buf[0..8].copy_from_slice(&self.to_le_bytes());
        Ok(8)
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self, ConfigError> {
        if bytes.len() < 8 {
            return Err(ConfigError::BufferTooSmall(8));
        }
        Ok(i64::from_le_bytes([
            bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
        ]))
    }
}

impl ConfigValue for f32 {
    type Getter<'a> = f32;
    fn to_getter<'a>(&'a self) -> Self::Getter<'a> {
        *self
    }

    fn to_bytes(&self, buf: &mut [u8]) -> Result<usize, ConfigError> {
        if buf.len() < 4 {
            return Err(ConfigError::BufferTooSmall(4));
        }
        buf[0..4].copy_from_slice(&self.to_le_bytes());
        Ok(4)
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self, ConfigError> {
        if bytes.len() < 4 {
            return Err(ConfigError::BufferTooSmall(4));
        }
        Ok(f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
    }

    const IS_FLOAT: bool = true;
    const JS_SAVE_KIND: JsSaveKind = JsSaveKind::Float;
}

impl ConfigValue for f64 {
    type Getter<'a> = f64;
    fn to_getter<'a>(&'a self) -> Self::Getter<'a> {
        *self
    }

    fn to_bytes(&self, buf: &mut [u8]) -> Result<usize, ConfigError> {
        if buf.len() < 8 {
            return Err(ConfigError::BufferTooSmall(8));
        }
        buf[0..8].copy_from_slice(&self.to_le_bytes());
        Ok(8)
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self, ConfigError> {
        if bytes.len() < 8 {
            return Err(ConfigError::BufferTooSmall(8));
        }
        Ok(f64::from_le_bytes([
            bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
        ]))
    }

    const IS_FLOAT: bool = true;
    const JS_SAVE_KIND: JsSaveKind = JsSaveKind::Float;
}

impl ConfigValue for String {
    type Getter<'a> = &'a String;
    fn to_getter<'a>(&'a self) -> Self::Getter<'a> {
        self
    }

    fn to_bytes(&self, buf: &mut [u8]) -> Result<usize, ConfigError> {
        let bytes = self.as_bytes();
        if buf.len() < bytes.len() {
            return Err(ConfigError::BufferTooSmall(bytes.len()));
        }
        buf[..bytes.len()].copy_from_slice(bytes);
        Ok(bytes.len())
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self, ConfigError> {
        core::str::from_utf8(bytes)
            .map(String::from)
            .map_err(|_| ConfigError::Utf8)
    }

    const DEFAULT_INPUT_TYPE: &'static str = "text";
    const JS_SAVE_KIND: JsSaveKind = JsSaveKind::String;
}