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
//! Types for the names Tango gives to things: case-ignored names, and type safe Tango
//! Resource Locators.

use std::fmt::{self, Debug, Display};
use std::hash::{Hash, Hasher};
use std::convert::Infallible;
use std::borrow::Borrow;
use std::num::NonZero;
use std::str::FromStr;
use std::ops::Deref;
use std::sync::Arc;


/// A name of something Tango names, compared and hashed the way Tango compares such a
/// name: ignoring the case, and on ASCII alone, every name Tango has being ASCII.
/// 
/// Which is what a server has to do of the names of its classes, of its devices, and of
/// the commands and attributes of each of them: cppTango lowercases every one of them
/// before it looks it up, and the database, being a SQL one, matches them the same way.
/// A name is kept as it was given all the same, because it is also what a client is shown.
#[repr(transparent)]
pub struct Name(str);

impl Name {

    /// Borrow a string as a name, which costs nothing: a name is a [`str`] with another
    /// comparison and nothing else.
    #[inline]
    pub fn new(name: &str) -> &Self {
        // SAFETY: Name is a repr(transparent) wrapper around str, so a reference to one is
        // a reference to the other.
        unsafe { &*(name as *const str as *const Self) }
    }

    /// Return the name as it was given, with its case.
    #[inline]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Copy the name into an owned one.
    #[inline]
    pub fn to_arc(&self) -> ArcName {
        ArcName(Arc::from(&self.0))
    }

}

impl PartialEq for Name {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.0.eq_ignore_ascii_case(&other.0)
    }
}

impl Eq for Name {}

impl Hash for Name {
    fn hash<H: Hasher>(&self, state: &mut H) {
        // Byte by byte rather than hashing the lowercased name, which would mean allocating
        // one on every lookup, with the same terminator `str` itself writes so that two
        // names one of which is a prefix of the other do not hash alike.
        for byte in self.0.bytes() {
            state.write_u8(byte.to_ascii_lowercase());
        }
        state.write_u8(0xff);
    }
}

impl Debug for Name {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Debug::fmt(&self.0, f)
    }
}

impl Display for Name {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Display::fmt(&self.0, f)
    }
}

/// Atomic counted reference to a [`Name`].
pub struct ArcName(Arc<str>);

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

impl From<&str> for ArcName {
    #[inline]
    fn from(value: &str) -> Self {
        Self(Arc::from(value))
    }
}

impl FromStr for ArcName {

    type Err = Infallible;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self::from(s))
    }

}

impl Deref for ArcName {
    type Target = Name;
    #[inline]
    fn deref(&self) -> &Self::Target {
        Name::new(&self.0)
    }
}

impl Borrow<Name> for ArcName {
    #[inline]
    fn borrow(&self) -> &Name {
        self
    }
}

impl PartialEq for ArcName {
    fn eq(&self, other: &Self) -> bool {
        **self == **other
    }
}

impl Eq for ArcName {}

impl Hash for ArcName {
    fn hash<H: Hasher>(&self, state: &mut H) {
        (**self).hash(state);
    }
}

impl Debug for ArcName {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Debug::fmt(&**self, f)
    }
}

impl Display for ArcName {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Display::fmt(&**self, f)
    }
}

// A Tango name is made of ASCII letters, digits, `_` and `-`, starting with a letter or a
// digit, see `is_tango_name_char`; what differs from one kind of name to another is how
// long it may be and how it is split.

fn check_non_empty_name(name: &str) -> bool {
    !name.is_empty() && name.chars().enumerate().all(is_tango_name_char)
}

fn check_non_empty_u8_name(name: &str) -> bool {
    !name.is_empty() && name.len() <= 255 && name.chars().enumerate().all(is_tango_name_char)
}

/// Check if a given Tango class name is valid.
pub fn check_tango_class_name(name: &str) -> bool {
    check_non_empty_name(name)
}

/// Check if a given part of a Tango server name, its executable or its instance, is valid.
pub fn check_tango_server_part_name(part: &str) -> bool {
    check_non_empty_name(part)
}

/// Check if a given Tango server name, `exe/inst`, is valid.
pub fn check_tango_server_name(name: &str) -> bool {
    let Some((exe, inst)) = name.split_once('/') else { return false };
    check_tango_server_part_name(exe) && 
    check_tango_server_part_name(inst)
}

fn check_tango_dev_part_name(part: &str) -> bool {
    !part.is_empty() && part.len() <= 85 && part.chars().enumerate().all(is_tango_name_char)
}

/// Check if a given Tango device name, `domain/family/member`, is valid, each part being
/// at most 85 long. An alias is not a device name, see [`check_tango_alias`].
pub fn check_tango_dev_name(name: &str) -> bool {
    let Some((domain, rest)) = name.split_once('/') else { return false };
    let Some((family, member)) = rest.split_once('/') else { return false };
    check_tango_dev_part_name(domain) &&
    check_tango_dev_part_name(family) &&
    check_tango_dev_part_name(member)
}

/// Check if a given Tango attribute name is valid, at most 255 long.
pub fn check_tango_attr_name(name: &str) -> bool {
    check_non_empty_u8_name(name)
}

/// Check if a given Tango command name is valid, at most 255 long.
pub fn check_tango_command_name(name: &str) -> bool {
    check_non_empty_u8_name(name)
}

/// Check if a given Tango property name is valid, at most 255 long.
pub fn check_tango_property_name(name: &str) -> bool {
    check_non_empty_u8_name(name)
}

/// Check if a given Tango device or attribute alias is valid, at most 255 long.
pub fn check_tango_alias(name: &str) -> bool {
    check_non_empty_u8_name(name)
}

/// An error common for name validation in Tango.
#[derive(thiserror::Error, Debug)]
pub enum TrlError {
    #[error("Invalid protocol, expecting tango://")]
    InvalidProtocol,
    #[error("Invalid host, wrong characters or too long (> 255)")]
    InvalidHost,
    #[error("Invalid port, expecting non-null 16-bit integer")]
    InvalidPort,
    #[error("Invalid hash, expecting #dbase=yes/no")]
    InvalidHash,
    #[error("Invalid or missing path, device-name[/attribute] with device-name being an alias or domain/family/member")]
    InvalidPath,
    #[error("Invalid device name, wrong characters or too long (> 85 per domain/family/member)")]
    InvalidDevName,
    #[error("Invalid attribute name, wrong characters or too long (> 255)")]
    InvalidAttrName,
    #[error("Invalid device or attribute alias, wrong characters or too long (> 255)")]
    InvalidAlias,
    #[error("Invalid property name, wrong characters or too long (> 255)")]
    InvalidPropName,
}

/// Tango Resource Locator, borrowing the string it was parsed from.
/// 
/// This is a custom reference: it is [`Copy`] and parsing one allocates nothing, the
/// owned counterpart being [`ArcTrl`].
/// 
/// RFC: 
/// - <https://tango-controls.readthedocs.io/projects/rfc/en/latest/16/TangoResourceLocator.html>
/// - <https://tango-controls.readthedocs.io/projects/rfc/en/latest/2/Device.html>
/// - <https://tango-controls.readthedocs.io/projects/rfc/en/latest/4/Attribute.html>
/// - <https://tango-controls.readthedocs.io/projects/rfc/en/latest/5/Property.html>
#[derive(Clone, Copy)]
pub struct Trl<'a> {
    /// The raw string.
    raw: &'a str,
    /// Where the parts are in the raw string.
    meta: TrlMeta,
}

/// Tango Resource Locator, owning the string it was parsed from.
/// 
/// Cloning this structure is cheap because it is backed by an Arc, and [`Self::as_trl`]
/// gives the [`Trl`] to read it through.
#[derive(Clone)]
pub struct ArcTrl {
    /// The raw string.
    raw: Arc<str>,
    /// Where the parts are in the raw string.
    meta: TrlMeta,
}

/// Where the parts of a TRL are in its raw string, shared by [`Trl`] and [`ArcTrl`].
#[derive(Debug, Clone, Copy)]
struct TrlMeta {
    /// If the host and port are present, this is the length of it.
    host_len_and_port: Option<(NonZero<u8>, NonZero<u16>)>,
    /// Offset of where the object starts.
    object_index: u16,
    /// Inner description of the object.
    object: TrlObjectMeta,
    /// From RFC 5/Property, maximum property name length is 255.
    property_len: Option<NonZero<u8>>,
    /// True if the tango:// protocol is present.
    protocol: bool,
    /// True if the host/port directly targets a database or not.
    db: bool,
}

/// The length of the device located, including the slashes. This can target either a
/// device or a device attribute, or be a simple alias without slashes. Both device
/// name and alias have max length of 255 if we don't count the slashes.
/// 
/// From RFC 4/Attribute, maximum attr name length is 255.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum TrlObjectMeta {
    Alias(NonZero<u8>),
    Dev(NonZero<u8>),
    Attr(NonZero<u8>, NonZero<u8>),
}

impl TrlMeta {

    fn parse(raw: &str) -> Result<Self, TrlError> {

        let mut rem = raw;
        let mut object_offset = 0u16;

        // Check protocol
        let mut protocol = false;
        if let Some((proto, new_rem)) = rem.split_once("://") {
            if proto != "tango" {
                return Err(TrlError::InvalidProtocol);
            }
            object_offset += "tango://".len() as u16;
            protocol = true;
            rem = new_rem;
        }

        // Parse the end hash first.
        let mut db = true;
        if let Some((new_rem, hash)) = rem.rsplit_once('#') {
            db = match hash {
                "dbase=yes" => true,
                "dbase=no" => false,
                _ => return Err(TrlError::InvalidHash),
            };
            rem = new_rem;
        }

        // Then parse the property, we don't validate the property immediately because 
        // acceptable characters depend on whether this is device property or attr property.
        let mut property_len = None;
        if let Some((new_rem, property_raw)) = rem.rsplit_once("->") {
            if !check_tango_property_name(property_raw) {
                return Err(TrlError::InvalidPropName);
            }
            property_len = Some(NonZero::new(property_raw.len() as u8).unwrap());
            rem = new_rem;
        }

        // Only 4 parts at most, construct an array on stack.
        let mut parts = [""; 5];
        let mut parts_count = 0;
        for part in rem.split('/') {
            // If there are more parts it's not normal!
            if parts_count >= parts.len() {
                return Err(TrlError::InvalidPath);
            }
            parts[parts_count] = part;
            parts_count += 1;
        }

        
        // Get a slice with the real number of parts.
        let mut parts = &mut parts[..parts_count];
        debug_assert!(!parts.is_empty(), "A split we should have at least one element");

        // Try to find host:port in the first part if possible.
        let mut host_len_and_port = None;
        if let Some((host_raw, port_raw)) = parts[0].split_once(':') {

            // Remove the host:port part from the parts, check if there are still parts.
            parts = &mut parts[1..];
            if parts.is_empty() {
                return Err(TrlError::InvalidPath)
            }

            let host_len = u8::try_from(host_raw.len()).ok()
                .and_then(NonZero::new)
                .ok_or(TrlError::InvalidHost)?;

            if !host_raw.chars().enumerate().all(is_hostname_char) {
                return Err(TrlError::InvalidHost);
            }

            let port = port_raw.parse::<NonZero<u16>>()
                .map_err(|_| TrlError::InvalidPort)?;

            host_len_and_port = Some((host_len, port));

            // +1 for ':', +1 for '/'
            object_offset += host_raw.len() as u16 + 1 + port_raw.len() as u16 + 1;

        }

        // If this is an alias, it can be of length 255.
        let object;
        if parts.len() == 1 {
            if !check_tango_alias(parts[0]) {
                return Err(TrlError::InvalidAlias);
            }
            object = TrlObjectMeta::Alias(NonZero::new(parts[0].len() as u8).unwrap());
        } else if parts.len() == 3 || parts.len() == 4 {

            let mut dev_len_raw = 0; // Add the 2 slashes to len.
            for &dev_part in &parts[..3] {
                if !check_tango_dev_part_name(dev_part) {
                    return Err(TrlError::InvalidDevName);
                }
                dev_len_raw += dev_part.len();
            }

            // Unwrap because we check every part to not be empty.
            let dev_len = NonZero::new(dev_len_raw as u8).unwrap();

            if let Some(&attr_raw) = parts.get(3) {
                if !check_tango_attr_name(attr_raw) {
                    return Err(TrlError::InvalidAttrName);
                }
                object = TrlObjectMeta::Attr(dev_len, NonZero::new(attr_raw.len() as u8).unwrap());
            } else {
                object = TrlObjectMeta::Dev(dev_len);
            }

        } else {
            return Err(TrlError::InvalidPath);
        }

        Ok(Self {
            host_len_and_port,
            object_index: object_offset,
            object,
            property_len,
            protocol,
            db,
        })

    }

}

impl<'a> Trl<'a> {

    /// Parse a TRL, borrowing the given string.
    pub fn parse(raw: &'a str) -> Result<Self, TrlError> {
        Ok(Self { raw, meta: TrlMeta::parse(raw)? })
    }

    /// Return the raw string for this TRL.
    #[inline]
    pub fn as_str(self) -> &'a str {
        self.raw
    }

    /// Copy the raw string into an owned TRL, without parsing it again.
    #[inline]
    pub fn to_arc(self) -> ArcTrl {
        ArcTrl { raw: Arc::from(self.raw), meta: self.meta }
    }

    #[inline]
    fn host_and_port_index(self) -> usize {
        if self.meta.protocol { "tango://".len() } else { 0 }
    }

    /// The host and port of this TRL, if it has any.
    pub fn host_and_port(self) -> Option<(&'a str, u16)> {
        let index = self.host_and_port_index();
        self.meta.host_len_and_port.map(|(host_len, port)| {
            (&self.raw[index..][..host_len.get() as usize], port.get())
        })
    }

    #[inline]
    fn object_index(self) -> usize {
        self.meta.object_index as usize
    }

    /// The object this TRL locates: an alias, a device or a device attribute.
    pub fn object(self) -> TrlObject<'a> {
        let index = self.object_index();
        match self.meta.object {
            TrlObjectMeta::Alias(alias_len) => {
                TrlObject::Alias(&self.raw[index..][..alias_len.get() as usize])
            }
            TrlObjectMeta::Dev(dev_len) => {
                // +2 for slashes that were ignored in length.
                TrlObject::Dev(&self.raw[index..][..dev_len.get() as usize + 2])
            }
            TrlObjectMeta::Attr(dev_len, attr_len) => {
                // +2 for slashes that were ignored in length.
                let (dev_name, raw) = self.raw[index..].split_at(dev_len.get() as usize + 2);
                // Start at 1 to ignore the slash between device and attribute.
                let attr_name = &raw[1..][..attr_len.get() as usize];
                TrlObject::Attr(dev_name, attr_name)
            }
        }
    }

    #[inline]
    fn property_index(self) -> usize {
        self.object_index() + match self.meta.object {
            TrlObjectMeta::Alias(alias_len) => 
                alias_len.get() as usize,
            TrlObjectMeta::Dev(dev_len) => 
                dev_len.get() as usize + 2,
            TrlObjectMeta::Attr(dev_len, attr_len) => 
                dev_len.get() as usize + attr_len.get() as usize + 3,
        } + 2  // +2 for the "->"
    }

    /// The name of the property this TRL locates on its object, if any.
    pub fn property(self) -> Option<&'a str> {
        let index = self.property_index();
        self.meta.property_len.map(|len| {
            &self.raw[index..][..len.get() as usize]
        })
    }

    /// Whether the object is reached through a database, which `#dbase=no` turns off.
    #[inline]
    pub fn db(self) -> bool {
        self.meta.db
    }

}

impl ArcTrl {

    /// Borrow this TRL.
    #[inline]
    pub fn as_trl(&self) -> Trl<'_> {
        Trl { raw: &self.raw, meta: self.meta }
    }

    /// Return the raw string for this TRL.
    #[inline]
    pub fn as_str(&self) -> &str {
        &self.raw
    }

}

impl FromStr for ArcTrl {

    type Err = TrlError;

    fn from_str(raw: &str) -> Result<Self, Self::Err> {
        Ok(Self { raw: Arc::from(raw), meta: TrlMeta::parse(raw)? })
    }

}

impl From<Trl<'_>> for ArcTrl {
    #[inline]
    fn from(trl: Trl<'_>) -> Self {
        trl.to_arc()
    }
}

impl<'a> From<&'a ArcTrl> for Trl<'a> {
    #[inline]
    fn from(trl: &'a ArcTrl) -> Self {
        trl.as_trl()
    }
}

impl fmt::Debug for Trl<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Trl").field(&self.raw).finish()
    }
}

impl fmt::Display for Trl<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.raw)
    }
}

impl fmt::Debug for ArcTrl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("ArcTrl").field(&&*self.raw).finish()
    }
}

impl fmt::Display for ArcTrl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.raw)
    }
}

/// The object pointed to by a Tango Resource Locator.
pub enum TrlObject<'a> {
    /// An alias for a device or attribute.
    Alias(&'a str),
    /// A device name.
    Dev(&'a str),
    /// An attribute name with its device name.
    Attr(&'a str, &'a str),
}

/// From the RFC.
fn is_hostname_char((i, c): (usize, char)) -> bool {
    c.is_ascii_alphanumeric() || (i != 0 && (c == '-' || c == '.'))
}

/// From the RFC. 
/// 
/// With added:
/// - Dash as non first char '-'
/// - Digits as first char
fn is_tango_name_char((i, c): (usize, char)) -> bool {
    c.is_ascii_alphanumeric() || (i != 0 && (c == '_' || c == '-'))
}

/// Something that can be parsed into, or borrowed as, a [`Trl`].
pub trait IntoTrl<'a> {
    /// Get this as a TRL, failing if it is not a valid one.
    fn into_trl(self) -> Result<Trl<'a>, TrlError>;
}

impl<'a> IntoTrl<'a> for Trl<'a> {
    fn into_trl(self) -> Result<Trl<'a>, TrlError> {
        Ok(self)
    }
}

impl<'a> IntoTrl<'a> for &'a ArcTrl {
    fn into_trl(self) -> Result<Trl<'a>, TrlError> {
        Ok(self.as_trl())
    }
}

impl<'a> IntoTrl<'a> for &'a str {
    fn into_trl(self) -> Result<Trl<'a>, TrlError> {
        Trl::parse(self)
    }
}


#[cfg(test)]
mod tests {

    use super::*;
    use std::num::NonZero;
    use std::collections::HashSet;

    #[test]
    fn name_ignores_case() {

        assert_eq!(Name::new("Sys/TG_Test/1"), Name::new("sys/tg_test/1"));
        assert_ne!(Name::new("sys/tg_test/1"), Name::new("sys/tg_test/2"));
        assert_ne!(Name::new("attr"), Name::new("attr_2"));

        let names = HashSet::from([ArcName::from("Double_Scalar")]);
        assert!(names.contains(Name::new("double_scalar")));
        assert!(!names.contains(Name::new("double_scalar_w")));

    }

    #[test]
    fn name_keeps_case() {

        let name = Name::new("Double_Scalar");
        assert_eq!(name.as_str(), "Double_Scalar");
        assert_eq!(name.to_string(), "Double_Scalar");

        let arc_name = name.to_arc();
        assert_eq!(arc_name.as_str(), "Double_Scalar");
        assert_eq!(arc_name.to_string(), "Double_Scalar");
        assert_eq!("double_scalar".parse::<ArcName>().unwrap(), arc_name);

    }

    /// Letters, digits, `_` and `-` only, the latter two never first.
    #[test]
    fn name_chars() {
        assert!(check_tango_class_name("Motor_2-a"));
        assert!(check_tango_class_name("2Motor"));
        assert!(!check_tango_class_name(""));
        assert!(!check_tango_class_name("_Motor"));
        assert!(!check_tango_class_name("-Motor"));
        assert!(!check_tango_class_name("Mo tor"));
        assert!(!check_tango_class_name("Mo.tor"));
        assert!(!check_tango_class_name("Mo/tor"));
        assert!(!check_tango_class_name("Motör"));
    }

    /// At most 255 long for attributes, commands, properties and aliases, unbounded for
    /// classes.
    #[test]
    fn name_length() {
        let (max, over) = ("a".repeat(255), "a".repeat(256));
        assert!(check_tango_attr_name(&max) && !check_tango_attr_name(&over));
        assert!(check_tango_command_name(&max) && !check_tango_command_name(&over));
        assert!(check_tango_property_name(&max) && !check_tango_property_name(&over));
        assert!(check_tango_alias(&max) && !check_tango_alias(&over));
        assert!(check_tango_class_name(&over));
    }

    /// Exactly three parts, each a name at most 85 long.
    #[test]
    fn dev_name() {
        assert!(check_tango_dev_name("sys/tg_test/1"));
        assert!(check_tango_dev_name(&format!("{0}/{0}/{0}", "a".repeat(85))));
        assert!(!check_tango_dev_name(&format!("a/a/{}", "a".repeat(86))));
        assert!(!check_tango_dev_name("sys/tg_test"));
        assert!(!check_tango_dev_name("sys/tg_test/1/2"));
        assert!(!check_tango_dev_name("sys//1"));
        assert!(!check_tango_dev_name("sys/tg_test/_1"));
    }

    /// Exactly two parts, each a name.
    #[test]
    fn server_name() {
        assert!(check_tango_server_name("TangoTest/test"));
        assert!(!check_tango_server_name("TangoTest"));
        assert!(!check_tango_server_name("TangoTest/"));
        assert!(!check_tango_server_name("TangoTest/te/st"));
        assert!(!check_tango_server_name("TangoTest/te st"));
    }

    #[test]
    fn parse_and_get() {

        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        enum TrlObjectKind {
            Alias,
            Dev,
            Attr,
        }

        for protocol in [false, true] {
            for host_and_port in [false, true] {
                for object in [TrlObjectKind::Alias, TrlObjectKind::Dev, TrlObjectKind::Attr] {
                    for property in [false, true] {
                        for db in [None, Some(false), Some(true)] {
                        
                            let mut buf = String::new();
                            
                            if protocol {
                                buf.push_str("tango://");
                            }

                            if host_and_port {
                                buf.push_str("example.com:10000/");
                            }

                            let object_index = buf.len() as u16;
                            match object {
                                TrlObjectKind::Alias => buf.push_str("alias"),
                                TrlObjectKind::Dev => buf.push_str("domain/family/member"),
                                TrlObjectKind::Attr => buf.push_str("domain/family/member/attribute"),
                            }

                            if property {
                                buf.push_str("->property");
                            }

                            match db {
                                Some(false) => buf.push_str("#dbase=no"),
                                Some(true) => buf.push_str("#dbase=yes"),
                                None => (),
                            }

                            let trl = Trl::parse(&buf).unwrap();

                            assert_eq!(trl.meta.protocol, protocol);
                            assert_eq!(trl.meta.host_len_and_port, host_and_port.then_some((NonZero::new(11u8).unwrap(), NonZero::new(10000u16).unwrap())));
                            assert_eq!(trl.meta.object_index, object_index);
                            assert_eq!(trl.meta.object, match object {
                                TrlObjectKind::Alias => TrlObjectMeta::Alias(NonZero::new(5u8).unwrap()),
                                TrlObjectKind::Dev => TrlObjectMeta::Dev(NonZero::new(18u8).unwrap()),
                                TrlObjectKind::Attr => TrlObjectMeta::Attr(NonZero::new(18u8).unwrap(), NonZero::new(9u8).unwrap()),
                            });
                            assert_eq!(trl.meta.property_len, property.then_some(NonZero::new(8u8).unwrap()));
                            assert_eq!(trl.meta.db, db.unwrap_or(true));

                        }
                    }
                }
            }
        }

    }

}