labstream-proto 0.2.0

The LSL protocol state machines. No input and no output.
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
//! The data feed state machine, client side. SPEC.md 4 and 6.
//!
//! The machine takes bytes and returns bytes. It opens no socket and reads no
//! clock, so a test drives every state with a byte slice.

use crate::features::{self, Token};
use crate::header::{parse_block, Error, Headers, StatusLine};
use crate::negotiate::{BIG, LITTLE};
use labstream_wire::{ByteOrder, Codec, Format, Sample, TEST_PATTERN_OFFSETS};

/// What the client asks for.
#[derive(Debug, Clone, PartialEq)]
pub struct FeedParams {
    /// The version to ask for.
    pub version: i32,
    /// The UID of the stream to open.
    pub uid: String,
    /// The byte order of this machine.
    pub native_byte_order: i32,
    /// How fast this machine converts a byte order.
    ///
    /// A measured value. A test injects a fixed number, because no conformance
    /// test can compare it. SPEC.md 5.2.
    pub endian_performance: f64,
    /// True when this machine holds IEEE-754 floats.
    pub has_ieee754_floats: bool,
    /// True when this machine holds subnormal values.
    pub supports_subnormals: bool,
    /// The width of one channel value. Zero for a string stream.
    pub value_size: i32,
    /// The buffer length to ask for.
    pub max_buffer_length: i32,
    /// The chunk length to ask for. Zero means no limit.
    pub max_chunk_length: i32,
    /// The host name of this machine.
    pub hostname: String,
    /// The source identifier of the stream.
    pub source_id: String,
    /// The session identifier.
    pub session_id: String,
}

impl FeedParams {
    /// Build the usual parameters for a stream.
    pub fn new(uid: &str, format: Format) -> Self {
        FeedParams {
            version: crate::negotiate::LSL_PROTOCOL_VERSION,
            uid: uid.to_string(),
            native_byte_order: if cfg!(target_endian = "little") {
                LITTLE
            } else {
                BIG
            },
            endian_performance: 0.0,
            has_ieee754_floats: true,
            supports_subnormals: true,
            value_size: format.width().unwrap_or(0) as i32,
            max_buffer_length: 360,
            max_chunk_length: 0,
            hostname: String::new(),
            source_id: String::new(),
            session_id: "default".to_string(),
        }
    }

    /// Write the request line and the header block.
    ///
    /// The field order matches `src/data_receiver.cpp:170-190`. A real liblsl
    /// server reads the names and not the order, but a transcript comparison
    /// needs the same order.
    pub fn to_wire(&self) -> Vec<u8> {
        let mut s = format!("LSL:streamfeed/{} {}\r\n", self.version, self.uid);
        s.push_str(&format!(
            "Native-Byte-Order: {}\r\n",
            self.native_byte_order
        ));
        s.push_str(&format!(
            "Endian-Performance: {}\r\n",
            self.endian_performance.floor()
        ));
        s.push_str(&format!(
            "Has-IEEE754-Floats: {}\r\n",
            self.has_ieee754_floats as i32
        ));
        s.push_str(&format!(
            "Supports-Subnormals: {}\r\n",
            self.supports_subnormals as i32
        ));
        s.push_str(&format!("Value-Size: {}\r\n", self.value_size));
        // liblsl writes this name, and the server never reads it. SPEC.md 4.4.
        s.push_str(&format!("Data-Protocol-Version: {}\r\n", self.version));
        s.push_str(&format!(
            "Max-Buffer-Length: {}\r\n",
            self.max_buffer_length
        ));
        s.push_str(&format!("Max-Chunk-Length: {}\r\n", self.max_chunk_length));
        s.push_str(&format!("Hostname: {}\r\n", self.hostname));
        s.push_str(&format!("Source-Id: {}\r\n", self.source_id));
        s.push_str(&format!("Session-Id: {}\r\n", self.session_id));
        s.push_str("\r\n");
        s.into_bytes()
    }

    /// Write the request with a `Labstream-Features` line, after the fields
    /// of liblsl. With no tokens, the request is the same as
    /// [`FeedParams::to_wire`]. `docs/extensions.md`.
    pub fn to_wire_with(&self, features: &[Token]) -> Vec<u8> {
        let mut bytes = self.to_wire();
        if !features.is_empty() {
            // Put the line before the empty line that ends the block.
            bytes.truncate(bytes.len() - 2);
            bytes.extend_from_slice(features::header_line(features).as_bytes());
            bytes.extend_from_slice(b"\r\n");
        }
        bytes
    }
}

/// The parameters that the answer settled.
#[derive(Debug, Clone, PartialEq)]
pub struct FeedAgreement {
    /// The negotiated data protocol version.
    pub data_protocol_version: i32,
    /// The byte order for the sample stream.
    pub order: ByteOrder,
    /// True when the reader clears subnormal values.
    pub suppress_subnormals: bool,
    /// The UID that the answer named.
    pub uid: String,
}

/// Where the client is in the handshake.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
    /// The request went out. The client waits for the answer headers.
    AwaitingHeaders,
    /// The headers arrived. The client waits for two test pattern samples.
    AwaitingTestPattern,
    /// The handshake finished. Every later byte is a sample.
    Streaming,
    /// The handshake stopped.
    Failed,
}

/// The client side of a data feed.
pub struct FeedClient {
    params: FeedParams,
    format: Format,
    channels: usize,
    state: State,
    agreement: Option<FeedAgreement>,
    codec: Option<Codec>,
    /// The features that the request offered.
    offer: Vec<Token>,
    /// The features that are on, once the headers arrive.
    features: Vec<Token>,
}

impl FeedClient {
    /// Build a client and return the bytes to send.
    pub fn start(params: FeedParams, format: Format, channels: usize) -> (Self, Vec<u8>) {
        Self::start_with(params, format, channels, Vec::new())
    }

    /// Build a client that offers features, and return the bytes to send.
    ///
    /// With no tokens, this is the same as [`FeedClient::start`].
    /// `docs/extensions.md`.
    pub fn start_with(
        params: FeedParams,
        format: Format,
        channels: usize,
        offer: Vec<Token>,
    ) -> (Self, Vec<u8>) {
        let bytes = params.to_wire_with(&offer);
        (
            FeedClient {
                params,
                format,
                channels,
                state: State::AwaitingHeaders,
                agreement: None,
                codec: None,
                offer,
                features: Vec::new(),
            },
            bytes,
        )
    }

    /// The features that are on for this connection. Empty until the headers
    /// arrive, and empty when the outlet gave no answer for them.
    pub fn features(&self) -> &[Token] {
        &self.features
    }

    /// The current state.
    pub fn state(&self) -> State {
        self.state
    }

    /// What the answer settled. Available once the headers arrive.
    pub fn agreement(&self) -> Option<&FeedAgreement> {
        self.agreement.as_ref()
    }

    /// The codec for the sample stream. Available once the headers arrive.
    pub fn codec(&self) -> Option<&Codec> {
        self.codec.as_ref()
    }

    /// Read the answer headers.
    ///
    /// Returns the number of bytes used. A buffer with no complete block
    /// returns `Error::Incomplete`, and the caller reads more bytes.
    pub fn on_headers(&mut self, buf: &[u8]) -> Result<usize, Error> {
        let nl = match buf.iter().position(|&b| b == b'\n') {
            Some(n) => n,
            None => return Err(Error::Incomplete),
        };
        let status = StatusLine::parse(&String::from_utf8_lossy(&buf[..nl]))?;

        // A newer major version stops the feed.
        // `src/data_receiver.cpp:200-203`.
        if status.version / 100 > self.params.version / 100 {
            self.state = State::Failed;
            return Err(Error::VersionTooNew {
                theirs: status.version,
                ours: self.params.version,
            });
        }

        if status.action() != crate::header::StatusAction::Proceed {
            self.state = State::Failed;
            return Err(Error::Status(status));
        }

        let (headers, used) = match parse_block(&buf[nl + 1..]) {
            Some(x) => x,
            None => return Err(Error::Incomplete),
        };

        let agreement = self.read_answer(&headers)?;
        // An outlet that does not know the header sends no answer for it, so
        // no feature is on.
        let answered = headers
            .get(features::HEADER_KEY)
            .map(features::parse)
            .unwrap_or_default();
        self.features = features::agreed(&self.offer, &answered);
        let order = agreement.order;
        self.codec = Some(
            Codec::new(self.format, self.channels, order)
                .with_suppress_subnormals(agreement.suppress_subnormals),
        );
        self.agreement = Some(agreement);
        self.state = State::AwaitingTestPattern;
        Ok(nl + 1 + used)
    }

    fn read_answer(&mut self, h: &Headers) -> Result<FeedAgreement, Error> {
        // The UID must match. `src/data_receiver.cpp:242`.
        let uid = h.get("uid").unwrap_or("").to_string();
        if !uid.is_empty() && uid != self.params.uid {
            self.state = State::Failed;
            return Err(Error::UidMismatch {
                expected: self.params.uid.clone(),
                actual: uid,
            });
        }

        // A value of 0 means the native order of the reader. This case exists
        // for liblsl 1.13 and earlier. `src/data_receiver.cpp:231`.
        let raw = h.get_int("byte-order").unwrap_or(LITTLE as i64) as i32;
        let order_value = if raw == 0 {
            self.params.native_byte_order
        } else {
            raw
        };
        let order = match ByteOrder::from_wire(order_value) {
            Some(o) => o,
            None => {
                self.state = State::Failed;
                return Err(Error::ByteOrderNotSupported(order_value));
            }
        };

        let version = h
            .get_int("data-protocol-version")
            .unwrap_or(self.params.version as i64) as i32;
        if version > self.params.version {
            self.state = State::Failed;
            return Err(Error::VersionTooNew {
                theirs: version,
                ours: self.params.version,
            });
        }
        // A server can agree to a version below the one that was asked for.
        // `src/tcp_server.cpp:576` only refuses a different major version, so
        // a 1.10 request against a server set to 1.00 is answered with 1.00.
        //
        // Protocol 1.00 carries every sample in a Boost archive
        // (`src/sample.cpp:330`), which this implementation does not read. It
        // has to stop here. Without this test the bytes of the archive are
        // decoded as 1.10 samples, and the first error is a wrong tag rather
        // than a wrong version.
        if version < 110 {
            self.state = State::Failed;
            return Err(Error::VersionTooOld { theirs: version });
        }

        Ok(FeedAgreement {
            data_protocol_version: version,
            order,
            suppress_subnormals: h.get_bool("suppress-subnormals").unwrap_or(false),
            uid,
        })
    }

    /// Read the two test pattern samples and compare them. SPEC.md 6.
    ///
    /// The client builds the expected samples itself. A mismatch means the
    /// formats differ, and liblsl stops the feed with a named error.
    ///
    /// Returns the number of bytes used.
    pub fn on_test_pattern(&mut self, buf: &[u8]) -> Result<usize, TestPatternError> {
        let codec = self.codec.as_ref().ok_or(TestPatternError::NotReady)?;
        let mut off = 0usize;
        for (i, pattern) in TEST_PATTERN_OFFSETS.iter().enumerate() {
            let (got, n) = match codec.decode(&buf[off..]) {
                Ok(x) => x,
                Err(labstream_wire::Error::Truncated) => return Err(TestPatternError::Incomplete),
                Err(e) => {
                    self.state = State::Failed;
                    return Err(TestPatternError::Decode(e));
                }
            };
            let want = labstream_wire::test_pattern(self.format, self.channels, *pattern);
            if !same_sample(&got, &want) {
                self.state = State::Failed;
                return Err(TestPatternError::Mismatch {
                    index: i,
                    expected: Box::new(want),
                    actual: Box::new(got),
                });
            }
            off += n;
        }
        self.state = State::Streaming;
        Ok(off)
    }

    /// Read samples from the stream.
    pub fn on_samples(&self, buf: &[u8]) -> Result<(Vec<Sample>, usize), labstream_wire::Error> {
        let codec = self.codec.as_ref().expect("the handshake set the codec");
        codec.decode_all(buf)
    }
}

/// Compare two samples by bit pattern.
///
/// liblsl compares samples with `operator!=`. A direct comparison of floats
/// fails for a value that is not a number, so this compares bits.
fn same_sample(a: &Sample, b: &Sample) -> bool {
    use labstream_wire::Value;
    a.timestamp.to_bits() == b.timestamp.to_bits()
        && a.values.len() == b.values.len()
        && a.values.iter().zip(&b.values).all(|(x, y)| match (x, y) {
            (Value::F32(p), Value::F32(q)) => p.to_bits() == q.to_bits(),
            (Value::F64(p), Value::F64(q)) => p.to_bits() == q.to_bits(),
            _ => x == y,
        })
}

/// A failure while reading the test pattern.
#[derive(Debug, Clone, PartialEq)]
pub enum TestPatternError {
    /// The buffer holds no complete sample yet.
    Incomplete,
    /// The handshake has not reached this stage.
    NotReady,
    /// The codec refused the bytes.
    Decode(labstream_wire::Error),
    /// A sample did not match the pattern.
    ///
    /// liblsl reports `The received test-pattern samples do not match the
    /// specification. The protocol formats are likely incompatible.`
    /// (`src/data_receiver.cpp:294`).
    Mismatch {
        /// Which of the two samples differed.
        index: usize,
        /// The sample that the specification produces.
        expected: Box<Sample>,
        /// The sample that arrived.
        actual: Box<Sample>,
    },
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::header::parse_block;
    use crate::negotiate::{negotiate, Accepted, FeedRequest, Outcome, ServerStream};

    fn handshake(
        format: Format,
        channels: usize,
        client_order: i32,
        client_perf: f64,
    ) -> FeedClient {
        let mut p = FeedParams::new("uid-1", format);
        p.native_byte_order = client_order;
        p.endian_performance = client_perf;
        let (mut client, request) = FeedClient::start(p, format, channels);

        // Drive a server built from the same specification.
        let text = String::from_utf8_lossy(&request);
        let head = text.split("\r\n").next().unwrap().to_string();
        let uid = head.split(' ').nth(1).unwrap_or("").to_string();
        let block_start = request.iter().position(|&b| b == b'\n').unwrap() + 1;
        let (headers, _) = parse_block(&request[block_start..]).expect("a block");

        let srv = ServerStream::new("uid-1", format, LITTLE, 1000.0);
        let req = FeedRequest::from_headers(110, &uid, &headers, srv.channel_bytes);
        let accepted = match negotiate(&req, &srv) {
            Outcome::Accept(a) => a,
            Outcome::Refuse(s) => panic!("refused: {} {}", s.code, s.message),
        };

        let answer = accepted.to_wire(110, "uid-1");
        client.on_headers(answer.as_bytes()).expect("headers");

        // The server then sends the two test pattern samples.
        let codec = *client.codec().expect("a codec");
        let mut bytes = Vec::new();
        for off in TEST_PATTERN_OFFSETS {
            let s = labstream_wire::test_pattern(format, channels, off);
            codec.encode(&s, &mut bytes).expect("encode");
        }
        let used = client.on_test_pattern(&bytes).expect("the test pattern");
        assert_eq!(used, bytes.len());
        client
    }

    #[test]
    fn the_request_carries_every_header_that_liblsl_writes() {
        let p = FeedParams::new("abc", Format::Float32);
        let text = String::from_utf8(p.to_wire()).unwrap();
        for name in [
            "Native-Byte-Order",
            "Endian-Performance",
            "Has-IEEE754-Floats",
            "Supports-Subnormals",
            "Value-Size",
            "Data-Protocol-Version",
            "Max-Buffer-Length",
            "Max-Chunk-Length",
            "Hostname",
            "Source-Id",
            "Session-Id",
        ] {
            assert!(text.contains(name), "the request is missing {name}");
        }
        assert!(text.starts_with("LSL:streamfeed/110 abc\r\n"));
        assert!(text.ends_with("\r\n\r\n"));
    }

    /// Run the feature exchange through both header parsers, as the outlet
    /// and the inlet do. `answer_features` is the server side decision.
    fn feature_handshake(offer: Vec<Token>, allowed: &[String]) -> FeedClient {
        let p = FeedParams::new("uid-1", Format::Float32);
        let (mut client, request) = FeedClient::start_with(p, Format::Float32, 2, offer);
        let block_start = request.iter().position(|&b| b == b'\n').unwrap() + 1;
        let (headers, _) = parse_block(&request[block_start..]).expect("a block");
        let srv = ServerStream::new("uid-1", Format::Float32, LITTLE, 1000.0);
        let req = FeedRequest::from_headers(110, "uid-1", &headers, srv.channel_bytes);
        let accepted = match negotiate(&req, &srv) {
            Outcome::Accept(a) => a,
            Outcome::Refuse(s) => panic!("refused: {}", s.code),
        };
        let answered = headers
            .get(features::HEADER_KEY)
            .map(|v| features::answer(&features::parse(v), allowed));
        let answer = accepted.to_wire_with(110, "uid-1", answered.as_deref());
        client.on_headers(answer.as_bytes()).expect("headers");
        client
    }

    #[test]
    fn a_request_with_no_offer_is_the_plain_request() {
        let p = FeedParams::new("abc", Format::Float32);
        assert_eq!(p.to_wire_with(&[]), p.to_wire());
    }

    #[test]
    fn the_offer_goes_last_in_the_block() {
        let p = FeedParams::new("abc", Format::Float32);
        let text = String::from_utf8(p.to_wire_with(&[Token::new("seq", 1)])).unwrap();
        assert!(text.ends_with("Session-Id: default\r\nLabstream-Features: seq/1\r\n\r\n"));
        assert!(text.starts_with(&String::from_utf8(p.to_wire()).unwrap()[..40]));
    }

    #[test]
    fn two_labstream_peers_agree_on_seq() {
        let all = vec![features::SEQ.to_string()];
        let c = feature_handshake(features::offer(&all), &all);
        assert!(features::has(c.features(), features::SEQ, 1));
    }

    #[test]
    fn two_labstream_peers_agree_on_resume_with_a_parameter() {
        let all = vec![features::SEQ.to_string(), features::RESUME.to_string()];
        let asked = features::ResumeParam {
            epoch: 0x9c3e_51a0_d2b7_f4e8,
            number: 0x1f4a0,
        };
        let mut offer = features::offer(&all);
        offer.extend(features::offer_resume(&all, Some(asked)));

        let p = FeedParams::new("uid-1", Format::Float32);
        let (mut client, request) = FeedClient::start_with(p, Format::Float32, 2, offer);
        let block_start = request.iter().position(|&b| b == b'\n').unwrap() + 1;
        let (headers, _) = parse_block(&request[block_start..]).expect("a block");
        let srv = ServerStream::new("uid-1", Format::Float32, LITTLE, 1000.0);
        let req = FeedRequest::from_headers(110, "uid-1", &headers, srv.channel_bytes);
        let accepted = match negotiate(&req, &srv) {
            Outcome::Accept(a) => a,
            Outcome::Refuse(s) => panic!("refused: {}", s.code),
        };

        // The outlet side: the request survives the header parser, which
        // converts the line to lowercase.
        let offered = features::parse(headers.get(features::HEADER_KEY).unwrap());
        let mut answered = features::answer(&offered, &all);
        let request = features::resume_request(&offered, &answered, &all);
        assert_eq!(request, Some(features::ResumeRequest::From(asked)));
        let given = features::ResumeParam {
            epoch: asked.epoch,
            number: 0x20000,
        };
        answered.push(given.token());

        let answer = accepted.to_wire_with(110, "uid-1", Some(&answered));
        client.on_headers(answer.as_bytes()).expect("headers");
        assert!(features::has(client.features(), features::SEQ, 1));
        assert_eq!(features::resume_answer(client.features()), Some(given));
    }

    #[test]
    fn an_outlet_that_allows_nothing_turns_seq_off() {
        let all = vec![features::SEQ.to_string()];
        let c = feature_handshake(features::offer(&all), &[]);
        assert!(c.features().is_empty());
    }

    #[test]
    fn an_answer_with_no_feature_line_turns_seq_off() {
        // A liblsl outlet and an older labstream outlet answer this way.
        let all = vec![features::SEQ.to_string()];
        let p = FeedParams::new("uid-1", Format::Float32);
        let (mut c, _) = FeedClient::start_with(p, Format::Float32, 2, features::offer(&all));
        c.on_headers(b"LSL/110 200 OK\r\nUID: uid-1\r\nByte-Order: 1234\r\nSuppress-Subnormals: 0\r\nData-Protocol-Version: 110\r\n\r\n")
            .expect("headers");
        assert!(c.features().is_empty());
    }

    #[test]
    fn an_answer_with_no_request_line_has_no_feature_line() {
        let a = Accepted {
            data_protocol_version: 110,
            byte_order: LITTLE,
            reverse_byte_order: false,
            suppress_subnormals: false,
            max_buffer_length: 360,
            max_chunk_length: 0,
        };
        assert_eq!(a.to_wire_with(110, "u", None), a.to_wire(110, "u"));
        assert!(a
            .to_wire_with(110, "u", Some(&[]))
            .contains("Labstream-Features: \r\n"));
    }

    #[test]
    fn a_full_handshake_reaches_the_streaming_state() {
        let c = handshake(Format::Float32, 8, LITTLE, 0.0);
        assert_eq!(c.state(), State::Streaming);
        let a = c.agreement().expect("an agreement");
        assert_eq!(a.data_protocol_version, 110);
        assert_eq!(a.order, ByteOrder::Little);
    }

    #[test]
    fn a_slow_client_makes_the_server_swap() {
        let c = handshake(Format::Double64, 4, BIG, 0.0);
        assert_eq!(c.agreement().unwrap().order, ByteOrder::Big);
    }

    #[test]
    fn a_wrong_uid_in_the_answer_stops_the_feed() {
        let p = FeedParams::new("uid-1", Format::Float32);
        let (mut c, _) = FeedClient::start(p, Format::Float32, 1);
        let answer = "LSL/110 200 OK\r\nUID: another\r\nByte-Order: 1234\r\n\
                      Suppress-Subnormals: 0\r\nData-Protocol-Version: 110\r\n\r\n";
        match c.on_headers(answer.as_bytes()) {
            Err(Error::UidMismatch { actual, .. }) => assert_eq!(actual, "another"),
            other => panic!("expected a UID mismatch, got {other:?}"),
        }
        assert_eq!(c.state(), State::Failed);
    }

    #[test]
    fn a_404_answer_stops_the_feed() {
        let p = FeedParams::new("uid-1", Format::Float32);
        let (mut c, _) = FeedClient::start(p, Format::Float32, 1);
        match c.on_headers(b"LSL/110 404 Not found\r\n\r\n") {
            Err(Error::Status(s)) => assert_eq!(s.code, 404),
            other => panic!("expected a status error, got {other:?}"),
        }
        assert_eq!(c.state(), State::Failed);
    }

    #[test]
    fn a_byte_order_of_zero_means_the_native_order() {
        // The case for liblsl 1.13 and earlier.
        let p = FeedParams::new("uid-1", Format::Float32);
        let (mut c, _) = FeedClient::start(p, Format::Float32, 1);
        let answer = "LSL/110 200 OK\r\nUID: uid-1\r\nByte-Order: 0\r\n\
                      Suppress-Subnormals: 0\r\nData-Protocol-Version: 110\r\n\r\n";
        c.on_headers(answer.as_bytes()).expect("headers");
        assert_eq!(c.agreement().unwrap().order, ByteOrder::native());
    }

    #[test]
    fn a_wrong_test_pattern_stops_the_feed() {
        let p = FeedParams::new("uid-1", Format::Float32);
        let (mut c, _) = FeedClient::start(p, Format::Float32, 2);
        let answer = "LSL/110 200 OK\r\nUID: uid-1\r\nByte-Order: 1234\r\n\
                      Suppress-Subnormals: 0\r\nData-Protocol-Version: 110\r\n\r\n";
        c.on_headers(answer.as_bytes()).expect("headers");

        // Send the second pattern first. A wrong implementation does this.
        let codec = *c.codec().unwrap();
        let mut bytes = Vec::new();
        for off in [2, 4] {
            codec
                .encode(
                    &labstream_wire::test_pattern(Format::Float32, 2, off),
                    &mut bytes,
                )
                .unwrap();
        }
        match c.on_test_pattern(&bytes) {
            Err(TestPatternError::Mismatch { index, .. }) => assert_eq!(index, 0),
            other => panic!("expected a mismatch, got {other:?}"),
        }
        assert_eq!(c.state(), State::Failed);
    }

    #[test]
    fn an_incomplete_buffer_asks_for_more() {
        let p = FeedParams::new("uid-1", Format::Float32);
        let (mut c, _) = FeedClient::start(p, Format::Float32, 1);
        assert_eq!(
            c.on_headers(b"LSL/110 200 OK\r\nUID: uid-1\r\n"),
            Err(Error::Incomplete)
        );
        assert_eq!(c.state(), State::AwaitingHeaders);
    }
}