token-value-map 0.2.5

A token-value map with interpolation of values: what you need for DCCs
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
use core::num::NonZeroU16;
use token_value_map::*;

#[test]
fn value_from_primitives() {
    let _: Data = 42i64.into();
    let _: Data = 3.5f64.into();
    let _: Data = true.into();
    let _: Data = "hello".into();
    #[cfg(feature = "vector2")]
    {
        let _: Data = [1.0, 2.0].into();
    }
    #[cfg(feature = "vector3")]
    {
        let _: Data = [1.0, 2.0, 3.0].into();
    }
    let _: Data = [1.0, 0.5, 0.0, 1.0].into(); // Color
}

#[test]
fn value_to_primitives() {
    let v: Data = 42i64.into();
    assert_eq!(i64::try_from(v).unwrap(), 42);

    let v: Data = [1.0, 0.5, 0.0, 1.0].into();
    assert_eq!(<[f32; 4]>::try_from(v).unwrap(), [1.0, 0.5, 0.0, 1.0]);
}

#[test]
fn data_type() {
    assert_eq!(Data::from(42i64).data_type(), DataType::Integer);
    assert_eq!(Data::from(3.5).data_type(), DataType::Real);
    assert_eq!(Data::from(true).data_type(), DataType::Boolean);
    assert_eq!(Data::from("hello").data_type(), DataType::String);
}

#[test]
fn try_convert() {
    // Integer to other types
    let v = Data::from(42i64);
    assert_eq!(v.try_convert(DataType::Real).unwrap(), Data::from(42.0));
    assert_eq!(v.try_convert(DataType::Boolean).unwrap(), Data::from(true));
    assert_eq!(v.try_convert(DataType::String).unwrap(), Data::from("42"));

    // Boolean conversions
    let v = Data::from(true);
    assert_eq!(v.try_convert(DataType::Integer).unwrap(), Data::from(1i64));
    assert_eq!(v.try_convert(DataType::Real).unwrap(), Data::from(1.0));

    let v = Data::from(false);
    assert_eq!(v.try_convert(DataType::Integer).unwrap(), Data::from(0i64));

    // String parsing
    let v = Data::from("123");
    assert_eq!(
        v.try_convert(DataType::Integer).unwrap(),
        Data::from(123i64)
    );
    assert_eq!(v.try_convert(DataType::Real).unwrap(), Data::from(123.0));

    let v = Data::from("true");
    assert_eq!(v.try_convert(DataType::Boolean).unwrap(), Data::from(true));

    // Fill conversions
    #[cfg(feature = "vector2")]
    {
        let v = Data::from(5.0);
        let vec2 = v.try_convert(DataType::Vector2).unwrap();
        assert_eq!(
            token_value_map::math::Vec2Impl::try_from(vec2).unwrap(),
            token_value_map::math::Vec2Impl::new(5.0, 5.0)
        );
    }

    #[cfg(feature = "vector3")]
    {
        let v = Data::from(5.0);
        let vec3 = v.try_convert(DataType::Vector3).unwrap();
        assert_eq!(
            token_value_map::math::Vec3Impl::try_from(vec3).unwrap(),
            token_value_map::math::Vec3Impl::new(5.0, 5.0, 5.0)
        );
    }

    // Color from grayscale
    let v = Data::from(0.5);
    let color = v.try_convert(DataType::Color).unwrap();
    assert_eq!(<[f32; 4]>::try_from(color).unwrap(), [0.5, 0.5, 0.5, 1.0]);

    // Vec3 to Color
    #[cfg(feature = "vector3")]
    {
        let v = Data::from([1.0, 0.5, 0.25]);
        let color = v.try_convert(DataType::Color).unwrap();
        assert_eq!(<[f32; 4]>::try_from(color).unwrap(), [1.0, 0.5, 0.25, 1.0]);
    }
}

#[test]
fn string_parsing() {
    // Vec2 parsing
    #[cfg(feature = "vector2")]
    {
        let v = Data::from("[1.0, 2.0]");
        let vec2 = v.try_convert(DataType::Vector2).unwrap();
        assert_eq!(
            token_value_map::math::Vec2Impl::try_from(vec2).unwrap(),
            token_value_map::math::Vec2Impl::new(1.0, 2.0)
        );
    }

    // Color hex parsing
    let v = Data::from("#FF0000");
    let color = v.try_convert(DataType::Color).unwrap();
    assert_eq!(<[f32; 4]>::try_from(color).unwrap(), [1.0, 0.0, 0.0, 1.0]);

    // Matrix parsing (diagonal)
    #[cfg(feature = "matrix3")]
    {
        let v = Data::from("5.0");
        let mat = v.try_convert(DataType::Matrix3).unwrap();
        let expected = token_value_map::math::mat3_from_diagonal_element(5.0);
        assert_eq!(
            token_value_map::math::Mat3Impl::try_from(mat).unwrap(),
            expected
        );
    }
}

#[test]
fn attribute_value() -> token_value_map::Result<()> {
    let av = Value::animated(vec![
        (Time::from_secs(0.0), 0.0),
        (Time::from_secs(1.0), 1.0),
        (Time::from_secs(2.0), 2.0),
    ])?;

    assert_eq!(av.sample_count(), 3);
    assert!(av.is_animated());

    let (before, _after) = av.sample_bracket(Time::from_secs(1.5));
    assert!(before.is_some());

    Ok(())
}

#[test]
fn token_value_map() -> token_value_map::Result<()> {
    let mut map = TokenValueMap::new();

    #[cfg(feature = "vector3")]
    map.insert("position", [1.0, 2.0, 3.0]);
    #[cfg(all(not(feature = "vector3"), feature = "vector2"))]
    map.insert("position", [1.0, 2.0]);
    #[cfg(all(not(feature = "vector3"), not(feature = "vector2")))]
    map.insert("position", 42.0);
    map.insert(
        "color",
        Value::animated(vec![
            (Time::from_secs(0.0), [1.0, 0.0, 0.0, 1.0]),
            (Time::from_secs(1.0), [0.0, 1.0, 0.0, 1.0]),
        ])?,
    );

    assert_eq!(map.len(), 2);
    assert!(map.contains(&"position".into()));

    Ok(())
}

#[test]
fn value_with_animated_data() -> token_value_map::Result<()> {
    // Test creating animated real values
    let animated_real = Value::animated(vec![
        (Time::from_secs(0.0), 1.0),
        (Time::from_secs(1.0), 2.0),
        (Time::from_secs(2.0), 3.0),
    ])?;

    assert!(animated_real.is_animated());
    assert_eq!(animated_real.sample_count(), 3);

    // Test exact sampling
    let sample = animated_real.sample_at(Time::from_secs(1.0));
    assert_eq!(sample, Some(Data::Real(Real(2.0))));

    // Test interpolation
    let interpolated = animated_real.interpolate(Time::from_secs(0.5));
    assert_eq!(interpolated, Data::Real(Real(1.5)));

    Ok(())
}

#[test]
#[cfg(feature = "vector3")]
fn value_with_animated_vectors() -> token_value_map::Result<()> {
    // Test animated Vector3
    let animated_vec3 = Value::animated(vec![
        (Time::from_secs(0.0), [0.0f32, 0.0, 0.0]),
        (Time::from_secs(1.0), [1.0f32, 2.0, 3.0]),
    ])?;

    assert!(animated_vec3.is_animated());
    assert_eq!(animated_vec3.sample_count(), 2);

    // Test interpolation
    let interpolated = animated_vec3.interpolate(Time::from_secs(0.5));
    match interpolated {
        Data::Vector3(Vector3(v)) => {
            assert_eq!(v, token_value_map::math::Vec3Impl::new(0.5, 1.0, 1.5));
        }
        _ => panic!("Expected Vector3 data, got: {:?}", interpolated),
    }

    Ok(())
}

#[test]
fn value_add_sample_conversion() -> token_value_map::Result<()> {
    // Start with uniform value and add sample to make it animated
    let mut value = Value::uniform(1.0);
    assert!(!value.is_animated()); // Uniform = not animated
    assert_eq!(value.sample_count(), 1);

    // Add a sample - should convert to animated and drop uniform content
    value.add_sample(Time::from_secs(1.0), 2.0)?;
    // With only one sample, it's not considered "animated" yet.
    assert!(!value.is_animated());
    assert_eq!(value.sample_count(), 1); // Only the new sample should remain

    // Test that we only have the new sample
    let sample = value.sample_at(Time::from_secs(1.0));
    assert_eq!(sample, Some(Data::Real(Real(2.0))));

    // Add another sample - now animated.
    value.add_sample(Time::from_secs(2.0), 3.0)?;
    assert!(value.is_animated());
    assert_eq!(value.sample_count(), 2);

    Ok(())
}

#[test]
fn value_type_safety() -> token_value_map::Result<()> {
    // Test that adding different types fails
    let mut real_value = Value::animated(vec![(Time::from_secs(0.0), 1.0)])?;

    let result = real_value.add_sample(Time::from_secs(1.0), true);
    assert!(result.is_err());

    // Test that creating animated value with mixed types fails
    let mixed_result = Value::animated(vec![
        (Time::from_secs(0.0), Data::Real(Real(1.0))),
        (Time::from_secs(1.0), Data::Boolean(Boolean(true))),
    ]);
    assert!(mixed_result.is_err());

    Ok(())
}

#[test]
fn value_animated_boolean_no_interpolation() -> token_value_map::Result<()> {
    // Boolean values should not interpolate, just use closest sample
    let animated_bool = Value::animated(vec![
        (Time::from_secs(0.0), false),
        (Time::from_secs(1.0), true),
    ])?;

    // Test that boolean uses closest sample, not interpolation
    let sample_early = animated_bool.interpolate(Time::from_secs(0.3));
    assert_eq!(sample_early, Data::Boolean(Boolean(false)));

    let sample_late = animated_bool.interpolate(Time::from_secs(0.7));
    assert_eq!(sample_late, Data::Boolean(Boolean(true)));

    Ok(())
}

#[test]
fn value_empty_animated_creation() {
    // Creating animated value with no samples should fail
    let empty_result: token_value_map::Result<Value> = Value::animated(Vec::<(Time, f64)>::new());
    assert!(empty_result.is_err());
}

#[test]
fn value_uses_generic_insert() -> token_value_map::Result<()> {
    // This test verifies that the simplified implementation using generic
    // insert works
    let animated_mixed = Value::animated(vec![
        (Time::from_secs(0.0), Data::Real(Real(0.0))),
        (Time::from_secs(1.0), Data::Real(Real(1.0))),
        (Time::from_secs(2.0), Data::Real(Real(2.0))),
    ])?;

    assert!(animated_mixed.is_animated());
    assert_eq!(animated_mixed.sample_count(), 3);

    // Test interpolation
    let interpolated = animated_mixed.interpolate(Time::from_secs(1.5));
    assert_eq!(interpolated, Data::Real(Real(1.5)));

    // Test adding more samples
    let mut mutable_value = animated_mixed;
    mutable_value.add_sample(Time::from_secs(3.0), Data::Real(Real(3.0)))?;
    assert_eq!(mutable_value.sample_count(), 4);

    Ok(())
}

#[test]
fn data_type_dispatch() {
    // Test that data_type() works for Data
    let data = Data::Real(Real(42.0));
    assert_eq!(data.data_type(), DataType::Real);
    assert_eq!(data.type_name(), "real");

    // Test that data_type() works for AnimatedData
    let animated = AnimatedData::Real(TimeDataMap::from_iter(vec![(
        Time::from_secs(0.0),
        Real(1.0),
    )]));
    assert_eq!(animated.data_type(), DataType::Real);
    assert_eq!(animated.type_name(), "real");

    // Test that data_type() works for Value (uniform)
    let uniform_value = Value::uniform(42.0);
    assert_eq!(uniform_value.data_type(), DataType::Real);
    assert_eq!(uniform_value.type_name(), "real");

    // Test that data_type() works for Value (animated)
    let animated_value = Value::animated(vec![(Time::from_secs(0.0), 1.0)]).unwrap();
    assert_eq!(animated_value.data_type(), DataType::Real);
    assert_eq!(animated_value.type_name(), "real");

    // Test different types
    let bool_data = Data::Boolean(Boolean(true));
    assert_eq!(bool_data.data_type(), DataType::Boolean);
    assert_eq!(bool_data.type_name(), "boolean");

    #[cfg(feature = "vector3")]
    {
        let vec3_data = Data::Vector3(Vector3(token_value_map::math::Vec3Impl::new(1.0, 2.0, 3.0)));
        assert_eq!(vec3_data.data_type(), DataType::Vector3);
        assert_eq!(vec3_data.type_name(), "vec3");
    }
}

#[test]
fn sample_trait_implementations() -> token_value_map::Result<()> {
    // Test uniform Value sampling - should always return 1 sample with the
    // uniform value
    let uniform_real = Value::uniform(42.0);
    let shutter = Shutter {
        range: Time::from_secs(0.0)..Time::from_secs(1.0),
        opening: Time::from_secs(0.0)..Time::from_secs(1.0),
    };
    let samples: Vec<(Real, SampleWeight)> =
        uniform_real.sample(&shutter, NonZeroU16::new(5).unwrap())?;
    assert_eq!(samples.len(), 1);
    assert_eq!(samples[0].0, Real(42.0));
    assert_eq!(samples[0].1, 1.0);

    // Test uniform Vector3 sampling
    #[cfg(feature = "vector3")]
    {
        let uniform_vector = Value::uniform([1.0f32, 2.0, 3.0]);
        let samples: Vec<(Vector3, SampleWeight)> =
            uniform_vector.sample(&shutter, NonZeroU16::new(3).unwrap())?;
        assert_eq!(samples.len(), 1);
        assert_eq!(
            samples[0].0,
            Vector3(token_value_map::math::Vec3Impl::new(1.0, 2.0, 3.0))
        );
        assert_eq!(samples[0].1, 1.0);
    }

    // Test animated Value sampling - should return the requested number of
    // samples
    let animated_real = Value::animated(vec![
        (Time::from_secs(0.0), 0.0),
        (Time::from_secs(1.0), 100.0),
    ])?;
    let samples: Vec<(Real, SampleWeight)> =
        animated_real.sample(&shutter, NonZeroU16::new(3).unwrap())?;
    assert_eq!(samples.len(), 3);
    // All samples should be valid (values between 0 and 100)
    for (value, _weight) in samples {
        assert!(value.0 >= 0.0 && value.0 <= 100.0);
    }

    Ok(())
}

#[cfg(all(test, feature = "rkyv"))]
mod rkyv_tests {
    use super::*;
    use rkyv::{Deserialize, archived_root, to_bytes};

    #[test]
    fn test_data_rkyv_roundtrip() {
        let original = Data::Integer(Integer(42));
        let bytes = to_bytes::<_, 256>(&original).unwrap();
        let archived = unsafe { archived_root::<Data>(&bytes) };
        let deserialized: Data = archived.deserialize(&mut rkyv::Infallible).unwrap();
        assert_eq!(original, deserialized);
    }

    #[test]
    fn test_value_rkyv_roundtrip() {
        let original = Value::uniform(42.0);
        let bytes = to_bytes::<_, 256>(&original).unwrap();
        let archived = unsafe { archived_root::<Value>(&bytes) };
        let deserialized: Value = archived.deserialize(&mut rkyv::Infallible).unwrap();
        assert_eq!(original, deserialized);
    }

    #[test]
    fn test_animated_value_rkyv_roundtrip() -> token_value_map::Result<()> {
        let original = Value::animated(vec![
            (Time::from_secs(0.0), 0.0),
            (Time::from_secs(1.0), 1.0),
            (Time::from_secs(2.0), 2.0),
        ])?;
        let bytes = to_bytes::<_, 1024>(&original).unwrap();
        let archived = unsafe { archived_root::<Value>(&bytes) };
        let deserialized: Value = archived.deserialize(&mut rkyv::Infallible).unwrap();
        assert_eq!(original, deserialized);
        Ok(())
    }

    #[test]
    #[cfg(feature = "vector3")]
    fn test_vector3_rkyv_roundtrip() {
        let original = Data::Vector3(Vector3(token_value_map::math::Vec3Impl::new(1.0, 2.0, 3.0)));
        let bytes = to_bytes::<_, 256>(&original).unwrap();
        let archived = unsafe { archived_root::<Data>(&bytes) };
        let deserialized: Data = archived.deserialize(&mut rkyv::Infallible).unwrap();
        assert_eq!(original, deserialized);
    }

    #[test]
    fn test_token_value_map_rkyv_roundtrip() -> token_value_map::Result<()> {
        let mut original = TokenValueMap::new();
        original.insert("position", 42.0);
        original.insert(
            "color",
            Value::animated(vec![
                (Time::from_secs(0.0), [1.0, 0.0, 0.0, 1.0]),
                (Time::from_secs(1.0), [0.0, 1.0, 0.0, 1.0]),
            ])?,
        );

        let bytes = to_bytes::<_, 2048>(&original).unwrap();
        let archived = unsafe { archived_root::<TokenValueMap>(&bytes) };
        let deserialized: TokenValueMap = archived.deserialize(&mut rkyv::Infallible).unwrap();
        assert_eq!(original, deserialized);
        Ok(())
    }
}