rstango 0.4.0

Implementation of the Tango distributed 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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
//! The values Tango devices exchange: a [`Value`] is a [`Buf`] of any element type and
//! dimensions Tango has, and what the arguments and results of handlers convert from and
//! into.

use std::fmt::{self, Debug};

use crate::buf::{Buf, Element, PackedElement};
use crate::error::{Error, ErrorKind};
use crate::dev::DevState;


// =========================== //
//          Tango data         //
// =========================== //

/// A single value, see [`Buf`].
pub type Scalar<T> = Buf<T, 0>;
/// A one-dimensional array of values, see [`Buf`].
pub type Spectrum<T> = Buf<T, 1>;
/// A two-dimensional array of values, in column-major order, see [`Buf`].
pub type Image<T> = Buf<T, 2>;

/// A value of an enumerated attribute: the index of its label among the labels of the
/// attribute, see [`crate::dev::AttrConfig::enum_labels`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[repr(transparent)]
pub struct DevEnum(pub i16);

/// A value of an encoded attribute or command: octets, and the name of the format they
/// are in, which is how a device sends what Tango has no type for, a compressed image
/// above all. Both share the message they were decoded out of.
///
/// Tango only has such a value as a scalar, an attribute of it being neither a spectrum
/// nor an image.
#[derive(Debug, Clone, PartialEq)]
pub struct DevEncoded {
    /// The name of the format the octets are in, such as `JPEG_RGB`, which is only a
    /// convention between the device and its clients.
    pub format: Scalar<str>,
    /// The octets themselves.
    pub data: Spectrum<u8>,
}

impl DevEncoded {
    /// An encoded value of that format, out of its octets.
    #[inline]
    pub fn new(format: impl Into<Scalar<str>>, data: impl Into<Spectrum<u8>>) -> Self {
        Self { format: format.into(), data: data.into() }
    }
}

/// Any value a Tango device exchanges, whatever its element type and dimensions: what a
/// backend encodes and decodes, and what the arguments and results of handlers are
/// converted from and into, with [`From`] and [`TryFrom`].
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    Void,
    Bool(ValueFormat<bool>),
    Octet(ValueFormat<u8>),
    UShort(ValueFormat<u16>),
    Short(ValueFormat<i16>),
    ULong(ValueFormat<u32>),
    Long(ValueFormat<i32>),
    ULong64(ValueFormat<u64>),
    Long64(ValueFormat<i64>),
    Float(ValueFormat<f32>),
    Double(ValueFormat<f64>),
    Enum(ValueFormat<DevEnum>),
    State(ValueFormat<DevState>),
    String(ValueFormat<str>),
    /// The `DevVarLongStringArray` a command may take or give.
    LongString(Spectrum<i32>, Spectrum<str>),
    /// The `DevVarDoubleStringArray` a command may take or give.
    DoubleString(Spectrum<f64>, Spectrum<str>),
    /// A [`DevEncoded`], which only exists as a scalar.
    Encoded(DevEncoded),
}

/// A data in any of the formats Tango has, as many dimensions as it has.
pub enum ValueFormat<T: Element + ?Sized> {
    Scalar(Scalar<T>),
    Spectrum(Spectrum<T>),
    Image(Image<T>),
}

macro_rules! impl_value_format {
    ( $( $variant:ident: $get:ident, $into:ident; )* ) => {
        impl<T: Element + ?Sized> ValueFormat<T> {
            $(
                #[doc = concat!("The data, if it is a ", stringify!($get), ".")]
                #[inline]
                pub fn $get(&self) -> Option<&$variant<T>> {
                    match self {
                        Self::$variant(data) => Some(data),
                        _ => None,
                    }
                }

                #[doc = concat!("The data, if it is a ", stringify!($get), ", or this format back.")]
                #[inline]
                pub fn $into(self) -> Result<$variant<T>, Self> {
                    match self {
                        Self::$variant(data) => Ok(data),
                        format => Err(format),
                    }
                }
            )*
        }
    };
}

impl_value_format! {
    Scalar: scalar, into_scalar;
    Spectrum: spectrum, into_spectrum;
    Image: image, into_image;
}

impl<T: Element + ?Sized> Clone for ValueFormat<T> {
    fn clone(&self) -> Self {
        match self {
            Self::Scalar(data) => Self::Scalar(data.clone()),
            Self::Spectrum(data) => Self::Spectrum(data.clone()),
            Self::Image(data) => Self::Image(data.clone()),
        }
    }
}

impl<T: Element + ?Sized> Debug for ValueFormat<T> {
    /// The data it holds, whose dimensions already tell its format.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Scalar(data) => data.fmt(f),
            Self::Spectrum(data) => data.fmt(f),
            Self::Image(data) => data.fmt(f),
        }
    }
}

impl<T: Element + ?Sized> PartialEq for ValueFormat<T>
where
    for<'a> T::Ref<'a>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Scalar(a), Self::Scalar(b)) => a == b,
            (Self::Spectrum(a), Self::Spectrum(b)) => a == b,
            (Self::Image(a), Self::Image(b)) => a == b,
            _ => false,
        }
    }
}

/// An element type Tango has: which variant of [`Value`] holds it, and what kinds it
/// is advertised as, see [`AttrData`] and [`CommandData`].
pub trait TangoElement: Element {

    /// The kind of an attribute of such values.
    const ATTR_KIND: AttrDataKind;
    /// The kind of a command argument of one such value, absent if none can be.
    const CMD_SCALAR_KIND: Option<CommandDataKind>;
    /// The kind of a command argument of an array of such values, absent if none can be.
    const CMD_ARRAY_KIND: Option<CommandDataKind>;

    fn wrap(format: ValueFormat<Self>) -> Value;
    fn unwrap(data: Value) -> Result<ValueFormat<Self>, Value>;
    fn unwrap_ref(data: &Value) -> Option<&ValueFormat<Self>>;

}

macro_rules! impl_tango_element {
    ($($ty:ty => $variant:ident, $scalar:expr, $array:expr;)*) => { $(
        impl TangoElement for $ty {

            const ATTR_KIND: AttrDataKind = AttrDataKind::$variant;
            const CMD_SCALAR_KIND: Option<CommandDataKind> = $scalar;
            const CMD_ARRAY_KIND: Option<CommandDataKind> = $array;

            #[inline]
            fn wrap(format: ValueFormat<Self>) -> Value {
                Value::$variant(format)
            }

            #[inline]
            fn unwrap(data: Value) -> Result<ValueFormat<Self>, Value> {
                match data {
                    Value::$variant(format) => Ok(format),
                    data => Err(data),
                }
            }

            #[inline]
            fn unwrap_ref(data: &Value) -> Option<&ValueFormat<Self>> {
                match data {
                    Value::$variant(format) => Some(format),
                    _ => None,
                }
            }

        }
    )* };
}

impl_tango_element! {
    bool => Bool, Some(CommandDataKind::Bool), Some(CommandDataKind::BoolArray);
    u8 => Octet, Some(CommandDataKind::Octet), Some(CommandDataKind::OctetArray);
    u16 => UShort, Some(CommandDataKind::UShort), Some(CommandDataKind::UShortArray);
    i16 => Short, Some(CommandDataKind::Short), Some(CommandDataKind::ShortArray);
    u32 => ULong, Some(CommandDataKind::ULong), Some(CommandDataKind::ULongArray);
    i32 => Long, Some(CommandDataKind::Long), Some(CommandDataKind::LongArray);
    u64 => ULong64, Some(CommandDataKind::ULong64), Some(CommandDataKind::ULong64Array);
    i64 => Long64, Some(CommandDataKind::Long64), Some(CommandDataKind::Long64Array);
    f32 => Float, Some(CommandDataKind::Float), Some(CommandDataKind::FloatArray);
    f64 => Double, Some(CommandDataKind::Double), Some(CommandDataKind::DoubleArray);
    DevEnum => Enum, None, None;
    DevState => State, Some(CommandDataKind::State), Some(CommandDataKind::StateArray);
    str => String, Some(CommandDataKind::String), Some(CommandDataKind::StringArray);
}

// =========================== //
//         Conversions         //
// =========================== //

/// A type a value converts into, failing with an [`Error`] when it holds something else:
/// every [`TryFrom<Value>`] whose error is one, [`Value`] itself included.
///
/// **Supporting trait**: it is only there to make this crate's API easier to use, it is
/// implemented for everything that API accepts and is not one to implement anywhere else.
pub trait FromValue: Sized {
    fn from_value(value: Value) -> Result<Self, Error>;
}

impl<T> FromValue for T
where
    T: TryFrom<Value>,
    T::Error: Into<Error>,
{
    #[inline]
    fn from_value(value: Value) -> Result<Self, Error> {
        T::try_from(value).map_err(Into::into)
    }
}

/// A type that converts into a value: every [`Into<Value>`], [`Value`] itself included, see
/// [`FromValue`] for the way back.
///
/// **Supporting trait**: it is only there to make this crate's API easier to use, it is
/// implemented for everything that API accepts and is not one to implement anywhere else.
pub trait IntoValue {
    fn into_value(self) -> Value;
}

impl<T: Into<Value>> IntoValue for T {
    #[inline]
    fn into_value(self) -> Value {
        self.into()
    }
}

/// The conversions between a value and a data of each of the formats it may hold.
macro_rules! impl_data_conversions {
    ( $( $variant:ident: $get:ident, $into:ident; )* ) => {
        $(
            impl<T: TangoElement + ?Sized> From<$variant<T>> for Value {
                #[inline]
                fn from(data: $variant<T>) -> Self {
                    T::wrap(ValueFormat::$variant(data))
                }
            }

            impl<T: TangoElement + ?Sized> TryFrom<Value> for $variant<T> {
                type Error = Error;
                fn try_from(data: Value) -> Result<Self, Error> {
                    T::unwrap(data)
                        .and_then(|format| format.$into().map_err(T::wrap))
                        .map_err(|data| Error::new(ErrorKind::InvalidData)
                            .with_description(format!("Value is not a {:?} {}", T::ATTR_KIND, stringify!($get)))
                            .with_append_description(format_args!("Got: {data:?}")))
                }
            }

            impl<'a, T: TangoElement + ?Sized> TryFrom<&'a Value> for &'a $variant<T> {
                type Error = Error;
                fn try_from(data: &'a Value) -> Result<Self, Error> {
                    T::unwrap_ref(data)
                        .and_then(ValueFormat::$get)
                        .ok_or_else(|| Error::new(ErrorKind::InvalidData)
                            .with_description(format!("Value is not a {:?} {}", T::ATTR_KIND, stringify!($get)))
                            .with_append_description(format_args!("Got: {data:?}")))
                }
            }
        )*
    };
}

impl_data_conversions! {
    Scalar: scalar, into_scalar;
    Spectrum: spectrum, into_spectrum;
    Image: image, into_image;
}

impl<T: TangoElement + PackedElement> From<T> for Value {
    #[inline]
    fn from(value: T) -> Self {
        Buf::<T, 0>::from(value).into()
    }
}

impl<T: TangoElement + PackedElement> From<&[T]> for Value {
    #[inline]
    fn from(values: &[T]) -> Self {
        Buf::from(values).into()
    }
}

impl<T: TangoElement + PackedElement> From<Vec<T>> for Value {
    #[inline]
    fn from(values: Vec<T>) -> Self {
        Buf::from(values).into()
    }
}

impl<T: TangoElement + PackedElement> From<Box<[T]>> for Value {
    #[inline]
    fn from(values: Box<[T]>) -> Self {
        Buf::from(values).into()
    }
}

impl<T: TangoElement + PackedElement, const N: usize> From<[T; N]> for Value {
    #[inline]
    fn from(values: [T; N]) -> Self {
        Buf::from(values).into()
    }
}

impl From<&str> for Value {
    #[inline]
    fn from(value: &str) -> Self {
        Buf::<str, 0>::from(value).into()
    }
}

impl From<String> for Value {
    #[inline]
    fn from(value: String) -> Self {
        Self::from(value.as_str())
    }
}

impl<const N: usize> From<[&str; N]> for Value {
    #[inline]
    fn from(values: [&str; N]) -> Self {
        Buf::<str, 1>::from(&values[..]).into()
    }
}

impl From<&[&str]> for Value {
    #[inline]
    fn from(values: &[&str]) -> Self {
        Buf::<str, 1>::from(values).into()
    }
}

impl From<Vec<String>> for Value {
    #[inline]
    fn from(values: Vec<String>) -> Self {
        Buf::<str, 1>::from(values.as_slice()).into()
    }
}

impl From<()> for Value {
    #[inline]
    fn from((): ()) -> Self {
        Self::Void
    }
}

impl From<(Buf<i32, 1>, Buf<str, 1>)> for Value {
    #[inline]
    fn from((longs, strings): (Buf<i32, 1>, Buf<str, 1>)) -> Self {
        Self::LongString(longs, strings)
    }
}

impl From<(Buf<f64, 1>, Buf<str, 1>)> for Value {
    #[inline]
    fn from((doubles, strings): (Buf<f64, 1>, Buf<str, 1>)) -> Self {
        Self::DoubleString(doubles, strings)
    }
}

impl From<DevEncoded> for Value {
    #[inline]
    fn from(encoded: DevEncoded) -> Self {
        Self::Encoded(encoded)
    }
}

macro_rules! impl_scalar_try_from {
    ($($ty:ty),*) => { $(
        impl TryFrom<Value> for $ty {
            type Error = Error;
            #[inline]
            fn try_from(data: Value) -> Result<Self, Error> {
                Self::try_from(&data)
            }
        }

        impl TryFrom<&Value> for $ty {
            type Error = Error;
            #[inline]
            fn try_from(data: &Value) -> Result<Self, Error> {
                <&Buf<$ty, 0>>::try_from(data).map(Buf::value)
            }
        }
    )* };
}

impl_scalar_try_from!(bool, u8, u16, i16, u32, i32, u64, i64, f32, f64, DevEnum, DevState);

impl<T: TangoElement + PackedElement> TryFrom<Value> for Vec<T> {
    type Error = Error;
    #[inline]
    fn try_from(data: Value) -> Result<Self, Error> {
        <&[T]>::try_from(&data).map(<[T]>::to_vec)
    }
}

impl<T: TangoElement + PackedElement> TryFrom<Value> for Box<[T]> {
    type Error = Error;
    #[inline]
    fn try_from(data: Value) -> Result<Self, Error> {
        <&[T]>::try_from(&data).map(Box::from)
    }
}

impl<T: TangoElement + PackedElement, const N: usize> TryFrom<Value> for [T; N] {
    type Error = Error;
    fn try_from(data: Value) -> Result<Self, Error> {
        let values = <&[T]>::try_from(&data)?;
        values.try_into().map_err(|_| Error::new(ErrorKind::InvalidData)
            .with_description(format!("Spectrum holds {} values where {N} were expected", values.len())))
    }
}

impl<'a, T: TangoElement + PackedElement> TryFrom<&'a Value> for &'a [T] {
    type Error = Error;
    #[inline]
    fn try_from(data: &'a Value) -> Result<Self, Error> {
        <&Buf<T, 1>>::try_from(data).map(Buf::as_slice)
    }
}

impl TryFrom<Value> for String {
    type Error = Error;
    #[inline]
    fn try_from(data: Value) -> Result<Self, Error> {
        <&str>::try_from(&data).map(str::to_string)
    }
}

impl<'a> TryFrom<&'a Value> for &'a str {
    type Error = Error;
    #[inline]
    fn try_from(data: &'a Value) -> Result<Self, Error> {
        <&Buf<str, 0>>::try_from(data).map(Buf::value)
    }
}

impl TryFrom<Value> for Vec<String> {
    type Error = Error;
    #[inline]
    fn try_from(data: Value) -> Result<Self, Error> {
        <&Buf<str, 1>>::try_from(&data).map(|strings| strings.iter().map(str::to_string).collect())
    }
}

impl TryFrom<Value> for () {
    type Error = Error;
    #[inline]
    fn try_from(data: Value) -> Result<Self, Error> {
        match data {
            Value::Void => Ok(()),
            data => Err(Error::new(ErrorKind::InvalidData)
                .with_description("Value is not void")
                .with_append_description(format_args!("Got: {data:?}"))),
        }
    }
}

impl TryFrom<Value> for (Buf<i32, 1>, Buf<str, 1>) {
    type Error = Error;
    #[inline]
    fn try_from(data: Value) -> Result<Self, Error> {
        match data {
            Value::LongString(longs, strings) => Ok((longs, strings)),
            data => Err(Error::new(ErrorKind::InvalidData)
                .with_description("Value is not a long string array")
                .with_append_description(format_args!("Got: {data:?}"))),
        }
    }
}

impl TryFrom<Value> for (Buf<f64, 1>, Buf<str, 1>) {
    type Error = Error;
    #[inline]
    fn try_from(data: Value) -> Result<Self, Error> {
        match data {
            Value::DoubleString(doubles, strings) => Ok((doubles, strings)),
            data => Err(Error::new(ErrorKind::InvalidData)
                .with_description("Value is not a double string array")
                .with_append_description(format_args!("Got: {data:?}"))),
        }
    }
}

impl TryFrom<Value> for DevEncoded {
    type Error = Error;
    #[inline]
    fn try_from(data: Value) -> Result<Self, Error> {
        match data {
            Value::Encoded(encoded) => Ok(encoded),
            data => Err(Error::new(ErrorKind::InvalidData)
                .with_description("Value is not encoded")
                .with_append_description(format_args!("Got: {data:?}"))),
        }
    }
}

impl<'a> TryFrom<&'a Value> for &'a DevEncoded {
    type Error = Error;
    #[inline]
    fn try_from(data: &'a Value) -> Result<Self, Error> {
        match data {
            Value::Encoded(encoded) => Ok(encoded),
            data => Err(Error::new(ErrorKind::InvalidData)
                .with_description("Value is not encoded")
                .with_append_description(format_args!("Got: {data:?}"))),
        }
    }
}

// =========================== //
//            Kinds            //
// =========================== //

/// The data kind of a Tango command argument. This is the closed set of types accepted
/// by `command_inout`, without any layout information (see [`CommandData`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CommandDataKind {
    Void,
    Bool,
    Octet,
    UShort,
    Short,
    ULong,
    Long,
    ULong64,
    Long64,
    Float,
    Double,
    State,
    String,
    BoolArray,
    OctetArray,
    UShortArray,
    ShortArray,
    ULongArray,
    LongArray,
    ULong64Array,
    Long64Array,
    FloatArray,
    DoubleArray,
    StateArray,
    StringArray,
    LongStringArray,
    DoubleStringArray,
    Encoded,
}

/// The element type of a Tango attribute value, its layout being an [`AttrDataFormat`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AttrDataKind {
    Bool,
    Octet,
    UShort,
    Short,
    ULong,
    Long,
    ULong64,
    Long64,
    Float,
    Double,
    State,
    String,
    /// An enumerated value, which travels as the index of its own label in the list of
    /// them: what those labels are is a property of the attribute a client may change, and
    /// lives in its configuration, see [`crate::dev::AttrConfig::enum_labels`].
    Enum,
    /// A [`DevEncoded`], only ever a scalar.
    Encoded,
}

/// The layout of a Tango attribute value.
/// 
/// The maximum size for spectrum and image formats is also given, those can be set to 0
/// when there is no maximum.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AttrDataFormat {
    Scalar,
    Spectrum(usize),
    Image(usize, usize),
}

/// A type an attribute value can be, and what kind and format it is advertised as.
pub trait AttrData {
    const DATA_KIND: AttrDataKind;
    const DATA_FORMAT: AttrDataFormat;
}

/// A type a command argument or result can be, and what kind it is advertised as.
pub trait CommandData {
    const DATA_KIND: CommandDataKind;
}

impl<T: TangoElement + ?Sized, const N: usize> AttrData for Buf<T, N> {
    const DATA_KIND: AttrDataKind = T::ATTR_KIND;
    const DATA_FORMAT: AttrDataFormat = match N {
        0 => AttrDataFormat::Scalar,
        1 => AttrDataFormat::Spectrum(0),
        2 => AttrDataFormat::Image(0, 0),
        _ => panic!("an attribute has at most two dimensions"),
    };
}

impl<T: TangoElement + ?Sized, const N: usize> CommandData for Buf<T, N> {
    const DATA_KIND: CommandDataKind = match (N, T::CMD_SCALAR_KIND, T::CMD_ARRAY_KIND) {
        (0, Some(kind), _) | (1, _, Some(kind)) => kind,
        (0 | 1, ..) => panic!("this element type cannot be a command argument"),
        _ => panic!("a command argument has at most one dimension"),
    };
}

/// Implement the kinds of these types as those of the data they convert to.
macro_rules! impl_kinds_as {
    ($({$($generics:tt)*} $ty:ty => $data:ty;)*) => { $(
        impl<$($generics)*> AttrData for $ty {
            const DATA_KIND: AttrDataKind = <$data as AttrData>::DATA_KIND;
            const DATA_FORMAT: AttrDataFormat = <$data as AttrData>::DATA_FORMAT;
        }

        impl<$($generics)*> CommandData for $ty {
            const DATA_KIND: CommandDataKind = <$data as CommandData>::DATA_KIND;
        }
    )* };
}

impl_kinds_as! {
    {T: TangoElement + PackedElement} T => Buf<T, 0>;
    {T: TangoElement + PackedElement} Vec<T> => Buf<T, 1>;
    {T: TangoElement + PackedElement} Box<[T]> => Buf<T, 1>;
    {T: TangoElement + PackedElement, const N: usize} [T; N] => Buf<T, 1>;
    {'a, T: TangoElement + PackedElement} &'a [T] => Buf<T, 1>;
    {} String => Buf<str, 0>;
    {'a} &'a str => Buf<str, 0>;
    {} Vec<String> => Buf<str, 1>;
    {'a, 'b} &'a [&'b str] => Buf<str, 1>;
}

impl CommandData for () {
    const DATA_KIND: CommandDataKind = CommandDataKind::Void;
}

impl CommandData for (Buf<i32, 1>, Buf<str, 1>) {
    const DATA_KIND: CommandDataKind = CommandDataKind::LongStringArray;
}

impl CommandData for (Buf<f64, 1>, Buf<str, 1>) {
    const DATA_KIND: CommandDataKind = CommandDataKind::DoubleStringArray;
}

impl AttrData for DevEncoded {
    const DATA_KIND: AttrDataKind = AttrDataKind::Encoded;
    const DATA_FORMAT: AttrDataFormat = AttrDataFormat::Scalar;
}

impl CommandData for DevEncoded {
    const DATA_KIND: CommandDataKind = CommandDataKind::Encoded;
}


// =========================== //
//       Encoded images        //
// =========================== //

impl DevEncoded {
    /// The format of a JPEG image in color, see [`Self::to_image`].
    pub const JPEG_RGB: &'static str = "JPEG_RGB";
    /// The format of a JPEG image in shades of gray, see [`Self::to_image`].
    pub const JPEG_GRAY8: &'static str = "JPEG_GRAY8";
    /// The format of raw 8 bits gray pixels, see [`EncodedPixels::Gray8`].
    pub const GRAY8: &'static str = "GRAY8";
    /// The format of raw 16 bits gray pixels, see [`EncodedPixels::Gray16`].
    pub const GRAY16: &'static str = "GRAY16";
    /// The format of raw 24 bits color pixels, see [`EncodedPixels::Rgb24`].
    pub const RGB24: &'static str = "RGB24";
}

/// The pixels of an image in one of the raw formats cppTango encodes images in, rows after
/// rows: in the dimensions of an image, the width comes first and varies fastest, the way
/// it does in an image attribute.
///
/// On the wire, such an image is its width and its height, both as big endian 16 bits
/// integers, and then its pixels.
#[derive(Debug, Clone, PartialEq)]
pub enum EncodedPixels {
    /// A [`DevEncoded::GRAY8`] image, sharing the octets of the value.
    Gray8(Image<u8>),
    /// A [`DevEncoded::GRAY16`] image, whose big endian pixels are converted.
    Gray16(Image<u16>),
    /// A [`DevEncoded::RGB24`] image, sharing the octets of the value, the three components
    /// of a pixel being the first dimension, then the width, then the height.
    Rgb24(Buf<u8, 3>),
}

impl DevEncoded {

    /// The pixels of an image in one of the raw formats, failing for any other format,
    /// JPEG included, see [`Self::to_image`] for that one.
    pub fn to_pixels(&self) -> Result<EncodedPixels, Error> {

        let format = self.format.value();
        let channels = match format {
            Self::GRAY8 => 1,
            Self::GRAY16 => 2,
            Self::RGB24 => 3,
            format => return Err(Error::new(ErrorKind::InvalidData)
                .with_description(format!("Encoded format {format:?} is not a raw image format"))),
        };

        let octets = self.data.as_slice();
        let [w_hi, w_lo, h_hi, h_lo, ..] = *octets else {
            return Err(Error::new(ErrorKind::InvalidData)
                .with_description(format!("Encoded {format} image has no dimensions")));
        };

        let width = u16::from_be_bytes([w_hi, w_lo]) as usize;
        let height = u16::from_be_bytes([h_hi, h_lo]) as usize;
        if octets.len() - 4 != width * height * channels {
            return Err(Error::new(ErrorKind::InvalidData)
                .with_description(format!("Encoded {format} image of {width}x{height} pixels holds {} octets where {} were expected",
                    octets.len() - 4, width * height * channels)));
        }

        let pixels = self.data.slice(4..);
        Ok(match channels {
            1 => EncodedPixels::Gray8(pixels.reshape([width, height]).expect("as many pixels as the dimensions")),
            2 => {
                let values = pixels.as_slice().as_chunks::<2>().0.iter()
                    .map(|pair| u16::from_be_bytes([pair[0], pair[1]]))
                    .collect::<Vec<_>>();
                EncodedPixels::Gray16(Image::from_slice(&values, [width, height]).expect("as many pixels as the dimensions"))
            }
            _ => EncodedPixels::Rgb24(pixels.reshape([3, width, height]).expect("as many pixels as the dimensions")),
        })

    }

    /// Encode these pixels in their raw format, failing for an image wider or higher than
    /// the 65535 pixels its dimensions have room for.
    pub fn from_pixels(pixels: &EncodedPixels) -> Result<Self, Error> {

        let (format, [width, height]) = match pixels {
            EncodedPixels::Gray8(image) => (Self::GRAY8, image.dim()),
            EncodedPixels::Gray16(image) => (Self::GRAY16, image.dim()),
            EncodedPixels::Rgb24(image) => {
                let [_, width, height] = image.dim();
                (Self::RGB24, [width, height])
            }
        };

        let (Ok(width), Ok(height)) = (u16::try_from(width), u16::try_from(height)) else {
            return Err(Error::new(ErrorKind::InvalidData)
                .with_description(format!("Image of {width}x{height} pixels is too large to be encoded")));
        };

        let mut data = Vec::new();
        data.extend_from_slice(&width.to_be_bytes());
        data.extend_from_slice(&height.to_be_bytes());
        match pixels {
            EncodedPixels::Gray8(image) => data.extend_from_slice(image.as_slice()),
            EncodedPixels::Gray16(image) => data.extend(image.as_slice().iter().flat_map(|pixel| pixel.to_be_bytes())),
            EncodedPixels::Rgb24(image) => data.extend_from_slice(image.as_slice()),
        }

        Ok(Self::new(format, data))

    }

    /// The image, in any of the formats cppTango encodes images in, JPEG included.
    #[cfg(feature = "image")]
    pub fn to_image(&self) -> Result<image::DynamicImage, Error> {

        use image::{DynamicImage, ImageBuffer, ImageFormat};

        fn image_err(err: image::ImageError) -> Error {
            Error::new(ErrorKind::InvalidData)
                .with_description("Failed to decode encoded image")
                .with_source(Box::new(err))
        }

        let format = self.format.value();
        if format == Self::JPEG_RGB || format == Self::JPEG_GRAY8 {
            return image::load_from_memory_with_format(self.data.as_slice(), ImageFormat::Jpeg).map_err(image_err);
        }

        Ok(match self.to_pixels()? {
            EncodedPixels::Gray8(pixels) => {
                let [width, height] = pixels.dim();
                DynamicImage::ImageLuma8(ImageBuffer::from_raw(width as u32, height as u32, pixels.as_slice().to_vec()).expect("as many pixels as the dimensions"))
            }
            EncodedPixels::Gray16(pixels) => {
                let [width, height] = pixels.dim();
                DynamicImage::ImageLuma16(ImageBuffer::from_raw(width as u32, height as u32, pixels.as_slice().to_vec()).expect("as many pixels as the dimensions"))
            }
            EncodedPixels::Rgb24(pixels) => {
                let [_, width, height] = pixels.dim();
                DynamicImage::ImageRgb8(ImageBuffer::from_raw(width as u32, height as u32, pixels.as_slice().to_vec()).expect("as many pixels as the dimensions"))
            }
        })

    }

    /// Encode the image in the raw format closest to it: gray images keep their depth, and
    /// any other one is converted to 8 bits color.
    #[cfg(feature = "image")]
    pub fn from_image(image: &image::DynamicImage) -> Result<Self, Error> {

        use image::DynamicImage;

        let dim = [image.width() as usize, image.height() as usize];
        let pixels = match image {
            DynamicImage::ImageLuma8(gray) => EncodedPixels::Gray8(Image::from_slice(gray.as_raw(), dim).expect("as many pixels as the dimensions")),
            DynamicImage::ImageLuma16(gray) => EncodedPixels::Gray16(Image::from_slice(gray.as_raw(), dim).expect("as many pixels as the dimensions")),
            image => EncodedPixels::Rgb24(Buf::from_slice(image.to_rgb8().as_raw(), [3, dim[0], dim[1]]).expect("as many pixels as the dimensions")),
        };

        Self::from_pixels(&pixels)

    }

}


#[cfg(test)]
mod tests {

    use super::*;

    /// A typed data converts into a value and back without copying, while the usual
    /// owned types convert by copying their values.
    #[test]
    fn value() {
        let spectrum = Buf::<f64, 1>::from(vec![1.0, 2.0]);
        let data = Value::from(spectrum.clone());
        assert!(!spectrum.is_unique());
        assert_eq!(Buf::<f64, 1>::try_from(data).unwrap().as_slice(), &[1.0, 2.0]);

        let values: Vec<f64> = Value::from(vec![1.0, 2.0]).try_into().unwrap();
        assert_eq!(values, [1.0, 2.0]);
        assert_eq!(i32::try_from(Value::from(3)).unwrap(), 3);
        assert_eq!(String::try_from(Value::from("text")).unwrap(), "text");
        assert_eq!(Vec::<String>::try_from(Value::from(&["a", "b"][..])).unwrap(), ["a", "b"]);
        assert!(<()>::try_from(Value::from(())).is_ok());
        assert_eq!(<[u8; 2]>::try_from(Value::from([1u8, 2])).unwrap(), [1, 2]);
        let encoded = DevEncoded::new("RAW", vec![1u8, 2]);
        assert_eq!(DevEncoded::try_from(Value::from(encoded.clone())).unwrap(), encoded);
        assert!(DevEncoded::try_from(Value::from(vec![1u8, 2])).is_err());
        assert!(<[u8; 3]>::try_from(Value::from([1u8, 2])).is_err());
    }

    /// A reference to a value converts into a reference to what it holds.
    #[test]
    fn value_borrowed() {
        let data = Value::from(vec![1u16, 2]);
        assert_eq!(<&[u16]>::try_from(&data).unwrap(), &[1, 2]);
        let data = Value::from("text");
        assert_eq!(<&str>::try_from(&data).unwrap(), "text");
        let data = Value::from(Buf::<u8, 2>::from_slice(&[1, 2, 3, 4], [2, 2]).unwrap());
        assert_eq!(<&Buf<u8, 2>>::try_from(&data).unwrap().get([1, 1]), Some(4));
    }

    /// Converting into another element type or other dimensions fails, saying what was
    /// expected and what was there.
    #[test]
    fn value_mismatch() {
        let err = Buf::<i32, 1>::try_from(Value::from(1.5)).unwrap_err();
        assert_eq!(err.description(), "Value is not a Long spectrum\nGot: Double(Buf(1.5))");
        assert!(f64::try_from(Value::from(vec![1.5])).is_err());
        // A short is not an enumerated value, even though both are 16 bits.
        assert!(DevEnum::try_from(Value::from(1i16)).is_err());
    }

    /// The kinds a type is advertised as follow from its element type and dimensions.
    #[test]
    fn kinds() {
        assert_eq!(<Buf<f64, 2> as AttrData>::DATA_FORMAT, AttrDataFormat::Image(0, 0));
        assert_eq!(<Vec<f64> as AttrData>::DATA_FORMAT, AttrDataFormat::Spectrum(0));
        assert_eq!(<Vec<f64> as CommandData>::DATA_KIND, CommandDataKind::DoubleArray);
        assert_eq!(<&str as CommandData>::DATA_KIND, CommandDataKind::String);
        assert_eq!(<DevEnum as AttrData>::DATA_KIND, AttrDataKind::Enum);
        assert_eq!(<() as CommandData>::DATA_KIND, CommandDataKind::Void);
        assert_eq!(<(Buf<i32, 1>, Buf<str, 1>) as CommandData>::DATA_KIND, CommandDataKind::LongStringArray);
        assert_eq!(<DevEncoded as AttrData>::DATA_KIND, AttrDataKind::Encoded);
        assert_eq!(<DevEncoded as AttrData>::DATA_FORMAT, AttrDataFormat::Scalar);
        assert_eq!(<DevEncoded as CommandData>::DATA_KIND, CommandDataKind::Encoded);
    }

    /// Values are equal when they hold the same data, wherever it is stored, and of the
    /// same element type.
    #[test]
    fn value_equality() {
        let spectrum = Buf::<i32, 1>::from([1, 2, 3, 4]);
        assert_eq!(Value::from(spectrum), Value::from(vec![1, 2, 3, 4]));
        assert_ne!(Value::from(1i16), Value::from(DevEnum(1)));
    }

    /// The raw formats go out with their dimensions ahead of their pixels and come back as
    /// they were, the 8 bits ones sharing the octets of the value.
    #[test]
    fn encoded_pixels() {

        let gray8 = EncodedPixels::Gray8(Image::from_slice(&[1u8, 2, 3, 4, 5, 6], [3, 2]).unwrap());
        let gray16 = EncodedPixels::Gray16(Image::from_slice(&[0x0102u16, 0xFFFE], [1, 2]).unwrap());
        let rgb24 = EncodedPixels::Rgb24(Buf::from_slice(&[1u8, 2, 3, 4, 5, 6], [3, 2, 1]).unwrap());

        for pixels in [gray8, gray16, rgb24] {
            let encoded = DevEncoded::from_pixels(&pixels).unwrap();
            assert_eq!(encoded.to_pixels().unwrap(), pixels);
        }

        let encoded = DevEncoded::from_pixels(&EncodedPixels::Gray16(Image::from_slice(&[0x0102u16], [1, 1]).unwrap())).unwrap();
        assert_eq!(encoded.format.value(), DevEncoded::GRAY16);
        assert_eq!(encoded.data.as_slice(), &[0, 1, 0, 1, 0x01, 0x02], "dimensions and pixels are big endian");

        let encoded = DevEncoded::new(DevEncoded::GRAY8, vec![0u8, 2, 0, 1, 7, 8]);
        let EncodedPixels::Gray8(image) = encoded.to_pixels().unwrap() else { panic!("not a GRAY8 image") };
        assert_eq!(image.get([1, 0]), Some(8));
        assert!(!encoded.data.is_unique(), "the pixels were copied out of the value");

    }

    /// An image whose octets do not add up to its dimensions, or in a format that is not a
    /// raw one, is refused.
    #[test]
    fn encoded_pixels_invalid() {
        assert!(DevEncoded::new(DevEncoded::GRAY8, vec![0u8, 2, 0, 2, 1]).to_pixels().is_err());
        assert!(DevEncoded::new(DevEncoded::RGB24, vec![0u8, 1]).to_pixels().is_err());
        assert!(DevEncoded::new(DevEncoded::JPEG_RGB, vec![0xFFu8, 0xD8]).to_pixels().is_err());
        let wide = EncodedPixels::Gray8(Image::from_slice(&vec![0u8; 70000], [70000, 1]).unwrap());
        assert!(DevEncoded::from_pixels(&wide).is_err());
    }

    /// An image goes through its closest raw format and comes back as it was, and a JPEG
    /// one is decoded whatever its depth.
    #[cfg(feature = "image")]
    #[test]
    fn encoded_image() {

        use image::{DynamicImage, GrayImage, ImageBuffer, ImageFormat, Luma, RgbImage};

        let gray8 = DynamicImage::ImageLuma8(GrayImage::from_raw(2, 1, vec![10, 20]).unwrap());
        let gray16 = DynamicImage::ImageLuma16(ImageBuffer::<Luma<u16>, _>::from_raw(1, 2, vec![1000, 2000]).unwrap());
        let rgb8 = DynamicImage::ImageRgb8(RgbImage::from_raw(1, 1, vec![1, 2, 3]).unwrap());

        for image in [gray8, gray16, rgb8] {
            assert_eq!(DevEncoded::from_image(&image).unwrap().to_image().unwrap(), image);
        }

        let mut jpeg = Vec::new();
        DynamicImage::ImageRgb8(RgbImage::from_pixel(8, 4, [200, 100, 50].into()))
            .write_to(&mut std::io::Cursor::new(&mut jpeg), ImageFormat::Jpeg)
            .unwrap();
        let image = DevEncoded::new(DevEncoded::JPEG_RGB, jpeg).to_image().unwrap();
        assert_eq!((image.width(), image.height()), (8, 4));

    }

}