ordofp_core 0.1.0

OrdoFP core provides developers with HList, Disiunctio, NominataUniversalis, Universalis, and functional type classes
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
//! Registrum - Extensible Record Type
//!
//! > *"Registrum est liber in quo res gestae describuntur."*
//! > — A register is a book in which deeds are recorded.
//!
//! This module provides the `Registrum` type - an extensible record that
//! supports row polymorphism.

use core::fmt;

use crate::hlist::{Coniunctio, HList, Nihil};
use crate::labelled::Field;

use super::campus::{Confluo, Extendo, HabetCampum, Muto, Restricto};

// =============================================================================
// Registrum - Extensible Record
// =============================================================================

/// An extensible record type with row polymorphism support.
///
/// `Registrum` wraps an `HList` of labelled fields and provides a clean API
/// for record operations while supporting row-polymorphic functions.
///
/// # Latin Etymology
///
/// *Registrum* = register, record book
///
/// # Type Parameters
///
/// * `R` - The row type (`HList` of Field types)
///
/// # Example
///
/// ```rust
/// use ordofp_core::rows::Registrum;
/// use ordofp_core::labelled::chars::*;
/// use ordofp_core::indices::{Here, There};
///
/// type Name = (Ln, La, Lm, Le);
/// type Age = (La, Lg, Le);
///
/// let person = Registrum::new()
///     .extend_field::<Name, _>("name", "Alice")
///     .extend_field::<Age, _>("age", 30);
///
/// assert_eq!(*person.get::<Name, &str, There<Here>>(), "Alice");
/// assert_eq!(*person.get::<Age, i32, Here>(), 30);
/// ```
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Registrum<R> {
    pub(crate) fields: R,
}

impl Registrum<Nihil> {
    /// Create a new empty record.
    ///
    /// # Example
    ///
    /// ```rust
    /// use ordofp_core::rows::Registrum;
    ///
    /// let empty = Registrum::new();
    /// assert!(empty.is_empty());
    /// ```
    #[inline]
    pub fn new() -> Self {
        Registrum { fields: Nihil }
    }
}

impl Default for Registrum<Nihil> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<R: HList> Registrum<R> {
    /// Create a record from an `HList` of fields.
    ///
    /// This is primarily for internal use or advanced scenarios.
    #[inline]
    pub fn from_hlist(fields: R) -> Self {
        Registrum { fields }
    }

    /// Get the underlying `HList` of fields.
    #[inline]
    pub fn into_hlist(self) -> R {
        self.fields
    }

    /// Get a reference to the underlying `HList`.
    #[inline]
    pub fn as_hlist(&self) -> &R {
        &self.fields
    }

    /// Get the number of fields in this record.
    #[inline]
    pub fn len(&self) -> usize {
        self.fields.len()
    }

    /// Check if the record has no fields.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.fields.is_empty()
    }
}

impl<R> Registrum<R> {
    /// Extend this record with a new field.
    ///
    /// # Type Parameters
    ///
    /// * `Label` - The type-level name for the new field
    /// * `Value` - The value type
    ///
    /// # Arguments
    ///
    /// * `name` - The runtime field name
    /// * `value` - The field value
    ///
    /// # Example
    ///
    /// ```rust
    /// use ordofp_core::rows::Registrum;
    /// use ordofp_core::labelled::chars::*;
    ///
    /// type Name = (Ln, La, Lm, Le);
    ///
    /// let record = Registrum::new().extend_field::<Name, _>("name", "Alice");
    /// assert_eq!(record.len(), 1);
    /// ```
    #[inline]
    pub fn extend_field<Label, Value>(
        self,
        name: &'static str,
        value: Value,
    ) -> Registrum<R::Output>
    where
        R: Extendo<Label, Value>,
    {
        Registrum {
            fields: self.fields.extend(name, value),
        }
    }

    /// Get a reference to a field by label.
    ///
    /// # Type Parameters
    ///
    /// * `Label` - The type-level field name
    /// * `Value` - The value type
    /// * `Index` - The index type (usually inferred)
    ///
    /// # Example
    ///
    /// ```rust
    /// use ordofp_core::rows::Registrum;
    /// use ordofp_core::labelled::chars::*;
    /// use ordofp_core::indices::Here;
    ///
    /// type Age = (La, Lg, Le);
    ///
    /// let record = Registrum::new().extend_field::<Age, _>("age", 30i32);
    /// let age: &i32 = record.get::<Age, i32, Here>();
    /// assert_eq!(*age, 30);
    /// ```
    #[inline]
    pub fn get<Label, Value, Index>(&self) -> &Value
    where
        R: HabetCampum<Label, Value, Index>,
    {
        self.fields.get_field()
    }

    /// Get a mutable reference to a field by label.
    #[inline]
    pub fn get_mut<Label, Value, Index>(&mut self) -> &mut Value
    where
        R: HabetCampum<Label, Value, Index>,
    {
        self.fields.get_field_mut()
    }

    /// Remove a field from the record and return it.
    ///
    /// Returns a tuple of (`field_value`, `remaining_record`).
    ///
    /// # Example
    ///
    /// ```rust
    /// use ordofp_core::rows::Registrum;
    /// use ordofp_core::labelled::chars::*;
    /// use ordofp_core::indices::Here;
    ///
    /// type Age = (La, Lg, Le);
    ///
    /// let record = Registrum::new().extend_field::<Age, _>("age", 30i32);
    /// let (age, rest): (i32, _) = record.restrict::<Age, Here>();
    /// assert_eq!(age, 30);
    /// assert!(rest.is_empty());
    /// ```
    #[inline]
    pub fn restrict<Label, Index>(self) -> (R::Value, Registrum<R::Remainder>)
    where
        R: Restricto<Label, Index>,
    {
        let (value, remainder) = self.fields.restrict();
        (value, Registrum { fields: remainder })
    }

    /// Merge this record with another.
    ///
    /// # Example
    ///
    /// ```rust
    /// use ordofp_core::rows::Registrum;
    /// use ordofp_core::labelled::chars::*;
    ///
    /// type Name = (Ln, La, Lm, Le);
    /// type Age = (La, Lg, Le);
    ///
    /// let name_record = Registrum::new().extend_field::<Name, _>("name", "Alice");
    /// let age_record = Registrum::new().extend_field::<Age, _>("age", 30i32);
    ///
    /// let person = name_record.merge(age_record);
    /// assert_eq!(person.len(), 2);
    /// ```
    #[inline]
    pub fn merge<Other>(self, other: Registrum<Other>) -> Registrum<R::Output>
    where
        R: Confluo<Other>,
    {
        Registrum {
            fields: self.fields.merge(other.fields),
        }
    }

    /// Modify a field with a function.
    ///
    /// # Example
    ///
    /// ```rust
    /// use ordofp_core::rows::Registrum;
    /// use ordofp_core::labelled::chars::*;
    /// use ordofp_core::indices::Here;
    ///
    /// type Age = (La, Lg, Le);
    ///
    /// let person = Registrum::new().extend_field::<Age, _>("age", 30i32);
    /// let older = person.modify::<Age, i32, Here, _>(|age| age + 1);
    /// let age: &i32 = older.get::<Age, i32, Here>();
    /// assert_eq!(*age, 31);
    /// ```
    #[inline]
    pub fn modify<Label, NewValue, Index, F>(self, f: F) -> Registrum<R::Output>
    where
        R: Muto<Label, NewValue, Index>,
        F: FnOnce(R::OldValue) -> NewValue,
    {
        Registrum {
            fields: self.fields.modify(f),
        }
    }
}

// =============================================================================
// Debug Implementation
// =============================================================================

impl fmt::Debug for Registrum<Nihil> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Registrum {{}}")
    }
}

impl<Label, Value: fmt::Debug, Tail: HList> fmt::Debug
    for Registrum<Coniunctio<Field<Label, Value>, Tail>>
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Registrum {{ {}: {:?}, ... }}",
            self.fields.head.name, self.fields.head.value
        )
    }
}

// =============================================================================
// Row-Polymorphic Function Support
// =============================================================================

/// Trait for functions that work on records with specific fields.
///
/// This enables row-polymorphic functions that can accept any record
/// containing the required fields.
///
/// # Example
///
/// ```rust
/// use ordofp_core::rows::{Registrum, HabetCampum};
/// use ordofp_core::labelled::chars::*;
///
/// type Name = (Ln, La, Lm, Le);
///
/// fn greet<R, I>(record: &Registrum<R>) -> String
/// where
///     R: HabetCampum<Name, String, I>,
/// {
///     format!("Hello, {}!", record.get::<Name, String, I>())
/// }
///
/// let record = Registrum::new().extend_field::<Name, _>("name", String::from("Alice"));
/// assert_eq!(greet(&record), "Hello, Alice!");
/// ```
pub trait RegistrumExt<R> {
    /// Apply a function to the record.
    fn with<F, T>(self, f: F) -> T
    where
        F: FnOnce(Registrum<R>) -> T;
}

impl<R> RegistrumExt<R> for Registrum<R> {
    #[inline]
    fn with<F, T>(self, f: F) -> T
    where
        F: FnOnce(Registrum<R>) -> T,
    {
        f(self)
    }
}

// =============================================================================
// Conversion Traits
// =============================================================================

impl<R: HList> From<R> for Registrum<R> {
    #[inline]
    fn from(fields: R) -> Self {
        Registrum { fields }
    }
}

// Note: We can't implement From<Registrum<R>> for R due to orphan rules
// Users can use into_hlist() instead.

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::indices::Here;
    use crate::labelled::chars::*;

    type Name = (Ln, La, Lm, Le);
    type Age = (La, Lg, Le);

    #[test]
    fn test_registrum_new() {
        let record = Registrum::new();
        assert!(record.is_empty());
        assert_eq!(record.len(), 0);
    }

    #[test]
    fn test_registrum_from_hlist() {
        let hlist = hlist![field!(Name, "Alice")];
        let record = Registrum::from_hlist(hlist);
        assert!(!record.is_empty());
        assert_eq!(record.len(), 1);
    }

    #[test]
    fn test_registrum_into_hlist() {
        let hlist = hlist![field!(Name, "Alice")];
        let record = Registrum::from_hlist(hlist);
        let back = record.into_hlist();
        assert_eq!(back, hlist);
    }

    #[test]
    fn test_registrum_extend() {
        let record = Registrum::new()
            .extend_field::<Name, _>("name", "Alice")
            .extend_field::<Age, _>("age", 30i32);

        assert_eq!(record.len(), 2);
    }

    #[test]
    fn test_registrum_get() {
        let record = Registrum::from_hlist(hlist![field!(Name, "Alice"), field!(Age, 30i32)]);

        let name: &&str = record.get::<Name, &str, Here>();
        assert_eq!(*name, "Alice");
    }

    #[test]
    fn test_registrum_restrict() {
        let record = Registrum::from_hlist(hlist![field!(Name, "Alice"), field!(Age, 30i32)]);

        let (name, rest): (&str, _) = record.restrict::<Name, Here>();
        assert_eq!(name, "Alice");
        assert_eq!(rest.len(), 1);
    }

    #[test]
    fn test_registrum_merge() {
        let r1 = Registrum::from_hlist(hlist![field!(Name, "Alice")]);
        let r2 = Registrum::from_hlist(hlist![field!(Age, 30i32)]);

        let merged = r1.merge(r2);
        assert_eq!(merged.len(), 2);
    }

    #[test]
    fn test_registrum_modify() {
        let record = Registrum::from_hlist(hlist![field!(Age, 30i32)]);
        let modified = record.modify::<Age, i32, Here, _>(|age| age + 1);

        let age: &i32 = modified.get::<Age, i32, Here>();
        assert_eq!(*age, 31);
    }

    #[test]
    fn test_registrum_debug() {
        let record = Registrum::new();
        let debug = alloc::format!("{record:?}");
        assert!(debug.contains("Registrum"));
    }
}