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
//! What a device says of itself, its commands and its attributes.

use std::time::Duration;
use std::borrow::Cow;
use std::fmt::Debug;

use crate::value::AttrDataFormat;
use crate::error::{Error, ErrorKind, Result};
use crate::dev::{
    AttrArchiveEventConfig, AttrChangeEventConfig, AttrConfig, AttrDeltaConfig, AttrInfo,
    AttrMemorized, AttrMode, AttrNumber, AttrPeriodicEventConfig, AttrRangeConfig, CommandInfo,
    DevInfo, DisplayLevel,
};

use super::super::orb::cdr::{CdrReader, CdrWriter};
use super::super::DevVersion;
use super::{
    attr_data_kind, attr_data_type, command_data_kind, command_data_type, read_attr_data_format,
    write_attr_data_format, DEV_LONG, DEV_LONG64, DEV_SHORT, DEV_UCHAR, DEV_ULONG, DEV_ULONG64,
    DEV_USHORT, DL_EXPERT, DL_OPERATOR, DL_UNKNOWN, NOT_A_NUMBER, NOT_SPECIFIED, NO_DESCRIPTION,
    NO_DISPLAY_UNIT, NO_LABEL, NO_STANDARD_UNIT, UNINITIALIZED, WT_READ, WT_READ_WITH_WRITE,
    WT_READ_WRITE, WT_UNKNOWN, WT_WRITE,
};


/// Read a `DispLevel`, which every version of the info structures has but v1 of the command
/// one. Note that a device sends `DL_UNKNOWN` for an object it has no level for, which
/// cppTango shows at the operator level, and so do we, [`DisplayLevel`] having no variant
/// for an unknown level.
fn read_display_level(buf: &mut CdrReader<'_>) -> Result<DisplayLevel> {
    Ok(match buf.read_ulong()? {
        DL_OPERATOR | DL_UNKNOWN => DisplayLevel::Operator,
        DL_EXPERT => DisplayLevel::Expert,
        value => return Err(Error::new(ErrorKind::InvalidData)
            .with_description(format!("Display level value {value} is invalid"))),
    })
}

/// Read a property, giving it back only if the device really has a value for it, see the
/// placeholders above. The one to expect depends on the property, hence the parameter.
fn read_prop<'a>(buf: &mut CdrReader<'a>, unset: &str) -> Result<Option<Cow<'static, str>>> {
    let value = buf.read_string()?;
    Ok(if value.is_empty() || value == unset {
        None
    } else {
        // The configuration outlives the buffer it was read from, so what a device sends
        // is always owned; only what a server defines by itself is borrowed.
        Some(Cow::Owned(value.into_owned()))
    })
}

/// Read one of the numeric properties, the bounds of a range and the deltas, which a device
/// leaves unset either the way any property is or with a not-a-number. What is left is the
/// value itself, still as the string the IDL declares it as.
fn read_value_str<'a>(buf: &mut CdrReader<'a>) -> Result<Option<Cow<'a, str>>> {
    let value = buf.read_string()?;
    Ok(if value.is_empty() || value == NOT_SPECIFIED || value == NOT_A_NUMBER {
        None
    } else {
        Some(value)
    })
}

/// Read one of those properties as the double it is, which is what the criteria of the
/// events are: a change is a magnitude and a relative change a percentage, neither of them
/// a value of the attribute, and Tango holds both as doubles whatever the attribute is.
///
/// A value that is not a number we can compare against — one a device wrote in a way we
/// cannot read, or an infinity — is one we have nothing to report, which is what an unset
/// one gives too, so it is not worth failing the whole configuration for.
fn read_value_prop<'a>(buf: &mut CdrReader<'a>) -> Result<Option<f64>> {
    Ok(read_value_str(buf)?
        .and_then(|value| value.trim().parse::<f64>().ok())
        .filter(|value| value.is_finite()))
}

/// Read one of those properties as a limit, which is a value of the attribute itself and
/// is therefore read as the type of the attribute, see [`AttrNumber`].
///
/// A device that wrote a limit its own type cannot hold still has one, so what does not
/// parse as the type of the attribute is read as a double before being given up on.
fn read_limit_prop<'a>(buf: &mut CdrReader<'a>, kind: LimitKind) -> Result<Option<AttrNumber>> {

    let Some(value) = read_value_str(buf)? else {
        return Ok(None);
    };
    let value = value.trim();

    let typed = match kind {
        LimitKind::Long => value.parse::<i64>().ok().map(AttrNumber::Long),
        LimitKind::ULong => value.parse::<u64>().ok().map(AttrNumber::ULong),
        LimitKind::Double => None,
    };

    Ok(typed.or_else(|| value.parse::<f64>().ok()
        .filter(|value| value.is_finite())
        .map(AttrNumber::Double)))

}

/// Which of the three numbers of an [`AttrNumber`] the limits of an attribute of that data
/// type are, which is only the signedness of it: the limits of an attribute are values of
/// it, so they are of its own type.
fn limit_kind(data_type: i32) -> LimitKind {
    match data_type {
        DEV_SHORT | DEV_LONG | DEV_LONG64 => LimitKind::Long,
        DEV_UCHAR | DEV_USHORT | DEV_ULONG | DEV_ULONG64 => LimitKind::ULong,
        // The floating kinds, and the kinds that have no limits to speak of — a string, a
        // state, a boolean — whose properties a device leaves unset anyway.
        _ => LimitKind::Double,
    }
}

/// The three kinds of number the limits of an attribute may be read as, see [`limit_kind`].
#[derive(Debug, Clone, Copy)]
enum LimitKind {
    Double,
    Long,
    ULong,
}

/// Read one of the duration properties, which travel as a plain number in the unit the
/// property is defined in, which is milliseconds for every one of them, the event periods
/// and the RDS alarm delta time alike. A device that has no value for it leaves it unset
/// like any other property.
fn read_duration_prop<'a>(buf: &mut CdrReader<'a>, unit: Duration) -> Result<Option<Duration>> {
    let Some(value) = read_value_str(buf)? else {
        return Ok(None);
    };
    // A period the device sends as something other than a number is one we have nothing to
    // report, which is what an unset one gives too, so it is not worth failing the whole
    // configuration for.
    Ok(value.trim().parse::<u32>().ok().map(|value| unit * value))
}

/// Common function for both versions of the command info structure, the v2 one only adding
/// the display level, which v1 has no place for at all: cppTango shows every command of a
/// v1 device at the operator level, and so do we.
///
/// Note that the `cmd_tag` both versions carry is not a display level despite holding small
/// numbers, it is a tag the IDL leaves to the device and that cppTango never reads back, so
/// it is skipped here.
pub fn read_command_info<'a>(buf: &mut CdrReader<'a>, version: DevVersion) -> Result<(Cow<'a, str>, Result<CommandInfo>)> {

    let name = buf.read_string()?;

    let display_level = if version >= DevVersion::V2 {
        read_display_level(buf)?
    } else {
        DisplayLevel::Operator
    };

    let _cmd_tag = buf.read_long()?;
    let in_type = buf.read_long()?;
    let out_type = buf.read_long()?;

    // The descriptions are read whatever the types are, so that the structure is fully
    // consumed even for a command we have no kind for, the next one in a list being read
    // right after it.
    let in_doc = read_prop(buf, UNINITIALIZED)?;
    let out_doc = read_prop(buf, UNINITIALIZED)?;

    let info = match (command_data_kind(in_type), command_data_kind(out_type)) {
        (Ok(in_kind), Ok(out_kind)) => Ok(CommandInfo {
            display_level,
            in_kind,
            out_kind,
            in_doc,
            out_doc,
        }),
        (Err(err), _) |
        (_, Err(err)) => Err(err),
    };

    Ok((name, info))

}

/// Common function for all versions of the attribute configuration structure.
///
/// The IDL only has four of these for the six device versions: v4 reuses the v3 one and v6
/// the v5 one, so what changes from one version to the next is
/// - v2 gains the display level;
/// - v3 moves the alarm bounds into a structure of their own, which also gains the warning
///   bounds and the delta of the read-different-from-set alarm, and gains the whole event
///   configuration along with a second list of extensions;
/// - v5 gains the memorization, the enumeration labels and the root attribute name of a
///   forwarded attribute.
///
/// Note that the version to give here is the one of the *structure* and not the one of the
/// device, which are not the same thing for a v4 device, whose configuration is the v3 one.
pub fn read_attr_info<'a>(buf: &mut CdrReader<'a>, version: DevVersion) -> Result<(Cow<'a, str>, Result<AttrInfo>)> {

    // Every field is read in the order the IDL declares it, and only assembled at the end,
    // so that the reading order stays plain to see.
    let name = buf.read_string()?;
    let writable = buf.read_ulong()?;
    let format = read_attr_data_format(buf)?;
    let data_type = buf.read_long()?;

    // The limits further down are values of the attribute, so they are read as its own
    // type, which the IDL is kind enough to announce before any of them.
    let limits = limit_kind(data_type);

    // v5 announces the memorization right after the type, the two flags being whether the
    // attribute is memorized at all and whether it is written back when the device starts.
    let mut memorized = None;
    if version >= DevVersion::V5 {
        memorized = match (buf.read_bool()?, buf.read_bool()?) {
            (false, _) => None,
            (true, false) => Some(AttrMemorized::RestoreSetPoint),
            (true, true) => Some(AttrMemorized::RestoreAndWrite),
        };
    }

    // The format the structure announces carries no dimension of its own, the maximum ones
    // the attribute is declared with being the two fields that follow it, and only the
    // formats that have dimensions have any use for them. A negative maximum is a device
    // that means none, the IDL declaring them as longs and not as sequence lengths.
    let max_dim_x = buf.read_long()?;
    let max_dim_y = buf.read_long()?;
    let max_dim = |value: i32| usize::try_from(value).unwrap_or(0);

    let data_format = match format {
        Some(AttrDataFormat::Scalar) => AttrDataFormat::Scalar,
        Some(AttrDataFormat::Spectrum(_)) => AttrDataFormat::Spectrum(max_dim(max_dim_x)),
        Some(AttrDataFormat::Image(_, _)) => AttrDataFormat::Image(max_dim(max_dim_x), max_dim(max_dim_y)),
        None => return Err(Error::new(ErrorKind::InvalidData)
            .with_description(format!("Attribute {name:?} has an unknown data format"))),
    };

    let doc = read_prop(buf, NO_DESCRIPTION)?;
    let label = read_prop(buf, NO_LABEL)?;
    let unit = read_prop(buf, "")?;
    let standard_unit = read_prop(buf, NO_STANDARD_UNIT)?;
    let display_unit = read_prop(buf, NO_DISPLAY_UNIT)?;
    let display_format = read_prop(buf, NOT_SPECIFIED)?;
    let range = AttrRangeConfig {
        min: read_limit_prop(buf, limits)?,
        max: read_limit_prop(buf, limits)?,
    };

    // From here the versions part ways: v1 and v2 carry the alarm bounds on their own and
    // have nothing else, where v3 onward has the alarm structure and the events.
    let mut alarm = AttrRangeConfig::default();
    if version <= DevVersion::V2 {
        alarm = AttrRangeConfig {
            min: read_limit_prop(buf, limits)?,
            max: read_limit_prop(buf, limits)?,
        };
    }

    let write_attr_name = buf.read_string()?;

    // v1 is the only one with no display level, and it is the last field of v2 before the
    // extensions, where v3 onward has it right after the associated write attribute.
    let mut display_level = DisplayLevel::Operator;
    if version >= DevVersion::V2 {
        display_level = read_display_level(buf)?;
    }

    // Only v5 has these two, the root attribute naming what a forwarded attribute forwards,
    // which the data module has nowhere to hold for now, and the labels naming the values
    // of a DevEnum, which are what the data kind of one is made of.
    let mut enum_labels = Vec::new();
    if version >= DevVersion::V5 {
        let _root_attr_name = buf.read_string()?;
        enum_labels = buf.read::<Vec<String>>()?;
    }

    let mut warning = AttrRangeConfig::default();
    let mut delta = None;
    let mut change_event = AttrChangeEventConfig::default();
    let mut periodic_event = AttrPeriodicEventConfig::default();
    let mut archive_event = AttrArchiveEventConfig::default();

    if version >= DevVersion::V3 {

        // 'AttributeAlarm', which holds the bounds v1 and v2 have of their own along with
        // the ones they know nothing about.
        alarm = AttrRangeConfig {
            min: read_limit_prop(buf, limits)?,
            max: read_limit_prop(buf, limits)?,
        };
        warning = AttrRangeConfig {
            min: read_limit_prop(buf, limits)?,
            max: read_limit_prop(buf, limits)?,
        };
        let delta_time = read_duration_prop(buf, Duration::from_millis(1))?;
        let delta_value = read_limit_prop(buf, limits)?;
        let _alarm_extensions = buf.read::<Vec<Cow<'_, str>>>()?;

        // The delta of the read-different-from-set alarm is only an alarm at all if there
        // is a difference to compare, its time being how long the device waits first.
        delta = delta_value.map(|value| AttrDeltaConfig {
            value,
            time: delta_time,
        });

        // 'EventProperties', whose three structures each end with extensions of their own.
        change_event = AttrChangeEventConfig {
            rel_change: read_value_prop(buf)?,
            abs_change: read_value_prop(buf)?,
        };
        let _change_extensions = buf.read::<Vec<Cow<'_, str>>>()?;
        periodic_event = AttrPeriodicEventConfig {
            period: read_duration_prop(buf, Duration::from_millis(1))?,
        };
        let _periodic_extensions = buf.read::<Vec<Cow<'_, str>>>()?;
        archive_event = AttrArchiveEventConfig {
            rel_change: read_value_prop(buf)?,
            abs_change: read_value_prop(buf)?,
            period: read_duration_prop(buf, Duration::from_millis(1))?,
        };
        let _archive_extensions = buf.read::<Vec<Cow<'_, str>>>()?;

    }

    let extensions = buf.read::<Vec<String>>()?.into_iter()
        .map(Cow::Owned)
        .collect();

    // The second list of extensions is the one a device keeps for itself, which it is not
    // supposed to put anything in that a client would read.
    if version >= DevVersion::V3 {
        let _sys_extensions = buf.read::<Vec<Cow<'_, str>>>()?;
    }

    // The mode is the writability along with the attribute that a read-only one is the
    // reading of, which is the only case the name means anything in.
    let mode = match writable {
        WT_READ => AttrMode::Read,
        WT_READ_WITH_WRITE => AttrMode::ReadWithWrite {
            write_attr_name: Cow::Owned(write_attr_name.into_owned()),
        },
        WT_WRITE => AttrMode::Write,
        WT_READ_WRITE => AttrMode::ReadWrite,
        WT_UNKNOWN => return Err(Error::new(ErrorKind::InvalidData)
            .with_description(format!("Attribute {name:?} has an unknown writability"))),
        value => return Err(Error::new(ErrorKind::InvalidData)
            .with_description(format!("Attribute writability value {value} is invalid"))),
    };

    let info = attr_data_kind(data_type).map(|data_kind| AttrInfo {
        config: AttrConfig {
            doc,
            label,
            unit,
            // The conversion factor travels as a text property rather than as one of the
            // numeric ones, so it is the one number here that is parsed out of a string a
            // device may have written anything in.
            standard_unit: standard_unit.and_then(|value| value.trim().parse::<f64>().ok()),
            display_unit,
            display_format,
            range,
            alarm,
            warning,
            delta,
            change_event,
            periodic_event,
            archive_event,
            enum_labels: enum_labels.into_iter().map(Cow::Owned).collect(),
            extensions,
        },
        mode,
        data_kind,
        data_format,
        display_level,
        memorized,
    });

    Ok((name, info))

}

/// Common function for all three versions of the device info structure.
///
/// The IDL has one of these for v1, v3 and v6, the others reusing the previous one, and
/// each adds a field at the end of the one before it: v3 the type of the device, and v6 the
/// versions of what the server is built out of.
///
/// Note that the version to give here is the one of the *structure* and not the one of the
/// device, a v4 and a v5 device both answering with the v3 one.
pub fn read_dev_info(buf: &mut CdrReader<'_>, version: DevVersion) -> Result<DevInfo> {

    // Every field is read in the order the IDL declares it, and only assembled at the end,
    // so that the reading order stays plain to see.
    let class = buf.read_string()?.into_owned();
    let server_id = buf.read_string()?.into_owned();
    let server_host = buf.read_string()?.into_owned();
    let server_version = buf.read_long()?;
    let doc_url = read_prop(buf, NOT_SPECIFIED)?;

    let mut dev_type = None;
    if version >= DevVersion::V3 {
        dev_type = read_prop(buf, NOT_SPECIFIED)?;
    }

    let mut version_info = Vec::new();
    if version >= DevVersion::V6 {
        let len = buf.read_sequence_len()?;
        version_info.try_reserve(len)
            .map_err(|_| Error::new(ErrorKind::Internal)
                .with_description(format!("Failed to reserve room for the {len} versions of a device info")))?;
        for _ in 0..len {
            let key = buf.read_string()?.into_owned();
            let value = buf.read_string()?.into_owned();
            version_info.push((Cow::Owned(key), Cow::Owned(value)));
        }
    }

    Ok(DevInfo {
        class,
        server_id,
        server_host,
        server_version,
        doc_url,
        dev_type,
        version_info,
    })

}

/// The exact mirror of [`read_dev_info`], the version being the one of the structure the
/// info goes out in, which is the one of the operation that asked for it.
pub fn write_dev_info(buf: &mut CdrWriter, version: DevVersion, info: &DevInfo) -> Result<()> {

    buf.write_string(&info.class)?;
    buf.write_string(&info.server_id)?;
    buf.write_string(&info.server_host)?;
    buf.write_long(info.server_version)?;
    write_prop(buf, info.doc_url.as_deref(), NOT_SPECIFIED)?;

    if version >= DevVersion::V3 {
        write_prop(buf, info.dev_type.as_deref(), NOT_SPECIFIED)?;
    }

    // Only v6 has these, so a device that has some and is asked in an earlier version
    // simply does not send them, there being nowhere to put them.
    if version >= DevVersion::V6 {
        buf.write_sequence_len(info.version_info.len())?;
        for (key, value) in &info.version_info {
            buf.write_string(key)?;
            buf.write_string(value)?;
        }
    }

    Ok(())

}

/// Common function for both versions of the command info structure, the exact mirror of
/// [`read_command_info`].
///
/// Note that the version to give here is the one of the *structure* and not the one of the
/// device, every version from v2 onward answering with the v2 structure.
pub fn write_command_info(buf: &mut CdrWriter, version: DevVersion, name: &str, info: &CommandInfo) -> Result<()> {

    buf.write_string(name)?;

    if version >= DevVersion::V2 {
        write_display_level(buf, info.display_level)?;
    }

    // The tag is something the IDL leaves to the device and that no client reads back, so
    // this one has nothing to put in it, see [`read_command_info`].
    buf.write_long(0)?;

    buf.write_long(command_data_type(&info.in_kind))?;
    buf.write_long(command_data_type(&info.out_kind))?;

    write_prop(buf, info.in_doc.as_deref(), UNINITIALIZED)?;
    write_prop(buf, info.out_doc.as_deref(), UNINITIALIZED)?;

    Ok(())

}

/// Common function for all versions of the attribute configuration structure, the exact
/// mirror of [`read_attr_info`], whose comments say what changes from one version to the
/// next and in which order every field goes.
///
/// Note that the version to give here is the one of the *structure* and not the one of the
/// device, which are not the same thing for a v4 device, whose configuration is the v3 one.
pub fn write_attr_info(buf: &mut CdrWriter, version: DevVersion, name: &str, info: &AttrInfo) -> Result<()> {

    let AttrInfo {
        config,
        mode,
        data_kind,
        data_format,
        display_level,
        memorized,
    } = info;

    buf.write_string(name)?;

    buf.write_ulong(match mode {
        AttrMode::Read => WT_READ,
        AttrMode::ReadWithWrite { .. } => WT_READ_WITH_WRITE,
        AttrMode::Write => WT_WRITE,
        AttrMode::ReadWrite => WT_READ_WRITE,
    })?;

    write_attr_data_format(buf, Some(*data_format))?;

    let data_type = attr_data_type(data_kind);
    buf.write_long(data_type)?;

    // The limits further down are values of the attribute, so they go out as its own type,
    // the way they are read as it.
    let limits = limit_kind(data_type);

    if version >= DevVersion::V5 {
        buf.write_bool(memorized.is_some())?;
        buf.write_bool(*memorized == Some(AttrMemorized::RestoreAndWrite))?;
    }

    // Only the formats that have dimensions have any to declare, a scalar declaring none,
    // which is what cppTango sends for one as well.
    let (max_dim_x, max_dim_y) = match data_format {
        AttrDataFormat::Scalar => (1, 0),
        AttrDataFormat::Spectrum(max_x) => (*max_x, 0),
        AttrDataFormat::Image(max_x, max_y) => (*max_x, *max_y),
    };

    let (Ok(max_dim_x), Ok(max_dim_y)) = (i32::try_from(max_dim_x), i32::try_from(max_dim_y)) else {
        return Err(Error::new(ErrorKind::InvalidData)
            .with_description(format!("Maximum dimensions of attribute {name:?} do not fit into a long"))
            .with_append_description(format_args!("Got: {max_dim_x}x{max_dim_y}")));
    };

    buf.write_long(max_dim_x)?;
    buf.write_long(max_dim_y)?;

    write_prop(buf, config.doc.as_deref(), NO_DESCRIPTION)?;
    write_prop(buf, config.label.as_deref(), name)?;
    write_prop(buf, config.unit.as_deref(), "")?;

    // The conversion factor travels as a text property rather than as one of the numeric
    // ones, so it goes out as the plain number it was parsed out of.
    match config.standard_unit {
        Some(factor) => buf.write_string(&factor.to_string())?,
        None => buf.write_string(NO_STANDARD_UNIT)?,
    }

    write_prop(buf, config.display_unit.as_deref(), NO_DISPLAY_UNIT)?;
    write_prop(buf, config.display_format.as_deref(), NOT_SPECIFIED)?;

    write_limit_prop(buf, config.range.min, limits)?;
    write_limit_prop(buf, config.range.max, limits)?;

    // v1 and v2 carry the alarm bounds on their own, where v3 onward has them in the alarm
    // structure further down, along with the ones they know nothing about.
    if version <= DevVersion::V2 {
        write_limit_prop(buf, config.alarm.min, limits)?;
        write_limit_prop(buf, config.alarm.max, limits)?;
    }

    // The associated write attribute only means anything for a read-only attribute that
    // has one, every other mode leaving it empty.
    buf.write_string(match mode {
        AttrMode::ReadWithWrite { write_attr_name } => write_attr_name,
        _ => "",
    })?;

    if version >= DevVersion::V2 {
        write_display_level(buf, *display_level)?;
    }

    if version >= DevVersion::V5 {
        // The root attribute of a forwarded attribute, which the data module has nowhere
        // to hold for now, so nothing here ever forwards anything.
        buf.write_string("")?;
        // The labels naming the values of a DevEnum, which every other kind has none of
        // and whose absence is what a client reads one of another kind back as.
        buf.write(&config.enum_labels)?;
    }

    if version >= DevVersion::V3 {

        // 'AttributeAlarm', which holds the bounds v1 and v2 have of their own along with
        // the ones they know nothing about.
        write_limit_prop(buf, config.alarm.min, limits)?;
        write_limit_prop(buf, config.alarm.max, limits)?;
        write_limit_prop(buf, config.warning.min, limits)?;
        write_limit_prop(buf, config.warning.max, limits)?;
        write_duration_prop(buf, config.delta.and_then(|delta| delta.time), Duration::from_millis(1))?;
        write_limit_prop(buf, config.delta.map(|delta| delta.value), limits)?;
        buf.write_sequence_len(0)?;  // Alarm extensions.

        // 'EventProperties', whose three structures each end with extensions of their own.
        write_value_prop(buf, config.change_event.rel_change)?;
        write_value_prop(buf, config.change_event.abs_change)?;
        buf.write_sequence_len(0)?;
        write_duration_prop(buf, config.periodic_event.period, Duration::from_millis(1))?;
        buf.write_sequence_len(0)?;
        write_value_prop(buf, config.archive_event.rel_change)?;
        write_value_prop(buf, config.archive_event.abs_change)?;
        write_duration_prop(buf, config.archive_event.period, Duration::from_millis(1))?;
        buf.write_sequence_len(0)?;

    }

    buf.write(&config.extensions)?;

    // The second list of extensions is the one a device keeps for itself, which a client
    // is not supposed to be told anything through.
    if version >= DevVersion::V3 {
        buf.write_sequence_len(0)?;
    }

    Ok(())

}

/// Write a `DispLevel`, the mirror of [`read_display_level`].
fn write_display_level(buf: &mut CdrWriter, level: DisplayLevel) -> Result<()> {
    buf.write_ulong(match level {
        DisplayLevel::Operator => DL_OPERATOR,
        DisplayLevel::Expert => DL_EXPERT,
    })
}

/// Write a property, an absent one going out as the placeholder a client reads back as no
/// value, the mirror of [`read_prop`].
fn write_prop(buf: &mut CdrWriter, value: Option<&str>, unset: &str) -> Result<()> {
    buf.write_string(value.unwrap_or(unset))
}

/// Write one of the numeric properties, the mirror of [`read_value_prop`]. An absent one
/// goes out as the placeholder every unset numeric property shares.
fn write_value_prop(buf: &mut CdrWriter, value: Option<f64>) -> Result<()> {
    match value {
        Some(value) => buf.write_string(&value.to_string()),
        None => buf.write_string(NOT_SPECIFIED),
    }
}

/// Write one of the limits, which is a value of the attribute itself and goes out written
/// the way the number it is written, the mirror of [`read_limit_prop`].
///
/// The kind is what the limit would be read back as, so a limit of another kind is written
/// as the number it is anyway: a client reads a limit its type cannot hold as a double
/// rather than losing it, the way this implementation does.
fn write_limit_prop(buf: &mut CdrWriter, value: Option<AttrNumber>, _kind: LimitKind) -> Result<()> {
    match value {
        Some(value) => buf.write_string(&value.to_string()),
        None => buf.write_string(NOT_SPECIFIED),
    }
}

/// Write one of the duration properties, as the plain number of the unit the property is
/// defined in that it travels as, the mirror of [`read_duration_prop`].
fn write_duration_prop(buf: &mut CdrWriter, value: Option<Duration>, unit: Duration) -> Result<()> {

    let Some(value) = value else {
        return buf.write_string(NOT_SPECIFIED);
    };

    // The properties are whole numbers of their unit, so a duration that is not one is
    // rounded to the nearest, and never down to zero, which would mean something else.
    let unit = unit.as_nanos().max(1);
    let count = (value.as_nanos() + unit / 2) / unit;

    buf.write_string(&count.max(1).to_string())

}


#[cfg(test)]
mod tests {

    use super::*;

    use crate::value::AttrDataKind;

    /// An attribute configuration written and read back the same in every version of the
    /// structure, a client changing one sending it back as it read it, the durations being
    /// milliseconds on the wire.
    #[test]
    fn attr_info_round_trip() {

        let config = AttrConfig {
            unit: Some("mm".into()),
            range: AttrRangeConfig { min: Some(AttrNumber::Long(-5)), max: None },
            alarm: AttrRangeConfig { min: None, max: Some(AttrNumber::Long(10)) },
            delta: Some(AttrDeltaConfig { value: AttrNumber::Long(1), time: Some(Duration::from_millis(250)) }),
            change_event: AttrChangeEventConfig { rel_change: Some(0.5), abs_change: None },
            periodic_event: AttrPeriodicEventConfig { period: Some(Duration::from_millis(1000)) },
            ..AttrConfig::default()
        };

        let info = AttrInfo {
            config,
            mode: AttrMode::ReadWrite,
            data_kind: AttrDataKind::Long,
            data_format: AttrDataFormat::Scalar,
            display_level: DisplayLevel::Operator,
            memorized: None,
        };

        let mut writer = CdrWriter::new();
        write_attr_info(&mut writer, DevVersion::V5, "Position", &info).unwrap();
        let buf = writer.into_buf().freeze();

        // An unset label goes out as the name of the attribute, as cppTango sends it.
        let mut expected = info;
        expected.config.label = Some("Position".into());

        let (name, back) = read_attr_info(&mut CdrReader::new(&buf), DevVersion::V5).unwrap();
        assert_eq!(name, "Position");
        assert_eq!(back.unwrap(), expected);

    }

}