structfs-core-store 0.2.0

Core StructFS store traits - Record, Value, Path, Format
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! Bridges between LL and Core layers.
//!
//! These adapters allow using LL stores from the Core layer and vice versa.
//!
//! # LL → Core Bridge
//!
//! Wrap an `LLStore` to get a Core `Store`:
//!
//! ```rust,ignore
//! let ll_store = SomeLLStore::new();
//! let core_store = LLToCore::new(ll_store, Format::JSON);
//! // Now use core_store as a Reader/Writer
//! ```
//!
//! # Core → LL Bridge
//!
//! Wrap a Core `Store` to get an `LLStore`:
//!
//! ```rust,ignore
//! let core_store = SomeCoreStore::new();
//! let ll_store = CoreToLL::new(core_store, JsonCodec, Format::JSON);
//! // Now use ll_store as an LLReader/LLWriter
//! ```

use bytes::Bytes;
use structfs_ll_store::{LLError, LLPath, LLReader, LLWriter};

use crate::{Codec, Error, Format, Path, PathError, Reader, Record, Writer};

/// Adapts an LL store to the Core Store interface.
///
/// This bridge:
/// - Converts `&[&[u8]]` paths to validated `Path`
/// - Wraps returned bytes as `Record::Raw` with a format hint
/// - Serializes `Record` to bytes for writes
pub struct LLToCore<T, C> {
    inner: T,
    codec: C,
    /// Format hint for data read from LL layer.
    read_format: Format,
    /// Format to use when serializing for LL writes.
    write_format: Format,
}

impl<T, C> LLToCore<T, C> {
    /// Create a new bridge with the same format for reads and writes.
    pub fn new(inner: T, codec: C, format: Format) -> Self {
        Self {
            inner,
            codec,
            read_format: format.clone(),
            write_format: format,
        }
    }

    /// Create a new bridge with different formats for reads and writes.
    pub fn with_formats(inner: T, codec: C, read_format: Format, write_format: Format) -> Self {
        Self {
            inner,
            codec,
            read_format,
            write_format,
        }
    }

    /// Get a reference to the inner LL store.
    pub fn inner(&self) -> &T {
        &self.inner
    }

    /// Get a mutable reference to the inner LL store.
    pub fn inner_mut(&mut self) -> &mut T {
        &mut self.inner
    }

    /// Unwrap, returning the inner LL store.
    pub fn into_inner(self) -> T {
        self.inner
    }
}

impl<T: LLReader, C: Send + Sync> Reader for LLToCore<T, C> {
    fn read(&mut self, from: &Path) -> Result<Option<Record>, Error> {
        // Borrow the validated byte components (free widening, no copy).
        let components: Vec<&[u8]> = from.as_ll().as_byte_refs();

        // Read via LL
        let bytes = match self.inner.ll_read(&components) {
            Ok(Some(b)) => b,
            Ok(None) => return Ok(None),
            Err(e) => return Err(Error::Ll(e)),
        };

        // Wrap as Raw record with our format hint
        Ok(Some(Record::raw(bytes, self.read_format.clone())))
    }
}

impl<T: LLWriter, C: Codec + Send + Sync> Writer for LLToCore<T, C> {
    fn write(&mut self, to: &Path, data: Record) -> Result<Path, Error> {
        // Get bytes from Record (serialize if Parsed)
        let bytes = data.into_bytes(&self.codec, &self.write_format)?;

        // Borrow the validated byte components (free widening, no copy).
        let components: Vec<&[u8]> = to.as_ll().as_byte_refs();

        // Write via LL
        let result_path = self.inner.ll_write(&components, bytes).map_err(Error::Ll)?;

        // Convert result back to Path
        path_from_ll(&result_path)
    }
}

/// Adapts a Core store to the LL Store interface.
///
/// This bridge:
/// - Converts `&[&[u8]]` paths to validated `Path`
/// - Parses/serializes data as needed
/// - Returns bytes in the configured format
pub struct CoreToLL<T, C> {
    inner: T,
    codec: C,
    format: Format,
}

impl<T, C> CoreToLL<T, C> {
    /// Create a new bridge.
    pub fn new(inner: T, codec: C, format: Format) -> Self {
        Self {
            inner,
            codec,
            format,
        }
    }

    /// Get a reference to the inner Core store.
    pub fn inner(&self) -> &T {
        &self.inner
    }

    /// Get a mutable reference to the inner Core store.
    pub fn inner_mut(&mut self) -> &mut T {
        &mut self.inner
    }

    /// Unwrap, returning the inner Core store.
    pub fn into_inner(self) -> T {
        self.inner
    }
}

impl<T: Reader, C: Codec + Send + Sync> LLReader for CoreToLL<T, C> {
    fn ll_read(&mut self, path: &[&[u8]]) -> Result<Option<Bytes>, LLError> {
        // Convert &[&[u8]] to Path
        let path = path_from_bytes(path).map_err(|e| LLError::Protocol {
            code: 1,
            detail: Bytes::copy_from_slice(e.to_string().as_bytes()),
        })?;

        // Read via Core
        let record = match self.inner.read(&path) {
            Ok(Some(r)) => r,
            Ok(None) => return Ok(None),
            Err(e) => {
                return Err(LLError::Protocol {
                    code: 2,
                    detail: Bytes::copy_from_slice(e.to_string().as_bytes()),
                })
            }
        };

        // Convert to bytes
        let bytes =
            record
                .into_bytes(&self.codec, &self.format)
                .map_err(|e| LLError::Protocol {
                    code: 3,
                    detail: Bytes::copy_from_slice(e.to_string().as_bytes()),
                })?;

        Ok(Some(bytes))
    }
}

impl<T: Writer, C: Send + Sync> LLWriter for CoreToLL<T, C> {
    fn ll_write(&mut self, path: &[&[u8]], data: Bytes) -> Result<LLPath, LLError> {
        // Convert path
        let path = path_from_bytes(path).map_err(|e| LLError::Protocol {
            code: 1,
            detail: Bytes::copy_from_slice(e.to_string().as_bytes()),
        })?;

        // Wrap data as Raw record
        let record = Record::raw(data, self.format.clone());

        // Write via Core
        let result_path = self
            .inner
            .write(&path, record)
            .map_err(|e| LLError::Protocol {
                code: 2,
                detail: Bytes::copy_from_slice(e.to_string().as_bytes()),
            })?;

        // Widen the validated result path to LL (free — no component copy).
        Ok(result_path.into_ll())
    }
}

/// Convert LL path components to Core Path.
pub(crate) fn path_from_bytes(components: &[&[u8]]) -> Result<Path, PathError> {
    let mut strings = Vec::with_capacity(components.len());
    for (i, bytes) in components.iter().enumerate() {
        let s = std::str::from_utf8(bytes).map_err(|_| PathError::InvalidComponent {
            component: format!("{:?}", bytes),
            position: i,
            message: "not valid UTF-8".to_string(),
        })?;
        strings.push(s.to_string());
    }
    Path::try_from_components(strings)
}

/// Convert LL path (owned) to Core Path.
pub(crate) fn path_from_ll(components: &[Bytes]) -> Result<Path, Error> {
    let refs: Vec<&[u8]> = components.iter().map(|b| b.as_ref()).collect();
    path_from_bytes(&refs).map_err(Error::Path)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{path, NoCodec};
    use std::collections::HashMap;

    /// Simple in-memory LL store for testing.
    struct TestLLStore {
        data: HashMap<Vec<Vec<u8>>, Bytes>,
    }

    impl TestLLStore {
        fn new() -> Self {
            Self {
                data: HashMap::new(),
            }
        }
    }

    impl LLReader for TestLLStore {
        fn ll_read(&mut self, path: &[&[u8]]) -> Result<Option<Bytes>, LLError> {
            let key: Vec<Vec<u8>> = path.iter().map(|c| c.to_vec()).collect();
            Ok(self.data.get(&key).cloned())
        }
    }

    impl LLWriter for TestLLStore {
        fn ll_write(&mut self, path: &[&[u8]], data: Bytes) -> Result<LLPath, LLError> {
            let key: Vec<Vec<u8>> = path.iter().map(|c| c.to_vec()).collect();
            self.data.insert(key, data);
            Ok(path.iter().map(|c| Bytes::copy_from_slice(c)).collect())
        }
    }

    /// Simple in-memory Core store for testing.
    struct TestCoreStore {
        data: HashMap<Path, Record>,
    }

    impl TestCoreStore {
        fn new() -> Self {
            Self {
                data: HashMap::new(),
            }
        }
    }

    impl Reader for TestCoreStore {
        fn read(&mut self, from: &Path) -> Result<Option<Record>, Error> {
            Ok(self.data.get(from).cloned())
        }
    }

    impl Writer for TestCoreStore {
        fn write(&mut self, to: &Path, data: Record) -> Result<Path, Error> {
            self.data.insert(to.clone(), data);
            Ok(to.clone())
        }
    }

    #[test]
    fn ll_to_core_read() {
        let mut ll = TestLLStore::new();
        ll.data.insert(
            vec![b"users".to_vec(), b"123".to_vec()],
            Bytes::from_static(b"hello"),
        );

        let mut bridge = LLToCore::new(ll, NoCodec, Format::OCTET_STREAM);

        let result = bridge.read(&path!("users/123")).unwrap();
        assert!(result.is_some());
        assert_eq!(
            result.unwrap().as_bytes(),
            Some(&Bytes::from_static(b"hello"))
        );
    }

    #[test]
    fn ll_to_core_write() {
        let ll = TestLLStore::new();
        let mut bridge = LLToCore::new(ll, NoCodec, Format::OCTET_STREAM);

        let record = Record::raw(Bytes::from_static(b"data"), Format::OCTET_STREAM);
        bridge.write(&path!("test/path"), record).unwrap();

        // Verify it was written
        let key = vec![b"test".to_vec(), b"path".to_vec()];
        assert!(bridge.inner().data.contains_key(&key));
    }

    #[test]
    fn core_to_ll_read() {
        let mut core = TestCoreStore::new();
        core.data.insert(
            path!("users/123"),
            Record::raw(Bytes::from_static(b"hello"), Format::OCTET_STREAM),
        );

        let mut bridge = CoreToLL::new(core, NoCodec, Format::OCTET_STREAM);

        let result = bridge.ll_read(&[b"users", b"123"]).unwrap();
        assert_eq!(result, Some(Bytes::from_static(b"hello")));
    }

    #[test]
    fn core_to_ll_write() {
        let core = TestCoreStore::new();
        let mut bridge = CoreToLL::new(core, NoCodec, Format::OCTET_STREAM);

        bridge
            .ll_write(&[b"test", b"path"], Bytes::from_static(b"data"))
            .unwrap();

        // Verify it was written
        assert!(bridge.inner().data.contains_key(&path!("test/path")));
    }

    #[test]
    fn invalid_utf8_path_rejected() {
        let core = TestCoreStore::new();
        let mut bridge = CoreToLL::new(core, NoCodec, Format::OCTET_STREAM);

        // Invalid UTF-8 sequence
        let result = bridge.ll_read(&[&[0xFF, 0xFE]]);
        assert!(matches!(result, Err(LLError::Protocol { .. })));
    }

    #[test]
    fn ll_to_core_with_formats() {
        let ll = TestLLStore::new();
        let bridge = LLToCore::with_formats(ll, NoCodec, Format::JSON, Format::OCTET_STREAM);
        assert_eq!(bridge.read_format, Format::JSON);
        assert_eq!(bridge.write_format, Format::OCTET_STREAM);
    }

    #[test]
    fn ll_to_core_inner_methods() {
        let ll = TestLLStore::new();
        let mut bridge = LLToCore::new(ll, NoCodec, Format::OCTET_STREAM);

        // Test inner()
        assert!(bridge.inner().data.is_empty());

        // Test inner_mut()
        bridge
            .inner_mut()
            .data
            .insert(vec![b"key".to_vec()], Bytes::from_static(b"value"));
        assert!(!bridge.inner().data.is_empty());

        // Test into_inner()
        let ll = bridge.into_inner();
        assert!(!ll.data.is_empty());
    }

    #[test]
    fn core_to_ll_inner_methods() {
        let core = TestCoreStore::new();
        let mut bridge = CoreToLL::new(core, NoCodec, Format::OCTET_STREAM);

        // Test inner()
        assert!(bridge.inner().data.is_empty());

        // Test inner_mut()
        bridge.inner_mut().data.insert(
            path!("key"),
            Record::raw(Bytes::from_static(b"value"), Format::OCTET_STREAM),
        );
        assert!(!bridge.inner().data.is_empty());

        // Test into_inner()
        let core = bridge.into_inner();
        assert!(!core.data.is_empty());
    }

    #[test]
    fn ll_to_core_read_none() {
        let ll = TestLLStore::new();
        let mut bridge = LLToCore::new(ll, NoCodec, Format::OCTET_STREAM);

        let result = bridge.read(&path!("nonexistent")).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn core_to_ll_read_none() {
        let core = TestCoreStore::new();
        let mut bridge = CoreToLL::new(core, NoCodec, Format::OCTET_STREAM);

        let result = bridge.ll_read(&[b"nonexistent"]).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn core_to_ll_write_invalid_utf8() {
        let core = TestCoreStore::new();
        let mut bridge = CoreToLL::new(core, NoCodec, Format::OCTET_STREAM);

        // Invalid UTF-8 sequence
        let result = bridge.ll_write(&[&[0xFF, 0xFE]], Bytes::from_static(b"data"));
        assert!(matches!(result, Err(LLError::Protocol { code: 1, .. })));
    }

    #[test]
    fn path_from_bytes_empty() {
        let result = path_from_bytes(&[]).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn path_from_bytes_single_component() {
        let result = path_from_bytes(&[b"users"]).unwrap();
        assert_eq!(result.to_string(), "users");
    }

    #[test]
    fn path_from_bytes_multiple_components() {
        let result = path_from_bytes(&[b"users", b"123", b"profile"]).unwrap();
        assert_eq!(result.to_string(), "users/123/profile");
    }

    #[test]
    fn path_from_ll_works() {
        let ll_path = vec![Bytes::from_static(b"a"), Bytes::from_static(b"b")];
        let result = path_from_ll(&ll_path).unwrap();
        assert_eq!(result.to_string(), "a/b");
    }

    #[test]
    fn path_from_ll_invalid_utf8() {
        let ll_path = vec![Bytes::from_static(&[0xFF, 0xFE])];
        let result = path_from_ll(&ll_path);
        assert!(result.is_err());
    }

    /// Store that always returns an error on read.
    struct ErrorCoreStore;

    impl Reader for ErrorCoreStore {
        fn read(&mut self, _from: &Path) -> Result<Option<Record>, Error> {
            Err(Error::store("test", "read", "read error"))
        }
    }

    impl Writer for ErrorCoreStore {
        fn write(&mut self, _to: &Path, _data: Record) -> Result<Path, Error> {
            Err(Error::store("test", "write", "write error"))
        }
    }

    #[test]
    fn core_to_ll_read_error() {
        let core = ErrorCoreStore;
        let mut bridge = CoreToLL::new(core, NoCodec, Format::OCTET_STREAM);

        let result = bridge.ll_read(&[b"any"]);
        assert!(matches!(result, Err(LLError::Protocol { code: 2, .. })));
    }

    #[test]
    fn core_to_ll_write_error() {
        let core = ErrorCoreStore;
        let mut bridge = CoreToLL::new(core, NoCodec, Format::OCTET_STREAM);

        let result = bridge.ll_write(&[b"any"], Bytes::from_static(b"data"));
        assert!(matches!(result, Err(LLError::Protocol { code: 2, .. })));
    }

    /// LL store that always returns an error.
    struct ErrorLLStore;

    impl LLReader for ErrorLLStore {
        fn ll_read(&mut self, _path: &[&[u8]]) -> Result<Option<Bytes>, LLError> {
            Err(LLError::Protocol {
                code: 99,
                detail: Bytes::from_static(b"ll error"),
            })
        }
    }

    impl LLWriter for ErrorLLStore {
        fn ll_write(&mut self, _path: &[&[u8]], _data: Bytes) -> Result<LLPath, LLError> {
            Err(LLError::Protocol {
                code: 99,
                detail: Bytes::from_static(b"ll write error"),
            })
        }
    }

    #[test]
    fn ll_to_core_read_error() {
        let ll = ErrorLLStore;
        let mut bridge = LLToCore::new(ll, NoCodec, Format::OCTET_STREAM);

        let result = bridge.read(&path!("any"));
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("ll error"));
    }

    #[test]
    fn ll_to_core_write_error() {
        let ll = ErrorLLStore;
        let mut bridge = LLToCore::new(ll, NoCodec, Format::OCTET_STREAM);

        let result = bridge.write(
            &path!("any"),
            Record::raw(Bytes::from_static(b"data"), Format::OCTET_STREAM),
        );
        assert!(result.is_err());
    }
}