enum_companion 0.1.4

A procedural macro for generating companion enums for structs.
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
#![doc = include_str!("../README.md")]

pub use enum_companion_derive::EnumCompanion;
/// A trait for accessing and updating struct fields dynamically.
///
/// This trait is automatically implemented for structs that derive `EnumCompanion`
/// and use the default method names.
pub trait EnumCompanionTrait<F, V>
where
    F: Copy + 'static,
{
    /// Returns the value of a specific field.
    fn value(&self, field: F) -> V;

    /// Updates the value of a specific field.
    fn update(&mut self, value: V);

    /// Returns an array of all field enum variants.
    fn fields() -> &'static [F];

    /// Returns a vector of all field values.
    fn as_values(&self) -> Vec<V>;
}

/// A trait for struct fields covered by the `EnumCompanion` derive macro, providing methods to access field data.
/// This trait is automatically implemented for structs that derive `EnumCompanion`.
pub trait EnumCompanionField {
    /// Returns the name of the field.
    fn name(&self) -> &'static str;

    /// Returns the type of the field as a string.
    fn type_str(&self) -> &'static str;

    /// Get a title for the field, typically used for display purposes.
    fn title(&self) -> &'static str {
        self.name()
    }
    /// Get a description for the field, typically used for display purposes.
    fn description(&self) -> &'static str {
        self.name()
    }
    /// Get the order of the field, which can be used for sorting or display purposes.
    fn order(&self) -> isize {
        0
    }
}

/// A trait for struct values covered by the `EnumCompanion` derive macro, providing methods to access value data.
/// This trait is automatically implemented for structs that derive `EnumCompanion`.
pub trait EnumCompanionValue {
    /// Returns the name of the field.
    fn field_name(&self) -> &'static str;

    /// Returns the type of the field as a string.
    fn type_name(&self) -> &'static str;
}

extern crate self as enum_companion;

// Tests
#[cfg(test)]
mod tests {
    use enum_companion_derive::EnumCompanion;

    #[test]
    fn test_simple_enum_companion() {
        // This test is just used to get the macro output for the README
        #[allow(dead_code)]
        #[derive(EnumCompanion)]
        #[companion(derive_value(Debug, PartialEq))]
        struct Example {
            id: u32,
            name: String,
        }
    }

    #[test]
    fn test_enum_companion() {
        #[derive(EnumCompanion)]
        #[companion(derive_field(PartialEq, Debug), derive_value(Debug, PartialEq))]
        struct Test {
            name: String,
            distance: u32,
        }

        let test = Test {
            name: "Test".to_string(),
            distance: 42,
        };
        assert_eq!(
            test.value(TestField::Name),
            TestValue::Name("Test".to_string())
        );
        assert_eq!(Test::fields(), [TestField::Name, TestField::Distance]);
    }

    #[test]
    fn test_with_lifetime() {
        #[derive(EnumCompanion)]
        #[companion(derive_field(PartialEq, Debug), derive_value(Debug, PartialEq))]
        struct TestLifetime<'a> {
            name: &'a str,
            distance: u32,
        }

        let test = TestLifetime {
            name: "Test",
            distance: 42,
        };
        assert_eq!(
            test.value(TestLifetimeField::Name),
            TestLifetimeValue::Name("Test")
        );
        assert_eq!(
            TestLifetime::fields(),
            [TestLifetimeField::Name, TestLifetimeField::Distance]
        );
    }

    #[test]
    fn test_with_generic() {
        #[derive(EnumCompanion)]
        #[companion(derive_field(PartialEq, Debug), derive_value(Debug, PartialEq))]
        struct TestGeneric<T: Clone + PartialEq + std::fmt::Debug> {
            name: String,
            data: T,
        }

        let test = TestGeneric {
            name: "Test".to_string(),
            data: 42u32,
        };
        assert_eq!(
            test.value(TestGenericField::Data),
            TestGenericValue::Data(42u32)
        );

        let test2 = TestGeneric {
            name: "Test2".to_string(),
            data: "hello".to_string(),
        };
        assert_eq!(
            test2.value(TestGenericField::Data),
            TestGenericValue::Data("hello".to_string())
        );
        assert_eq!(
            TestGeneric::<String>::fields(),
            [TestGenericField::Name, TestGenericField::Data]
        );
    }

    mod nested {
        use super::*;

        #[derive(EnumCompanion)]
        #[allow(dead_code)]
        #[companion(derive_field(PartialEq, Debug), derive_value(Debug, PartialEq))]
        pub(super) struct TestVisibility {
            pub name: String,
        }
    }

    #[test]
    fn test_visibility() {
        let test = nested::TestVisibility {
            name: "Test".to_string(),
        };
        assert_eq!(
            test.value(nested::TestVisibilityField::Name),
            nested::TestVisibilityValue::Name("Test".to_string())
        );
        assert_eq!(
            nested::TestVisibility::fields(),
            &[nested::TestVisibilityField::Name]
        );
    }

    #[test]
    fn test_from_str() {
        #[allow(dead_code)]
        #[derive(EnumCompanion)]
        #[companion(derive_field(PartialEq, Debug))]
        struct Test {
            field_one: String,
            #[companion(rename = "Field2")]
            field_two: u32,
        }

        use std::str::FromStr;
        assert_eq!(TestField::from_str("field_one"), Ok(TestField::FieldOne));
        assert_eq!(TestField::from_str("FieldOne"), Ok(TestField::FieldOne));
        assert_eq!(TestField::from_str("field_two"), Ok(TestField::Field2));
        assert_eq!(TestField::from_str("Field2"), Ok(TestField::Field2));
        assert!(TestField::from_str("field_three").is_err());
    }

    #[test]
    fn test_trait() {
        #[derive(EnumCompanion)]
        #[companion(derive_field(PartialEq, Debug), derive_value(Debug, PartialEq))]
        struct Test {
            name: String,
            distance: u32,
        }

        let mut test = Test {
            name: "Test".to_string(),
            distance: 42,
        };

        assert_eq!(
            test.value(TestField::Name),
            TestValue::Name("Test".to_string())
        );
        test.update(TestValue::Distance(100));
        assert_eq!(test.distance, 100);
        assert_eq!(Test::fields(), &[TestField::Name, TestField::Distance]);
        assert_eq!(
            test.as_values(),
            vec![
                TestValue::Name("Test".to_string()),
                TestValue::Distance(100)
            ]
        );
    }

    #[test]
    fn test_with_serde() {
        use serde::{Deserialize, Serialize};
        #[derive(EnumCompanion)]
        #[companion(
            value_fn = "get_field",
            update_fn = "set_field",
            fields_fn = "get_all_fields",
            derive_field(Hash, Eq, PartialEq, Debug, Serialize, Deserialize),
            derive_value(Serialize, Deserialize, Debug, PartialEq),
            serde_field(rename_all = "camelCase"),
            serde_value(rename_all = "camelCase", tag = "type", content = "value")
        )]
        struct UserProfile {
            #[companion(rename = "UserId")]
            id: u64,

            #[companion(rename = "DisplayName")]
            username: String,

            email: String,

            #[allow(dead_code)]
            #[companion(skip)]
            password_hash: String, // This field won't appear in companion enums

            age: Option<u8>,
            is_verified: bool,
        }

        let mut profile = UserProfile {
            id: 12345,
            username: "alice_dev".to_string(),
            email: "alice@example.com".to_string(),
            password_hash: "secret_hash".to_string(),
            age: Some(28),
            is_verified: true,
        };

        // Use custom method names
        let user_id = profile.get_field(UserProfileField::UserId);
        assert_eq!(user_id, UserProfileValue::UserId(12345));

        // Update using custom method
        profile.set_field(UserProfileValue::DisplayName("alice_developer".to_string()));
        assert_eq!(profile.username, "alice_developer");

        // The password_hash field is skipped, so it doesn't appear in enums
        let fields = UserProfile::get_all_fields();
        assert_eq!(
            fields,
            &[
                UserProfileField::UserId,
                UserProfileField::DisplayName,
                UserProfileField::Email,
                UserProfileField::Age,
                UserProfileField::IsVerified
            ]
        );

        // Work with optional fields
        profile.set_field(UserProfileValue::Age(None));
        assert_eq!(profile.age, None);

        // Serialize/deserialize the values (if serde feature is enabled)
        let all_values = profile.as_values();
        for value in all_values {
            let serialized = serde_json::to_string(&value).unwrap();
            println!("Field value: {serialized}");
            if let UserProfileValue::UserId(_) = value {
                assert_eq!(serialized, r#"{"type":"userId","value":12345}"#);
            }
        }
    }

    #[test]
    fn test_try_from() {
        use std::convert::TryInto;

        #[derive(EnumCompanion)]
        #[companion(derive_field(PartialEq, Debug), derive_value(Debug, PartialEq))]
        struct Test {
            name: String,
            distance: u32,
            speed: u32,
        }

        let test = Test {
            name: "Test".to_string(),
            distance: 42,
            speed: 100,
        };

        // Test successful conversion
        let name_value = test.value(TestField::Name);
        let name: String = name_value.clone().try_into().unwrap();
        assert_eq!(name, "Test".to_string());

        let distance_value = test.value(TestField::Distance);
        let distance: u32 = distance_value.clone().try_into().unwrap();
        assert_eq!(distance, 42);

        let speed_value = test.value(TestField::Speed);
        let speed: u32 = speed_value.clone().try_into().unwrap();
        assert_eq!(speed, 100);

        // Test failed conversion
        let name_value_fail = test.value(TestField::Name);
        let name_res: Result<u32, _> = name_value_fail.try_into();
        assert!(name_res.is_err());
    }

    #[test]
    fn test_try_from_tuple() {
        use std::convert::TryInto;

        #[derive(EnumCompanion)]
        #[allow(dead_code)]
        #[companion(derive_field(PartialEq, Debug), derive_value(Debug, PartialEq))]
        struct Test {
            name: String,
            distance: u32,
        }

        // Test successful conversion
        let name_tuple = (TestField::Name, "Test".to_string());
        let name_value: TestValue = name_tuple.try_into().unwrap();
        assert_eq!(name_value, TestValue::Name("Test".to_string()));

        let distance_tuple = (TestField::Distance, 42u32);
        let distance_value: TestValue = distance_tuple.try_into().unwrap();
        assert_eq!(distance_value, TestValue::Distance(42));

        // Test failed conversion
        let name_tuple_fail = (TestField::Name, 42u32);
        let name_res: Result<TestValue, _> = name_tuple_fail.try_into();
        assert!(name_res.is_err());
        assert_eq!(name_res.unwrap_err(), TestField::Name);
    }

    #[test]
    fn test_field_trait() {
        use crate::{EnumCompanionField, EnumCompanionValue};

        #[derive(EnumCompanion)]
        #[companion(derive_field(PartialEq, Debug), derive_value(Debug, PartialEq))]
        struct Test {
            #[companion(title = "The Name", description = "The name of the test", order = 1)]
            name: String,
            distance: u32,
        }

        let test = Test {
            name: "Test".to_string(),
            distance: 42,
        };

        // Test EnumCompanionField
        assert_eq!(TestField::Name.name(), "name");
        assert_eq!(TestField::Distance.name(), "distance");
        assert_eq!(TestField::Name.type_str(), "String");
        assert_eq!(TestField::Distance.type_str(), "u32");
        assert_eq!(TestField::Name.title(), "The Name");
        assert_eq!(TestField::Distance.title(), "distance");
        assert_eq!(TestField::Name.description(), "The name of the test");
        assert_eq!(TestField::Distance.description(), "");
        assert_eq!(TestField::Name.order(), 1);
        assert_eq!(TestField::Distance.order(), 0);

        // Test EnumCompanionValue
        let name_value = test.value(TestField::Name);
        assert_eq!(name_value.field_name(), "name");
        assert_eq!(name_value.type_name(), "String");

        let distance_value = test.value(TestField::Distance);
        assert_eq!(distance_value.field_name(), "distance");
        assert_eq!(distance_value.type_name(), "u32");
    }

    #[test]
    fn test_display_and_fromstr_for_field() {
        use std::str::FromStr;
        #[allow(dead_code)]
        #[derive(EnumCompanion)]
        #[companion(derive_field(PartialEq, Debug), derive_value(Debug, PartialEq))]
        struct Test {
            #[companion(rename = "DisplayName")]
            name: String,
            distance: u32,
        }

        // Display should use name()
        assert_eq!(format!("{}", TestField::DisplayName), "DisplayName");
        assert_eq!(format!("{}", TestField::Distance), "distance");

        // FromStr should accept name() and the original snake_case and PascalCase
        assert_eq!(
            TestField::from_str("DisplayName"),
            Ok(TestField::DisplayName)
        );
        assert_eq!(TestField::from_str("distance"), Ok(TestField::Distance));
        assert_eq!(TestField::from_str("Distance"), Ok(TestField::Distance));
        assert!(TestField::from_str("unknown").is_err());
    }

    #[test]
    fn test_raw_identifier_field() {
        use crate::EnumCompanionField;

        #[derive(EnumCompanion)]
        #[companion(derive_field(PartialEq, Debug), derive_value(Debug, PartialEq))]
        struct Foo {
            name: String,
            id: i64,
            r#type: String,
        }

        let foo = Foo {
            name: "Foo".to_string(),
            id: 123,
            r#type: "example".to_string(),
        };

        assert_eq!(
            Foo::fields(),
            &[FooField::Name, FooField::Id, FooField::Type]
        );
        assert_eq!(
            foo.value(FooField::Type),
            FooValue::Type("example".to_string())
        );
        assert_eq!(FooField::Type.name(), "type");
    }
}