rstango 0.3.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
//! Contains serialization types for IOR.
//! 
//! Specification: https://www.omg.org/spec/CORBA/3.4/Interoperability/PDF
//!                Section 7.6.[2-3]

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

use crate::error::{Error, ErrorKind, Result};
use crate::buf::Buf;

use super::cdr::{CdrReader, CdrWriter, CdrRead, CdrWrite};
use super::codeset::{Codeset, WideCodeset, AnyCodeset};
use super::giop::Version;


/// Represent an IOR.
#[derive(Debug, Clone)]
pub struct Ior<'a> {
    pub type_id: Cow<'a, str>,
    pub profiles: Cow<'a, [Profile]>,
}

impl<'d> CdrRead<'d> for Ior<'d> {
    fn read(buf: &mut CdrReader<'d>) -> Result<Self> {
        Ok(Self {
            type_id: buf.read_string()?,
            profiles: Cow::Owned(buf.read()?),
        })
    }
}

impl CdrWrite for Ior<'_> {
    fn write(&self, buf: &mut CdrWriter) -> Result<()> {
        buf.write_string(&self.type_id)?;
        buf.write(&*self.profiles)?;
        Ok(())
    }
}

/// Represent a profile into an IOR.
#[derive(Clone, Debug)]
pub struct Profile {
    pub tag: u32,
    pub data: Buf<u8, 1>,
}

impl CdrRead<'_> for Profile {
    fn read(buf: &mut CdrReader<'_>) -> Result<Self> {
        Ok(Self {
            tag: buf.read_ulong()?,
            data: buf.read()?,
        })
    }
}

impl CdrWrite for Profile {
    fn write(&self, buf: &mut CdrWriter) -> Result<()> {
        buf.write_ulong(self.tag)?;
        buf.write(&self.data)?;
        Ok(())
    }
}

impl Profile {

    /// A reader over the encapsulation the data of this profile is, left right past the byte
    /// order flag it starts with, which it has already applied.
    ///
    /// Those octets are where the CDR alignment restarts from, and they are read in place
    /// and never copied, see [`CdrReader`].
    pub fn reader(&self) -> Result<CdrReader<'_>> {
        let mut reader = CdrReader::new(&self.data);
        reader.read_endian()?;
        Ok(reader)
    }

    /// Parse this profile out of its own octets, [`None`] for a tag this implementation
    /// knows nothing about.
    pub fn parse(&self) -> Result<Option<ProfileKind<'_>>> {
        let mut reader = self.reader()?;
        Ok(Some(match self.tag {
            0 => ProfileKind::Iiop(reader.read()?),
            1 => ProfileKind::MultipleComponents(Cow::Owned(reader.read()?)),
            _ => return Ok(None),
        }))
    }

}

#[derive(Debug, Clone)]
pub enum ProfileKind<'a> {
    Iiop(IiopProfile<'a>),
    MultipleComponents(Cow<'a, [Component]>),
}

impl ProfileKind<'_> {

    /// Encode this profile into a buffer of its own, which is the encapsulation its data is
    /// made of, and which is therefore where its CDR alignment restarts from.
    pub fn build(&self) -> Result<Profile> {

        let mut writer = CdrWriter::new();

        // The byte order flag every encapsulation starts with, the length that prefixes it
        // being written when the profile itself is, see its own implementation.
        writer.write_endian()?;

        let tag = match self {
            ProfileKind::Iiop(iiop) => {
                writer.write(iiop)?;
                0
            }
            ProfileKind::MultipleComponents(components) => {
                writer.write(&**components)?;
                1
            }
        };

        Ok(Profile {
            tag,
            data: writer.into_buf().freeze(),
        })

    }

}

#[derive(Debug, Clone)]
pub struct IiopProfile<'a> {
    /// The IIOP version of the profile, whose major is always 1, which tells the GIOP
    /// version the object it points to speaks, and therefore how the profile itself is
    /// encoded: only 1.1 and above hold components.
    pub version: Version,
    pub host: Cow<'a, str>,
    pub port: u16,
    pub object_key: Cow<'a, [u8]>,
    pub components: Cow<'a, [Component]>,
}

impl<'d> CdrRead<'d> for IiopProfile<'d> {
    fn read(buf: &mut CdrReader<'d>) -> Result<Self> {
        
        let major = buf.read_octet()?;
        let minor = buf.read_octet()?;

        let Some(version) = Version::from_minor(minor).filter(|_| major == 1) else {
            return Err(Error::new(ErrorKind::InvalidData)
                .with_description(format!("Invalid version for IIOP: {major}.{minor}")));
        };

        Ok(Self {
            version,
            host: buf.read_string()?,
            port: buf.read_ushort()?,
            object_key: Cow::Borrowed(buf.read::<&[u8]>()?),
            components: if version == Version::V10 {
                Cow::Borrowed(&[])
            } else {
                Cow::Owned(buf.read::<Vec<_>>()?)
            }
        })

    }
}

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

        buf.write_octet(1)?;
        buf.write_octet(self.version.minor())?;

        buf.write_string(&self.host)?;
        buf.write_ushort(self.port)?;
        buf.write::<[u8]>(&self.object_key)?;

        // IIOP 1.0 knows nothing of the components, so a profile that holds some cannot be
        // encoded with that version at all rather than silently losing them.
        if self.version == Version::V10 {
            if !self.components.is_empty() {
                return Err(Error::new(ErrorKind::InvalidData)
                    .with_description("Cannot encode IIOP profile components with version 1.0"));
            }
        } else {
            buf.write(&*self.components)?;
        }

        Ok(())

    }
}

#[derive(Debug, Clone)]
pub struct Component {
    pub tag: u32,
    pub data: Buf<u8, 1>,
}

impl CdrRead<'_> for Component {
    fn read(buf: &mut CdrReader<'_>) -> Result<Self> {
        Ok(Self {
            tag: buf.read_ulong()?,
            data: buf.read()?,
        })
    }
}

impl CdrWrite for Component {
    fn write(&self, buf: &mut CdrWriter) -> Result<()> {
        buf.write_ulong(self.tag)?;
        buf.write(&self.data)?;
        Ok(())
    }
}

impl Component {

    /// A reader over the encapsulation the data of this component is, left right past the
    /// byte order flag it starts with, which it has already applied, see
    /// [`Profile::reader`].
    pub fn reader(&self) -> Result<CdrReader<'_>> {
        let mut reader = CdrReader::new(&self.data);
        reader.read_endian()?;
        Ok(reader)
    }

    /// Parse this component out of its own octets, [`None`] for a tag this implementation
    /// knows nothing about.
    pub fn parse(&self) -> Result<Option<ComponentKind<'_>>> {
        let mut reader = self.reader()?;
        Ok(Some(match self.tag {
            0 => ComponentKind::OrbType(reader.read_ulong()?),
            1 => ComponentKind::Codesets(reader.read()?),
            3 => ComponentKind::AltIiopAddr(reader.read()?),
            _ => return Ok(None),
        }))
    }

}

#[derive(Debug, Clone)]
pub enum ComponentKind<'a> {
    OrbType(u32),
    Codesets(CodesetsComponent<'a>),
    AltIiopAddr(AltIiopAddr<'a>),
}

impl ComponentKind<'_> {

    /// Encode this component into a buffer of its own, which is the encapsulation its data
    /// is made of, and which is therefore where its CDR alignment restarts from.
    pub fn build(&self) -> Result<Component> {

        let mut writer = CdrWriter::new();

        // The byte order flag every encapsulation starts with, the length that prefixes it
        // being written when the component itself is, see its own implementation.
        writer.write_endian()?;

        let tag = match self {
            ComponentKind::OrbType(orb_type) => {
                writer.write_ulong(*orb_type)?;
                0
            }
            ComponentKind::Codesets(codesets) => {
                writer.write(codesets)?;
                1
            }
            ComponentKind::AltIiopAddr(alt_addr) => {
                writer.write(alt_addr)?;
                3
            }
        };

        Ok(Component {
            tag,
            data: writer.into_buf().freeze(),
        })

    }

}

#[derive(Debug, Clone)]
pub struct CodesetsComponent<'a> {
    pub native_codeset: u32,
    pub conversion_codesets: Cow<'a, [u32]>,
    pub native_wide_codeset: u32,
    pub conversion_wide_codesets: Cow<'a, [u32]>,
}

impl<'d> CdrRead<'d> for CodesetsComponent<'d> {
    fn read(buf: &mut CdrReader<'d>) -> Result<Self> {
        Ok(Self {
            native_codeset: buf.read()?,
            conversion_codesets: buf.read()?,
            native_wide_codeset: buf.read()?,
            conversion_wide_codesets: buf.read()?,
        })
    }
}

impl CdrWrite for CodesetsComponent<'_> {
    fn write(&self, buf: &mut CdrWriter) -> Result<()> {
        buf.write_ulong(self.native_codeset)?;
        buf.write(&*self.conversion_codesets)?;
        buf.write_ulong(self.native_wide_codeset)?;
        buf.write(&*self.conversion_wide_codesets)?;
        Ok(())
    }
}

impl CodesetsComponent<'_> {

    pub fn parse_native_codeset(&self) -> Option<Codeset> {
        Codeset::from_id(self.native_codeset)
    }

    pub fn parse_conversion_codesets(&self) -> impl Iterator<Item = Codeset> + use<'_> {
        self.conversion_codesets.iter().copied().filter_map(Codeset::from_id)
    }

    pub fn parse_native_wide_codeset(&self) -> Option<WideCodeset> {
        WideCodeset::from_id(self.native_wide_codeset)
    }

    pub fn parse_conversion_wide_codesets(&self) -> impl Iterator<Item = WideCodeset> + use<'_> {
        self.conversion_wide_codesets.iter().copied().filter_map(WideCodeset::from_id)
    }

}

#[derive(Debug, Clone)]
pub struct AltIiopAddr<'a> {
    pub host: Cow<'a, str>,
    pub port: u16,
}

impl<'d> CdrRead<'d> for AltIiopAddr<'d> {
    fn read(buf: &mut CdrReader<'d>) -> Result<Self> {
        Ok(Self {
            host: buf.read_string()?,
            port: buf.read()?,
        })
    }
}

impl CdrWrite for AltIiopAddr<'_> {
    fn write(&self, buf: &mut CdrWriter) -> Result<()> {
        buf.write_string(&self.host)?;
        buf.write_ushort(self.port)?;
        Ok(())
    }
}

// ==================== //
//        Tests         //
// ==================== //

#[cfg(test)]
mod tests {

    use super::*;

    /// An IOR goes through a stream whole, its profiles and their components being the
    /// encapsulations they are built into, and comes back out of it exactly as it went in.
    #[test]
    fn round_trip() {

        let codesets = ComponentKind::Codesets(CodesetsComponent {
            native_codeset: Codeset::Utf8.id(),
            conversion_codesets: Cow::Borrowed(&[]),
            native_wide_codeset: WideCodeset::Utf16.id(),
            conversion_wide_codesets: Cow::Borrowed(&[]),
        }).build().unwrap();

        assert_eq!(codesets.tag, 1);

        let profile = ProfileKind::Iiop(IiopProfile {
            version: Version::V12,
            host: Cow::Borrowed("localhost"),
            port: 10000,
            object_key: Cow::Borrowed(b"the object key"),
            components: Cow::Owned(vec![codesets]),
        }).build().unwrap();

        assert_eq!(profile.tag, 0);

        let mut writer = CdrWriter::new();
        writer.write(&Ior {
            type_id: Cow::Borrowed("IDL:Tango/Device_5:1.0"),
            profiles: Cow::Owned(vec![profile]),
        }).unwrap();

        let buf = writer.into_buf().freeze();
        let ior = CdrReader::new(&buf).read::<Ior>().unwrap();

        assert_eq!(ior.type_id, "IDL:Tango/Device_5:1.0");
        assert_eq!(ior.profiles.len(), 1);

        let Some(ProfileKind::Iiop(iiop)) = ior.profiles[0].parse().unwrap() else {
            panic!("expected an IIOP profile");
        };

        assert_eq!(iiop.version, Version::V12);
        assert_eq!(iiop.host, "localhost");
        assert_eq!(iiop.port, 10000);
        assert_eq!(&*iiop.object_key, b"the object key");
        assert_eq!(iiop.components.len(), 1);

        let Some(ComponentKind::Codesets(codesets)) = iiop.components[0].parse().unwrap() else {
            panic!("expected the codesets component");
        };

        assert_eq!(codesets.parse_native_codeset(), Some(Codeset::Utf8));
        assert_eq!(codesets.parse_native_wide_codeset(), Some(WideCodeset::Utf16));
        assert_eq!(codesets.parse_conversion_codesets().count(), 0);

    }

    /// A component this implementation knows nothing about is simply not parsed.
    #[test]
    fn unknown_component() {
        let mut component = ComponentKind::OrbType(0x41545400).build().unwrap();
        component.tag = 0xDEAD;
        assert!(component.parse().unwrap().is_none());
    }

    /// IIOP 1.0 knows nothing of the components, so a profile holding some cannot claim to
    /// be one rather than silently losing them.
    #[test]
    fn v10_no_components() {

        let mut iiop = IiopProfile {
            version: Version::V10,
            host: Cow::Borrowed("localhost"),
            port: 10000,
            object_key: Cow::Borrowed(b"the object key"),
            components: Cow::Owned(vec![ComponentKind::OrbType(0x41545400).build().unwrap()]),
        };

        assert!(ProfileKind::Iiop(iiop.clone()).build().is_err());

        iiop.components = Cow::Borrowed(&[]);
        assert!(ProfileKind::Iiop(iiop).build().is_ok());

    }

}