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
//! Marshalling and unmarshalling of types from the Tango IDL.
//! 
//! See file:///usr/include/tango.idl, or any path you installed it.

use std::time::{Duration, SystemTime};
use std::borrow::Cow;
use std::fmt::Debug;

use crate::value::{AttrDataFormat, AttrDataKind, CommandDataKind, DevEncoded, DevEnum, TangoElement, Value, ValueFormat};
use crate::error::{Error, ErrorKind, ErrorSeverity, Result};
use crate::value::{Scalar, Spectrum};
use crate::buf::Buf;
use crate::dev::{AttrQuality, DevSource, DevState};

use super::orb::cdr::{CdrReader, CdrWriter, CdrRead, CdrWrite};


// ================= //
//   CORBA Support   //
// ================= //

/// Internal macro to generate a Tango repository ID.
macro_rules! tango_repo_id {
    ($ty:literal) => { concat!("IDL:Tango/", $ty, ":1.0") };
}

pub(crate) use tango_repo_id as tango_repo_id;
use uuid::Uuid;

mod command;
mod attr;
mod info;
mod history;

pub use command::{read_command_data, write_command_data};
pub use attr::{read_attr, read_attr_ready, write_attr, write_attr_ready};
pub use info::{read_attr_info, read_command_info, read_dev_info, write_attr_info, write_command_info, write_dev_info};
pub use history::{read_attr_history, read_command_history, write_attr_history, write_command_history};

// The typecode kinds constants used by Tango for the Any values transfered for commands
// and attributes!
const TK_NULL: u32 = 0;
const TK_VOID: u32 = 1;
const TK_SHORT: u32 = 2;
const TK_LONG: u32 = 3;
const TK_USHORT: u32 = 4;
const TK_ULONG: u32 = 5;
const TK_FLOAT: u32 = 6;
const TK_DOUBLE: u32 = 7;
const TK_BOOL: u32 = 8;
const TK_OCTET: u32 = 10;
const TK_STRUCT: u32 = 15;
const TK_ENUM: u32 = 17;
const TK_STRING: u32 = 18;
const TK_SEQUENCE: u32 = 19;
const TK_ALIAS: u32 = 21;
const TK_LONGLONG: u32 = 23;
const TK_ULONGLONG: u32 = 24;

// The 'AttributeDataType' discriminants of the attribute value union used from the IDL v4
// onward, in place of the Any the earlier versions carry.
const ATT_BOOL: u32 = 0;
const ATT_SHORT: u32 = 1;
const ATT_LONG: u32 = 2;
const ATT_LONG64: u32 = 3;
const ATT_FLOAT: u32 = 4;
const ATT_DOUBLE: u32 = 5;
const ATT_UCHAR: u32 = 6;
const ATT_USHORT: u32 = 7;
const ATT_ULONG: u32 = 8;
const ATT_ULONG64: u32 = 9;
const ATT_STRING: u32 = 10;
const ATT_STATE: u32 = 11;
const ATT_DEVICE_STATE: u32 = 12;
const ATT_ENCODED: u32 = 13;
const ATT_NO_DATA: u32 = 14;

// The 'AttrDataFormat' enumerators of the IDL, FMT_UNKNOWN being represented by the absence
// of a format.
const FMT_SCALAR: u32 = 0;
const FMT_SPECTRUM: u32 = 1;
const FMT_IMAGE: u32 = 2;
const FMT_UNKNOWN: u32 = 3;

// The 'CmdArgType' enumerators, which the IDL does not declare but that the data_type
// field of an attribute value from v5 onward holds, as well as the input and output types
// of a command and the type of an attribute in its configuration. For an attribute this is
// always the scalar element type whatever the format of the value is, the array
// enumerators only ever being the type of a command.
//
// Note that this is the *declared* type of the attribute and not the one of the union
// arm carrying it, which are only the same as long as no DevEnum is involved: those
// travel as shorts, and data_type is the only thing telling them from a real DevShort.
// We have no enumerated variant in the data module, so the two always match for us.
//
// See 'CmdArgType' in tango_const.h, whose 27 is deliberately left out, having been an
// unused enumerator that was removed while keeping the following ones where they were.
const DEV_VOID: i32 = 0;
const DEV_BOOLEAN: i32 = 1;
const DEV_SHORT: i32 = 2;
const DEV_LONG: i32 = 3;
const DEV_FLOAT: i32 = 4;
const DEV_DOUBLE: i32 = 5;
const DEV_USHORT: i32 = 6;
const DEV_ULONG: i32 = 7;
const DEV_STRING: i32 = 8;
const DEVVAR_CHARARRAY: i32 = 9;
const DEVVAR_SHORTARRAY: i32 = 10;
const DEVVAR_LONGARRAY: i32 = 11;
const DEVVAR_FLOATARRAY: i32 = 12;
const DEVVAR_DOUBLEARRAY: i32 = 13;
const DEVVAR_USHORTARRAY: i32 = 14;
const DEVVAR_ULONGARRAY: i32 = 15;
const DEVVAR_STRINGARRAY: i32 = 16;
const DEVVAR_LONGSTRINGARRAY: i32 = 17;
const DEVVAR_DOUBLESTRINGARRAY: i32 = 18;
const DEV_STATE: i32 = 19;
const CONST_DEV_STRING: i32 = 20;
const DEVVAR_BOOLEANARRAY: i32 = 21;
const DEV_UCHAR: i32 = 22;
const DEV_LONG64: i32 = 23;
const DEV_ULONG64: i32 = 24;
const DEVVAR_LONG64ARRAY: i32 = 25;
const DEVVAR_ULONG64ARRAY: i32 = 26;
const DEV_ENCODED: i32 = 28;
const DEV_ENUM: i32 = 29;
const DEV_PIPE_BLOB: i32 = 30;
const DEVVAR_STATEARRAY: i32 = 31;
const DEVVAR_ENCODEDARRAY: i32 = 32;
const DATA_TYPE_UNKNOWN: i32 = 100;

// The 'DispLevel' enumerators, carried by the command and attribute configurations.
const DL_OPERATOR: u32 = 0;
const DL_EXPERT: u32 = 1;
const DL_UNKNOWN: u32 = 2;

// The 'AttrWriteType' enumerators, carried by the attribute configuration.
const WT_READ: u32 = 0;
const WT_READ_WITH_WRITE: u32 = 1;
const WT_WRITE: u32 = 2;
const WT_READ_WRITE: u32 = 3;
const WT_UNKNOWN: u32 = 4;

// The strings cppTango sends for a configuration property a device has no value for, which
// we give back as no value at all, an empty string doing the same. See tango_const.h, where
// they are respectively AlrmValueNotSpec, NotANumber, LabelNotSpec, DescNotSpec,
// StdUnitNotSpec, DispUnitNotSpec and NotSet.
//
// Note that the display format has no placeholder of its own, FormatNotSpec being "%6.2f",
// a real format that a device means, so only NOT_SPECIFIED stands for an unset one. And an
// unset label is sent as the name of the attribute, as cppTango does, NO_LABEL only being
// accepted from a client that means to reset it.
const NOT_SPECIFIED: &str = "Not specified";
const NOT_A_NUMBER: &str = "NaN";
const NO_LABEL: &str = "No label";
const NO_DESCRIPTION: &str = "No description";
const NO_STANDARD_UNIT: &str = "No standard unit";
const NO_DISPLAY_UNIT: &str = "No display unit";
const UNINITIALIZED: &str = "Uninitialised";

// ================= //
//  Simple adapters  //
// ================= //

/// Internal macro to generate a CDR adapter for an enumeration.
macro_rules! def_cdr_enum_adapter {
    ( $enum:ty { $( $variant:ident = $value:literal, )* } ) => {

        impl CdrRead<'_> for $enum {
            fn read(buf: &mut CdrReader<'_>) -> Result<Self> {
                Ok(match buf.read_ulong()? {
                    $( $value => Self::$variant,)*
                    id => return Err(Error::new(ErrorKind::InvalidData)
                        .with_description(format!(concat!(stringify!($enum), " numeric value {} is invalid"), id))),
                })
            }
        }

        impl CdrWrite for $enum {
            fn write(&self, buf: &mut CdrWriter) -> Result<()> {
                buf.write_ulong(match self {
                    $( Self::$variant => $value,)*
                })
            }
        }

    };
}

def_cdr_enum_adapter!(ErrorSeverity {
    Warning = 0,
    Error = 1,
    Panic = 2,
});

def_cdr_enum_adapter!(DevState {
    On = 0,
    Off = 1,
    Close = 2,
    Open = 3,
    Insert = 4,
    Extract = 5,
    Moving = 6,
    Standby = 7,
    Fault = 8,
    Init = 9,
    Running = 10,
    Alarm = 11,
    Disable = 12,
    Unknown = 13,
});

def_cdr_enum_adapter!(DevSource {
    Dev = 0,
    Cache = 1,
    CacheDev = 2,
});

def_cdr_enum_adapter!(AttrQuality {
    Valid = 0,
    Invalid = 1,
    Alarm = 2,
    Changing = 3,
    Warning = 4,
});

impl CdrRead<'_> for Option<Error> {
    fn read(buf: &mut CdrReader<'_>) -> Result<Self> {
        
        let mut top_err = None;

        // A dev failed contains only one sequence of DevError structures...
        let len = buf.read_sequence_len()?;
        for _ in 0..len {

            let reason = buf.read_string()?;
            let mut err = Error::new(ErrorKind::Reason(&reason));
            err.set_severity(buf.read()?);
            err.set_description(buf.read_string()?.into_owned());
            err.set_origin(buf.read_string()?.into_owned());

            if let Some(parent_err) = top_err.take() {
                err.set_parent(parent_err);
            }

            top_err = Some(err);

        }

        Ok(top_err)

    }
}

impl CdrWrite for Option<Error> {
    #[inline]
    fn write(&self, buf: &mut CdrWriter) -> Result<()> {
        buf.write(&self.as_ref())
    }
}

impl CdrWrite for Option<&Error> {
    #[inline]
    fn write(&self, buf: &mut CdrWriter) -> Result<()> {
        if let Some(error) = self {
            buf.write(error)
        } else {
            buf.write_sequence_len(0)
        }
    }
}

impl CdrWrite for Error {
    #[inline]
    fn write(&self, buf: &mut CdrWriter) -> Result<()> {
        
        // The chain is walked from the error down to its deepest parent, which is the order
        // the reading above builds it back from, so it goes out reversed.
        let mut chain = Vec::new();
        let mut next = Some(self);
        while let Some(err) = next {
            chain.push(err);
            next = err.parent();
        }

        buf.write_sequence_len(chain.len())?;
        for err in chain.iter().rev() {
            buf.write_string(err.reason())?;
            buf.write(&err.severity())?;
            buf.write_string(err.description())?;
            buf.write_string(err.origin())?;
        }

        Ok(())

    }
}

impl CdrRead<'_> for Error {
    fn read(buf: &mut CdrReader<'_>) -> Result<Self> {
        let err = buf.read::<Option<Error>>()?;
        err.ok_or_else(|| Error::new(ErrorKind::InvalidData)
            .with_description("The given DevFailed should have at least one error"))
    }
}

impl CdrRead<'_> for SystemTime {

    /// Read a `TimeVal`, which is three longs and nothing else, so nothing about one says
    /// it holds a time: a sender with no time to give sends whatever it has.
    ///
    /// cppTango is such a sender. `TimeVal` is generated without a constructor and
    /// `DeviceAttribute::time` declared without an initializer, so the timestamp of a
    /// write request is whatever was on the client's stack — seen here as the halves of a
    /// pointer, the seconds and the nanoseconds 28 apart and the microseconds a steady
    /// `0x7Fxx`, and negative about a third of the time.
    ///
    /// Which is why a component that cannot be part of a time is taken as no time at all
    /// rather than as a reason to fail. Failing here would refuse a whole request over a
    /// field nothing reads: a server drops the timestamp of a write, see
    /// [`super::read_attr_values`], and a reply for an attribute that failed carries no
    /// time either. The arithmetic cannot overflow either, which would be a panic in a debug
    /// build and a time quietly wrong in a release build.
    fn read(buf: &mut CdrReader<'_>) -> Result<Self> {

        let tv_sec = buf.read_long()?;
        let tv_usec = buf.read_long()?;
        let tv_nsec = buf.read_long()?;

        // Each of the three is a count of something, so a negative one is not a time that
        // is merely wrong: it is a field that was never filled in.
        let (Ok(secs), Ok(usecs), Ok(nsecs)) = (
            u64::try_from(tv_sec),
            u64::try_from(tv_usec),
            u64::try_from(tv_nsec),
        ) else {
            return Ok(SystemTime::UNIX_EPOCH);
        };

        let since_epoch = Duration::from_secs(secs)
            .checked_add(Duration::from_micros(usecs))
            .and_then(|elapsed| elapsed.checked_add(Duration::from_nanos(nsecs)));

        Ok(since_epoch
            .and_then(|since_epoch| SystemTime::UNIX_EPOCH.checked_add(since_epoch))
            .unwrap_or(SystemTime::UNIX_EPOCH))

    }

}

impl CdrWrite for SystemTime {
    fn write(&self, buf: &mut CdrWriter) -> Result<()> {

        let since_epoch = self.duration_since(SystemTime::UNIX_EPOCH)
            .map_err(|_| Error::new(ErrorKind::InvalidData)
                .with_description("Failed to write a system time that is before the UNIX epoch"))?;

        // The three components are longs in the IDL, so the seconds are bounded like any
        // 32 bits UNIX timestamp is.
        let tv_sec = i32::try_from(since_epoch.as_secs())
            .map_err(|_| Error::new(ErrorKind::InvalidData)
                .with_description("Failed to write a system time whose seconds do not fit into a long"))?;

        // Splitting the sub-second part the way the reading above puts it back together.
        let subsec_nanos = since_epoch.subsec_nanos();

        buf.write_long(tv_sec)?;
        buf.write_long((subsec_nanos / 1_000) as i32)?;
        buf.write_long((subsec_nanos % 1_000) as i32)

    }
}

/// Equivalent to `ClntIdent` in the IDL.
/// 
/// TODO: For now we don't support IDL v6 OpenTelemetry trace context!
#[derive(Debug,)]
pub enum ClientIdent<'a> {
    Cpp {
        id: u32,
    },
    Java {
        main_class: Cow<'a, str>,
        uuid: Uuid,
    },
}

impl CdrWrite for ClientIdent<'_> {
    fn write(&self, buf: &mut CdrWriter) -> Result<()> {
        match self {
            ClientIdent::Cpp { id } => {
                buf.write_ulong(0)?;
                buf.write_ulong(*id)?;
            }
            ClientIdent::Java { main_class, uuid } => {
                buf.write_ulong(1)?;
                buf.write_string(main_class)?;
                // 'JavaUUID' is 'unsigned long long[2]', an array and not a sequence, so
                // it has no length, but it is 8-aligned like any long long. The pair is
                // most-significant first, matching Java's UUID accessors.
                let (msb, lsb) = uuid.as_u64_pair();
                buf.write_ulonglong_slice(&[msb, lsb])?;
            }
        }
        Ok(())
    }
}

// ================= //
//   Element types   //
// ================= //

/// How the values of a Tango element type travel, and how they are announced: the typecode
/// of a scalar of them in an `any`, the repository ID of the alias of a sequence of them,
/// the discriminant of their arm of the attribute value union, and their declared type.
trait CdrTangoElement: TangoElement {
    const TK: u32;
    const ARRAY_REPO_ID: &'static str;
    const ATT: u32;
    const DEV_TYPE: i32;
    /// Read `len` values, without the length that precedes a sequence.
    fn read_values(buf: &mut CdrReader<'_>, len: usize) -> Result<Spectrum<Self>>;
    /// Write the values of that data, in column-major order and without the length that
    /// precedes a sequence.
    fn write_values<const N: usize>(buf: &mut CdrWriter, data: &Buf<Self, N>) -> Result<()>;
}

/// The CDR primitives, whose arrays are shared out of the message, see
/// [`CdrReader::read_buf`].
macro_rules! impl_cdr_tango_element {
    ( $( $ty:ty => $tk:ident, $array:literal, $att:ident, $dev:ident; )* ) => {
        $(
            impl CdrTangoElement for $ty {
                const TK: u32 = $tk;
                const ARRAY_REPO_ID: &'static str = tango_repo_id!($array);
                const ATT: u32 = $att;
                const DEV_TYPE: i32 = $dev;
                fn read_values(buf: &mut CdrReader<'_>, len: usize) -> Result<Spectrum<Self>> {
                    buf.read_buf(len)
                }
                fn write_values<const N: usize>(buf: &mut CdrWriter, data: &Buf<Self, N>) -> Result<()> {
                    buf.write_data(data)
                }
            }
        )*
    };
}

impl_cdr_tango_element! {
    bool => TK_BOOL, "DevVarBooleanArray", ATT_BOOL, DEV_BOOLEAN;
    u8 => TK_OCTET, "DevVarCharArray", ATT_UCHAR, DEV_UCHAR;
    u16 => TK_USHORT, "DevVarUShortArray", ATT_USHORT, DEV_USHORT;
    i16 => TK_SHORT, "DevVarShortArray", ATT_SHORT, DEV_SHORT;
    u32 => TK_ULONG, "DevVarULongArray", ATT_ULONG, DEV_ULONG;
    i32 => TK_LONG, "DevVarLongArray", ATT_LONG, DEV_LONG;
    u64 => TK_ULONGLONG, "DevVarULong64Array", ATT_ULONG64, DEV_ULONG64;
    i64 => TK_LONGLONG, "DevVarLong64Array", ATT_LONG64, DEV_LONG64;
    f32 => TK_FLOAT, "DevVarFloatArray", ATT_FLOAT, DEV_FLOAT;
    f64 => TK_DOUBLE, "DevVarDoubleArray", ATT_DOUBLE, DEV_DOUBLE;
    // An enumeration travels as the short it is, only its declared type telling it apart.
    DevEnum => TK_SHORT, "DevVarShortArray", ATT_SHORT, DEV_ENUM;
}

/// A state is an enum, which is an ulong on the wire and one octet in memory, so its values
/// are always copied.
impl CdrTangoElement for DevState {
    const TK: u32 = TK_ENUM;
    const ARRAY_REPO_ID: &'static str = tango_repo_id!("DevVarStateArray");
    const ATT: u32 = ATT_STATE;
    const DEV_TYPE: i32 = DEV_STATE;
    fn read_values(buf: &mut CdrReader<'_>, len: usize) -> Result<Spectrum<Self>> {
        buf.read_vec(len).map(Buf::from)
    }
    fn write_values<const N: usize>(buf: &mut CdrWriter, data: &Buf<Self, N>) -> Result<()> {
        data.iter().try_for_each(|state| buf.write(&state))
    }
}

impl CdrTangoElement for str {
    const TK: u32 = TK_STRING;
    const ARRAY_REPO_ID: &'static str = tango_repo_id!("DevVarStringArray");
    const ATT: u32 = ATT_STRING;
    const DEV_TYPE: i32 = DEV_STRING;
    fn read_values(buf: &mut CdrReader<'_>, len: usize) -> Result<Spectrum<Self>> {
        buf.read_string_buf(len)
    }
    fn write_values<const N: usize>(buf: &mut CdrWriter, data: &Buf<Self, N>) -> Result<()> {
        buf.write_string_data(data)
    }
}

/// Read a sequence, its length included.
fn read_seq<T: CdrTangoElement + ?Sized>(buf: &mut CdrReader<'_>) -> Result<Spectrum<T>> {
    let len = buf.read_sequence_len()?;
    T::read_values(buf, len)
}

/// Write a sequence, its length included.
fn write_seq<T: CdrTangoElement + ?Sized, const N: usize>(buf: &mut CdrWriter, data: &Buf<T, N>) -> Result<()> {
    buf.write_sequence_len(data.len())?;
    T::write_values(buf, data)
}

/// Read a single value, as the scalar it is.
fn read_scalar<T: CdrTangoElement + ?Sized>(buf: &mut CdrReader<'_>) -> Result<Value> {
    let value = T::read_values(buf, 1)?.into_scalar().expect("a single value was read");
    Ok(T::wrap(ValueFormat::Scalar(value)))
}

/// Read a sequence, as the spectrum it is.
fn read_spectrum<T: CdrTangoElement + ?Sized>(buf: &mut CdrReader<'_>) -> Result<Value> {
    Ok(T::wrap(ValueFormat::Spectrum(read_seq(buf)?)))
}

fn write_scalar_tc(buf: &mut CdrWriter, tk: u32) -> Result<()> {

    buf.write_ulong(tk)?;

    if tk == TK_STRING {
        buf.write_ulong(0)?;  // unbounded string!
    } else if tk == TK_ENUM {
        buf.write_encapsulation(|param| {
            param.write_string(tango_repo_id!("DevState"))?;
            param.write_string("DevState")?;
            param.write(&["ON", "OFF", "CLOSE", "OPEN", "INSERT", "EXTRACT", "MOVING", "STANDBY", "FAULT", "INIT", "RUNNING", "ALARM", "DISABLE", "UNKNOWN"])
        })?;
    }

    Ok(())

}

fn write_array_tc(buf: &mut CdrWriter, tk: u32, repo_id: &str) -> Result<()> {

    let name = &repo_id[10..repo_id.len() - 4];

    buf.write_ulong(TK_ALIAS)?;

    buf.write_encapsulation(|alias| {
        alias.write_string(repo_id)?;
        alias.write_string(name)?;
        alias.write_ulong(TK_SEQUENCE)?;
        alias.write_encapsulation(|sequence| {
            write_scalar_tc(sequence, tk)?;
            sequence.write_ulong(0)  // unbounded sequence!
        })
    })

}

fn write_any_string_array_tc(buf: &mut CdrWriter, repo_id: &str, first_name: &str, first_tk: u32, first_repo_id: &str) -> Result<()> {

    let name = &repo_id[10..repo_id.len() - 4];

    buf.write_ulong(TK_STRUCT)?;

    buf.write_encapsulation(|param| {

        param.write_string(repo_id)?;
        param.write_string(name)?;

        // The parameters of a tk_struct carry the number of members before the members
        // themselves, and a server refuses the whole request with a marshalling error when
        // it is missing. Note that the reading side skips this, only ever taking the
        // repository ID out of the parameters.
        param.write_ulong(2)?;

        param.write_string(first_name)?;
        write_array_tc(param, first_tk, first_repo_id)?;
        param.write_string("svalue")?;
        write_array_tc(param, TK_STRING, tango_repo_id!("DevVarStringArray"))

    })

}

/// Write the TypeCode of a `DevEncoded`, whose format is a `DevString` and not a bare
/// string, the IDL declaring it through that alias.
fn write_encoded_tc(buf: &mut CdrWriter) -> Result<()> {

    buf.write_ulong(TK_STRUCT)?;

    buf.write_encapsulation(|param| {
        param.write_string(tango_repo_id!("DevEncoded"))?;
        param.write_string("DevEncoded")?;
        param.write_ulong(2)?;
        param.write_string("encoded_format")?;
        param.write_ulong(TK_ALIAS)?;
        param.write_encapsulation(|alias| {
            alias.write_string(tango_repo_id!("DevString"))?;
            alias.write_string("DevString")?;
            write_scalar_tc(alias, TK_STRING)
        })?;
        param.write_string("encoded_data")?;
        write_array_tc(param, u8::TK, u8::ARRAY_REPO_ID)
    })

}

/// Read a `DevEncoded`, its format and its octets sharing the message.
fn read_encoded(buf: &mut CdrReader<'_>) -> Result<DevEncoded> {
    Ok(DevEncoded { format: buf.read::<Scalar<str>>()?, data: read_seq(buf)? })
}

/// Write a `DevEncoded`.
fn write_encoded(buf: &mut CdrWriter, encoded: &DevEncoded) -> Result<()> {
    buf.write_string(encoded.format.value())?;
    write_seq(buf, &encoded.data)
}

// ================= //
//    Data types     //
// ================= //

/// The command data kind of a `CmdArgType`, which is what both the input and the output of
/// a command are announced with, the array enumerators included.
fn command_data_kind(data_type: i32) -> Result<CommandDataKind> {
    Ok(match data_type {
        DEV_VOID => CommandDataKind::Void,
        DEV_BOOLEAN => CommandDataKind::Bool,
        DEV_UCHAR => CommandDataKind::Octet,
        DEV_USHORT => CommandDataKind::UShort,
        DEV_SHORT => CommandDataKind::Short,
        DEV_ULONG => CommandDataKind::ULong,
        DEV_LONG => CommandDataKind::Long,
        DEV_ULONG64 => CommandDataKind::ULong64,
        DEV_LONG64 => CommandDataKind::Long64,
        DEV_FLOAT => CommandDataKind::Float,
        DEV_DOUBLE => CommandDataKind::Double,
        DEV_STATE => CommandDataKind::State,
        // A constant string is a string that the device promises not to free, which is a
        // C++ lifetime matter that changes nothing on the wire.
        DEV_STRING | CONST_DEV_STRING => CommandDataKind::String,
        // A DevEnum travels as a short and its labels only live in the configuration of an
        // attribute, so a command carrying one carries a short.
        DEV_ENUM => CommandDataKind::Short,
        DEVVAR_BOOLEANARRAY => CommandDataKind::BoolArray,
        DEVVAR_CHARARRAY => CommandDataKind::OctetArray,
        DEVVAR_USHORTARRAY => CommandDataKind::UShortArray,
        DEVVAR_SHORTARRAY => CommandDataKind::ShortArray,
        DEVVAR_ULONGARRAY => CommandDataKind::ULongArray,
        DEVVAR_LONGARRAY => CommandDataKind::LongArray,
        DEVVAR_ULONG64ARRAY => CommandDataKind::ULong64Array,
        DEVVAR_LONG64ARRAY => CommandDataKind::Long64Array,
        DEVVAR_FLOATARRAY => CommandDataKind::FloatArray,
        DEVVAR_DOUBLEARRAY => CommandDataKind::DoubleArray,
        DEVVAR_STATEARRAY => CommandDataKind::StateArray,
        DEVVAR_STRINGARRAY => CommandDataKind::StringArray,
        DEVVAR_LONGSTRINGARRAY => CommandDataKind::LongStringArray,
        DEVVAR_DOUBLESTRINGARRAY => CommandDataKind::DoubleStringArray,
        DEV_ENCODED => CommandDataKind::Encoded,
        data_type => return Err(unsupported_data_type_err(data_type)),
    })
}

/// The attribute data kind of a `CmdArgType`, which is what the data type of an attribute
/// configuration holds, always the type of an element and never an array one whatever the
/// format of the attribute is.
fn attr_data_kind(data_type: i32) -> Result<AttrDataKind> {
    Ok(match data_type {
        DEV_BOOLEAN => AttrDataKind::Bool,
        DEV_UCHAR => AttrDataKind::Octet,
        DEV_USHORT => AttrDataKind::UShort,
        DEV_SHORT => AttrDataKind::Short,
        DEV_ULONG => AttrDataKind::ULong,
        DEV_LONG => AttrDataKind::Long,
        DEV_ULONG64 => AttrDataKind::ULong64,
        DEV_LONG64 => AttrDataKind::Long64,
        DEV_FLOAT => AttrDataKind::Float,
        DEV_DOUBLE => AttrDataKind::Double,
        DEV_STATE => AttrDataKind::State,
        DEV_STRING | CONST_DEV_STRING => AttrDataKind::String,
        // A DevEnum attribute travels as a short, the labels of its configuration being the
        // only thing telling it from one and giving a meaning to its values, which are the
        // indices in that list, see [`AttrConfig::enum_labels`].
        DEV_ENUM => AttrDataKind::Enum,
        DEV_ENCODED => AttrDataKind::Encoded,
        data_type => return Err(unsupported_data_type_err(data_type)),
    })
}

/// The `CmdArgType` of a command data kind, the mirror of [`command_data_kind`].
fn command_data_type(kind: &CommandDataKind) -> i32 {
    match kind {
        CommandDataKind::Void => DEV_VOID,
        CommandDataKind::Bool => DEV_BOOLEAN,
        CommandDataKind::Octet => DEV_UCHAR,
        CommandDataKind::UShort => DEV_USHORT,
        CommandDataKind::Short => DEV_SHORT,
        CommandDataKind::ULong => DEV_ULONG,
        CommandDataKind::Long => DEV_LONG,
        CommandDataKind::ULong64 => DEV_ULONG64,
        CommandDataKind::Long64 => DEV_LONG64,
        CommandDataKind::Float => DEV_FLOAT,
        CommandDataKind::Double => DEV_DOUBLE,
        CommandDataKind::State => DEV_STATE,
        CommandDataKind::String => DEV_STRING,
        CommandDataKind::BoolArray => DEVVAR_BOOLEANARRAY,
        CommandDataKind::OctetArray => DEVVAR_CHARARRAY,
        CommandDataKind::UShortArray => DEVVAR_USHORTARRAY,
        CommandDataKind::ShortArray => DEVVAR_SHORTARRAY,
        CommandDataKind::ULongArray => DEVVAR_ULONGARRAY,
        CommandDataKind::LongArray => DEVVAR_LONGARRAY,
        CommandDataKind::ULong64Array => DEVVAR_ULONG64ARRAY,
        CommandDataKind::Long64Array => DEVVAR_LONG64ARRAY,
        CommandDataKind::FloatArray => DEVVAR_FLOATARRAY,
        CommandDataKind::DoubleArray => DEVVAR_DOUBLEARRAY,
        CommandDataKind::StateArray => DEVVAR_STATEARRAY,
        CommandDataKind::StringArray => DEVVAR_STRINGARRAY,
        CommandDataKind::LongStringArray => DEVVAR_LONGSTRINGARRAY,
        CommandDataKind::DoubleStringArray => DEVVAR_DOUBLESTRINGARRAY,
        CommandDataKind::Encoded => DEV_ENCODED,
    }
}

/// The `CmdArgType` of an attribute data kind, the mirror of [`attr_data_kind`], which is
/// always the type of an element and never an array one whatever the format is.
fn attr_data_type(kind: &AttrDataKind) -> i32 {
    match kind {
        AttrDataKind::Bool => DEV_BOOLEAN,
        AttrDataKind::Octet => DEV_UCHAR,
        AttrDataKind::UShort => DEV_USHORT,
        AttrDataKind::Short => DEV_SHORT,
        AttrDataKind::ULong => DEV_ULONG,
        AttrDataKind::Long => DEV_LONG,
        AttrDataKind::ULong64 => DEV_ULONG64,
        AttrDataKind::Long64 => DEV_LONG64,
        AttrDataKind::Float => DEV_FLOAT,
        AttrDataKind::Double => DEV_DOUBLE,
        AttrDataKind::State => DEV_STATE,
        AttrDataKind::String => DEV_STRING,
        AttrDataKind::Enum => DEV_ENUM,
        AttrDataKind::Encoded => DEV_ENCODED,
    }
}

/// The error to report for a data type that none of our data kinds has a variant for,
/// which is either one we know of and have yet to support, pipe blobs being the one a
/// device really sends, or one that no Tango data type has that value. Note that cppTango
/// has no use of `DevVarEncodedArray` but as the sequence an encoded attribute travels in.
///
/// Note that this only makes the one command or attribute carrying it unusable and not the
/// whole listing it belongs to, which is why the info readers give it back for that one
/// object instead of failing, see [`read_command_info`] and [`read_attr_info`].
fn unsupported_data_type_err(data_type: i32) -> Error {
    match data_type {
        DEVVAR_ENCODEDARRAY => Error::not_implemented()
            .with_description("DevVarEncodedArray data is not implemented"),
        DEV_PIPE_BLOB => Error::not_implemented()
            .with_description("Pipe blob data is not implemented"),
        data_type => Error::new(ErrorKind::InvalidData)
            .with_description(format!("Tango data type {data_type} is unknown")),
    }
}

fn read_attr_data_format<'a>(buf: &mut CdrReader<'a>) -> Result<Option<AttrDataFormat>> {
    Ok(Some(match buf.read_ulong()? {
        FMT_SCALAR => AttrDataFormat::Scalar,
        FMT_SPECTRUM => AttrDataFormat::Spectrum(0),
        FMT_IMAGE => AttrDataFormat::Image(0, 0),
        FMT_UNKNOWN => return Ok(None),
        value => return Err(Error::new(ErrorKind::InvalidData)
            .with_description(format!("Attribute data format value {value} is invalid")))
    }))
}

/// Note that the absence of a format is `FMT_UNKNOWN`, which is what goes out along a
/// value the device has nothing to put in.
fn write_attr_data_format(buf: &mut CdrWriter, format: Option<AttrDataFormat>) -> Result<()> {
    buf.write_ulong(match format {
        Some(AttrDataFormat::Scalar) => FMT_SCALAR,
        Some(AttrDataFormat::Spectrum(_)) => FMT_SPECTRUM,
        Some(AttrDataFormat::Image(_, _)) => FMT_IMAGE,
        None => FMT_UNKNOWN,
    })
}

/// Write an `AttributeDim`, or the loose pair of dimensions v1 has in place of it, which
/// the IDL declares as longs and not as sequence lengths.
fn write_attr_dim(buf: &mut CdrWriter, dim_x: usize, dim_y: usize) -> Result<()> {
    let (Ok(dim_x), Ok(dim_y)) = (i32::try_from(dim_x), i32::try_from(dim_y)) else {
        return Err(Error::new(ErrorKind::InvalidData)
            .with_description("Attribute dimensions do not fit into a long")
            .with_append_description(format_args!("Got: {dim_x}x{dim_y}")));
    };
    buf.write_long(dim_x)?;
    buf.write_long(dim_y)
}

/// Equivalent to `NamedDevError` in the IDL, one entry of the `MultiDevFailed` exception
/// that the write operations raise when only some of the attributes failed.
#[derive(Debug)]
pub struct NamedError<'a> {
    /// Name of the attribute that failed to be written.
    pub name: Cow<'a, str>,
    /// Index of the attribute in the list the call was given.
    pub index: usize,
    /// The failure itself, absent when the server sent an empty error list for it.
    pub err: Option<Error>,
}

impl<'a> CdrRead<'a> for NamedError<'a> {
    fn read(buf: &mut CdrReader<'a>) -> Result<Self> {

        let name = buf.read_string()?;

        // 'index_in_call' is a long and not a sequence length, so a negative one is a
        // server that has no index to give rather than a huge one.
        let index = buf.read_long()?;
        let index = usize::try_from(index)
            .map_err(|_| Error::new(ErrorKind::InvalidData)
                .with_description(format!("Attribute index {index} in a MultiDevFailed is invalid")))?;

        Ok(Self {
            name,
            index,
            err: buf.read()?,
        })

    }
}

impl CdrWrite for NamedError<'_> {
    fn write(&self, buf: &mut CdrWriter) -> Result<()> {

        buf.write_string(&self.name)?;

        // 'index_in_call' is a long and not a sequence length, so an index that does not
        // fit in one goes out as the negative that means the server has none to give.
        buf.write_long(i32::try_from(self.index).unwrap_or(-1))?;

        buf.write(&self.err.as_ref())?;

        Ok(())

    }
}


#[cfg(test)]
mod tests {

    use super::*;


    /// A `TimeVal` a sender never filled in — the halves of a pointer, which is what
    /// cppTango leaves in the one it sends with a write — is no time rather than an error,
    /// whichever of the three components is the negative one.
    #[test]
    fn unset_time() {

        for (tv_sec, tv_usec, tv_nsec) in [
            (-116981683, 32749, -116981655),
            (32716, -1409265532, 32716),
            (i32::MIN, i32::MIN, i32::MIN),
            (-1, 0, 0),
        ] {

            let mut writer = CdrWriter::new();
            writer.write_long(tv_sec).unwrap();
            writer.write_long(tv_usec).unwrap();
            writer.write_long(tv_nsec).unwrap();
            let buf = writer.into_buf().freeze();

            let read = CdrReader::new(&buf).read::<SystemTime>()
                .unwrap_or_else(|err| panic!("({tv_sec}, {tv_usec}, {tv_nsec}) was refused: {err}"));

            assert_eq!(read, SystemTime::UNIX_EPOCH, "({tv_sec}, {tv_usec}, {tv_nsec})");

        }

    }

    /// One whose components are each in range but whose total is not answers no time
    /// either, rather than overflowing — which it did, and a debug build panicked on it.
    #[test]
    fn unreachable_time() {
        let mut writer = CdrWriter::new();
        writer.write_long(i32::MAX).unwrap();
        writer.write_long(i32::MAX).unwrap();
        writer.write_long(i32::MAX).unwrap();
        let buf = writer.into_buf().freeze();
        assert!(CdrReader::new(&buf).read::<SystemTime>().is_ok(), "a time too far out was refused");
    }

    /// A time that is one goes out and comes back, to the microsecond `TimeVal` carries.
    #[test]
    fn time_roundtrip() {

        let sent = SystemTime::UNIX_EPOCH + Duration::from_micros(1_788_714_320_192_300);

        let mut writer = CdrWriter::new();
        writer.write(&sent).unwrap();
        let buf = writer.into_buf().freeze();

        assert_eq!(CdrReader::new(&buf).read::<SystemTime>().unwrap(), sent);

    }

}