drmem-api 0.5.0

Traits and types used internally by the DrMem control system
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
use crate::types::Error;
use std::{convert::TryFrom, fmt, sync::Arc};

/// Defines fundamental types that can be associated with a device.
/// Drivers set the type for each device they manage and, for devices
/// that can be set, only accept values of the correct type.

#[derive(Clone, Debug, PartialEq)]
pub enum Value {
    /// For devices that return/accept a simple true/false, on/off,
    /// etc., state.
    Bool(bool),

    /// For devices that return/accept an integer value. It is stored
    /// as a signed, 32-bit. This type should primarily be used for
    /// digital inputs/outputs. There is no 64-bit version because
    /// Javascript doesn't support a 64-bit integer. For integer
    /// values greater than 32 bits, use a `Flt` since it can
    /// losslessly handle integers up to 52 bits.
    Int(i32),

    /// For devices that return/accept floating point numbers or
    /// integers up to 52 bits.
    Flt(f64),

    /// For devices that return/accept text. Since strings can greatly
    /// vary in size, care must be taken when returning this type. A
    /// driver that returns strings rapidly should keep them short.
    /// Longer strings should be returned at a slower rate. If the
    /// system takes too much time serializing string data, it could
    /// throw other portions of DrMem out of "soft real-time".
    Str(Arc<str>),

    /// For devices that render color values.
    Color(palette::LinSrgba<u8>),
}

impl Value {
    pub fn is_same_type(&self, o: &Value) -> bool {
        matches!(
            (self, o),
            (Value::Bool(_), Value::Bool(_))
                | (Value::Int(_), Value::Int(_))
                | (Value::Flt(_), Value::Flt(_))
                | (Value::Str(_), Value::Str(_))
                | (Value::Color(_), Value::Color(_))
        )
    }
}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Value::Bool(v) => write!(f, "{}", v),
            Value::Int(v) => write!(f, "{}", v),
            Value::Flt(v) => write!(f, "{}", v),
            Value::Str(v) => write!(f, "\"{}\"", v),
            Value::Color(v) => {
                write!(f, "\"#{:02x}{:02x}{:02x}", v.red, v.green, v.blue)?;
                if v.alpha < 255 {
                    write!(f, "{:02x}", v.alpha)?;
                }
                write!(f, "\"")
            }
        }
    }
}

impl TryFrom<Value> for bool {
    type Error = Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        if let Value::Bool(v) = value {
            Ok(v)
        } else {
            Err(Error::TypeError)
        }
    }
}

impl From<bool> for Value {
    fn from(value: bool) -> Self {
        Value::Bool(value)
    }
}

impl TryFrom<Value> for i32 {
    type Error = Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        if let Value::Int(v) = value {
            return Ok(v);
        }
        Err(Error::TypeError)
    }
}

impl From<i32> for Value {
    fn from(value: i32) -> Self {
        Value::Int(value)
    }
}

impl TryFrom<Value> for i16 {
    type Error = Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        if let Value::Int(v) = value {
            if let Ok(v) = i16::try_from(v) {
                return Ok(v);
            }
        }
        Err(Error::TypeError)
    }
}

impl From<i16> for Value {
    fn from(value: i16) -> Self {
        Value::Int(i32::from(value))
    }
}

impl TryFrom<Value> for u16 {
    type Error = Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        if let Value::Int(v) = value {
            if let Ok(v) = u16::try_from(v) {
                return Ok(v);
            }
        }
        Err(Error::TypeError)
    }
}

impl From<u16> for Value {
    fn from(value: u16) -> Self {
        Value::Int(i32::from(value))
    }
}

impl TryFrom<Value> for f64 {
    type Error = Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        if let Value::Flt(v) = value {
            Ok(v)
        } else {
            Err(Error::TypeError)
        }
    }
}

impl From<f64> for Value {
    fn from(value: f64) -> Self {
        Value::Flt(value)
    }
}

impl TryFrom<Value> for String {
    type Error = Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        if let Value::Str(v) = value {
            Ok(v.to_string())
        } else {
            Err(Error::TypeError)
        }
    }
}

impl TryFrom<Value> for Arc<str> {
    type Error = Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        if let Value::Str(v) = value {
            Ok(v)
        } else {
            Err(Error::TypeError)
        }
    }
}

impl From<String> for Value {
    fn from(value: String) -> Self {
        Value::Str(value.into())
    }
}

impl From<Arc<str>> for Value {
    fn from(value: Arc<str>) -> Self {
        Value::Str(value)
    }
}

impl From<&str> for Value {
    fn from(value: &str) -> Self {
        Value::Str(value.into())
    }
}

impl From<palette::LinSrgba<u8>> for Value {
    fn from(value: palette::LinSrgba<u8>) -> Self {
        Value::Color(value)
    }
}

impl TryFrom<Value> for palette::LinSrgba<u8> {
    type Error = Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        if let Value::Color(v) = value {
            Ok(v)
        } else {
            Err(Error::TypeError)
        }
    }
}

// Parses a color from a string. The only forms currently supported
// are "#RRGGBB" and "#RRGGBBAA" where the red, green, blue, and alpha
// portions are two hex digits. Even though this function takes a
// slice, it's a private function and we know we only call it when the
// slice has exactly 6 or 8 hex digits so we don't have to test to see
// if the result exceeds 0xffffff.

fn parse_color(s: &[u8]) -> Option<Value> {
    let mut result = 0u32;

    for ii in s {
        if ii.is_ascii_digit() {
            result = (result << 4) + (ii - b'0') as u32;
        } else if (b'A'..=b'F').contains(ii) {
            result = (result << 4) + (ii - b'A' + 10) as u32;
        } else if (b'a'..=b'f').contains(ii) {
            result = (result << 4) + (ii - b'a' + 10) as u32;
        } else {
            return None;
        }
    }

    if s.len() == 6 {
        result = (result << 8) + 255;
    }

    Some(Value::Color(palette::LinSrgba::new(
        (result >> 24) as u8,
        (result >> 16) as u8,
        (result >> 8) as u8,
        result as u8,
    )))
}

impl TryFrom<&toml::value::Value> for Value {
    type Error = Error;

    fn try_from(value: &toml::value::Value) -> Result<Self, Self::Error> {
        match value {
            toml::value::Value::Boolean(v) => Ok(Value::Bool(*v)),
            toml::value::Value::Integer(v) => i32::try_from(*v)
                .map(Value::Int)
                .map_err(|_| Error::TypeError),
            toml::value::Value::Float(v) => Ok(Value::Flt(*v)),
            toml::value::Value::String(v) => match v.as_bytes() {
                tmp @ &[b'#', _, _, _, _, _, _]
                | tmp @ &[b'#', _, _, _, _, _, _, _, _] => {
                    if let Some(v) = parse_color(&tmp[1..]) {
                        Ok(v)
                    } else {
                        Ok(Value::Str(v.to_owned().into()))
                    }
                }
                _ => Ok(Value::Str(v.to_owned().into())),
            },
            _ => Err(Error::TypeError),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::convert::TryFrom;

    #[test]
    fn test_device_values_to() {
        assert_eq!("false", format!("{}", Value::Bool(false)));
        assert_eq!("true", format!("{}", Value::Bool(true)));

        assert_eq!("0", format!("{}", Value::Int(0)));
        assert_eq!("1", format!("{}", Value::Int(1)));
        assert_eq!("-1", format!("{}", Value::Int(-1)));
        assert_eq!("-2147483648", format!("{}", Value::Int(-0x80000000)));
        assert_eq!("2147483647", format!("{}", Value::Int(0x7fffffff)));

        assert_eq!(
            "\"#010203\"",
            format!("{}", Value::Color(palette::LinSrgba::new(1, 2, 3, 255)))
        );
        assert_eq!(
            "\"#01020304\"",
            format!("{}", Value::Color(palette::LinSrgba::new(1, 2, 3, 4)))
        );
    }

    #[test]
    fn test_device_values_from() {
        assert_eq!(Value::Bool(true), Value::from(true));
        assert_eq!(Value::Bool(false), Value::from(false));

        assert_eq!(Value::Int(0), Value::from(0i32));
        assert_eq!(Value::Int(-1), Value::from(-1i32));
        assert_eq!(Value::Int(2), Value::from(2i32));
        assert_eq!(Value::Int(-3), Value::from(-3i16));
        assert_eq!(Value::Int(4), Value::from(4u16));

        assert_eq!(Value::Flt(5.0), Value::from(5.0f64));

        assert_eq!(Value::Str("hello".into()), "hello".into());

        // Cycle through 256 values.

        for ii in 1..=255u8 {
            let r: u8 = ii;
            let g: u8 = ii ^ 0xa5u8;
            let b: u8 = 255u8 - ii;
            let a: u8 = ii ^ 0x81u8;

            assert_eq!(
                Value::Color(palette::LinSrgba::new(r, g, b, a)),
                Value::from(palette::LinSrgba::new(r, g, b, a))
            );
        }
    }

    #[test]
    fn test_device_values_tryfrom() {
        // Check that we can convert bool values.

        assert_eq!(bool::try_from(Value::Bool(true)), Ok(true));
        assert!(bool::try_from(Value::Int(0)).is_err());
        assert!(bool::try_from(Value::Flt(0.0)).is_err());
        assert!(bool::try_from(Value::Str("hello".into())).is_err());

        // Check that we can convert i32 values.

        assert!(i32::try_from(Value::Bool(true)).is_err());
        assert_eq!(i32::try_from(Value::Int(0x7fffffffi32)), Ok(0x7fffffffi32));
        assert_eq!(
            i32::try_from(Value::Int(-0x80000000i32)),
            Ok(-0x80000000i32)
        );
        assert!(i32::try_from(Value::Flt(0.0)).is_err());
        assert!(i32::try_from(Value::Str("hello".into())).is_err());

        // Check that we can convert i16 values.

        assert!(i16::try_from(Value::Bool(true)).is_err());
        assert_eq!(i16::try_from(Value::Int(0x7fffi32)), Ok(0x7fffi16));
        assert_eq!(i16::try_from(Value::Int(-0x8000i32)), Ok(-0x8000i16));
        assert!(i16::try_from(Value::Int(0x8000i32)).is_err());
        assert!(i16::try_from(Value::Int(-0x8000i32 - 1i32)).is_err());
        assert!(i16::try_from(Value::Flt(0.0)).is_err());
        assert!(i16::try_from(Value::Str("hello".into())).is_err());

        // Check that we can convert u16 values.

        assert!(u16::try_from(Value::Bool(true)).is_err());
        assert_eq!(u16::try_from(Value::Int(0xffffi32)), Ok(0xffffu16));
        assert_eq!(u16::try_from(Value::Int(0i32)), Ok(0u16));
        assert!(u16::try_from(Value::Int(0x10000i32)).is_err());
        assert!(u16::try_from(Value::Int(-1i32)).is_err());
        assert!(u16::try_from(Value::Flt(0.0)).is_err());
        assert!(u16::try_from(Value::Str("hello".into())).is_err());
    }

    #[test]
    fn test_toml_value_tryfrom() {
        assert_eq!(
            Value::try_from(&toml::value::Value::Boolean(true)),
            Ok(Value::Bool(true))
        );
        assert_eq!(
            Value::try_from(&toml::value::Value::Boolean(false)),
            Ok(Value::Bool(false))
        );

        assert_eq!(
            Value::try_from(&toml::value::Value::Integer(0)),
            Ok(Value::Int(0))
        );
        assert_eq!(
            Value::try_from(&toml::value::Value::Integer(10)),
            Ok(Value::Int(10))
        );
        assert_eq!(
            Value::try_from(&toml::value::Value::Integer(-10)),
            Ok(Value::Int(-10))
        );
        assert_eq!(
            Value::try_from(&toml::value::Value::Integer(0x7fffffff)),
            Ok(Value::Int(0x7fffffff))
        );
        assert_eq!(
            Value::try_from(&toml::value::Value::Integer(-0x80000000)),
            Ok(Value::Int(-0x80000000))
        );
        assert!(
            Value::try_from(&toml::value::Value::Integer(-0x80000001)).is_err(),
        );
        assert!(
            Value::try_from(&toml::value::Value::Integer(0x80000000)).is_err(),
        );

        assert_eq!(
            Value::try_from(&toml::value::Value::Float(0.0)),
            Ok(Value::Flt(0.0))
        );
        assert_eq!(
            Value::try_from(&toml::value::Value::Float(10.0)),
            Ok(Value::Flt(10.0))
        );
        assert_eq!(
            Value::try_from(&toml::value::Value::Float(-10.0)),
            Ok(Value::Flt(-10.0))
        );

        assert_eq!(
            Value::try_from(&toml::value::Value::String("hello".into())),
            Ok(Value::Str("hello".into()))
        );

        assert_eq!(
            Value::try_from(&toml::value::Value::String("#".into())),
            Ok(Value::Str("#".into()))
        );
        assert_eq!(
            Value::try_from(&toml::value::Value::String("#1".into())),
            Ok(Value::Str("#1".into()))
        );
        assert_eq!(
            Value::try_from(&toml::value::Value::String("#12".into())),
            Ok(Value::Str("#12".into()))
        );
        assert_eq!(
            Value::try_from(&toml::value::Value::String("#123".into())),
            Ok(Value::Str("#123".into()))
        );
        assert_eq!(
            Value::try_from(&toml::value::Value::String("#1234".into())),
            Ok(Value::Str("#1234".into()))
        );
        assert_eq!(
            Value::try_from(&toml::value::Value::String("#12345".into())),
            Ok(Value::Str("#12345".into()))
        );
        assert_eq!(
            Value::try_from(&toml::value::Value::String("#1234567".into())),
            Ok(Value::Str("#1234567".into()))
        );
        assert_eq!(
            Value::try_from(&toml::value::Value::String("#123456789".into())),
            Ok(Value::Str("#123456789".into()))
        );
        assert_eq!(
            Value::try_from(&toml::value::Value::String("#1234567z".into())),
            Ok(Value::Str("#1234567z".into()))
        );

        // Cycle through 256 semi-random colors. Make sure the parsing
        // handles upper and lower case hex digits.

        for ii in 1..=255u8 {
            let r: u8 = ii;
            let g: u8 = ii ^ 0xa5u8;
            let b: u8 = 255u8 - ii;
            let a: u8 = ii ^ 0xc3u8;

            assert_eq!(
                Value::try_from(&toml::value::Value::String(format!(
                    "#{:02x}{:02x}{:02x}",
                    r, g, b
                )))
                .unwrap(),
                Value::Color(palette::LinSrgba::new(r, g, b, 255))
            );
            assert_eq!(
                Value::try_from(&toml::value::Value::String(format!(
                    "#{:02X}{:02X}{:02X}",
                    r, g, b
                )))
                .unwrap(),
                Value::Color(palette::LinSrgba::new(r, g, b, 255))
            );
            assert_eq!(
                Value::try_from(&toml::value::Value::String(format!(
                    "#{:02x}{:02x}{:02x}{:02x}",
                    r, g, b, a
                )))
                .unwrap(),
                Value::Color(palette::LinSrgba::new(r, g, b, a))
            );
            assert_eq!(
                Value::try_from(&toml::value::Value::String(format!(
                    "#{:02X}{:02X}{:02X}{:02X}",
                    r, g, b, a
                )))
                .unwrap(),
                Value::Color(palette::LinSrgba::new(r, g, b, a))
            );
        }

        assert!(Value::try_from(&toml::value::Value::Datetime(
            toml::value::Datetime {
                date: None,
                time: None,
                offset: None
            }
        ))
        .is_err());
        assert!(Value::try_from(&toml::value::Value::Array(vec![])).is_err());
        assert!(Value::try_from(&toml::value::Value::Table(
            toml::map::Map::new()
        ))
        .is_err());
    }
}