Skip to main content

labstream_proto/
feed.rs

1//! The data feed state machine, client side. SPEC.md 4 and 6.
2//!
3//! The machine takes bytes and returns bytes. It opens no socket and reads no
4//! clock, so a test drives every state with a byte slice.
5
6use crate::features::{self, Token};
7use crate::header::{parse_block, Error, Headers, StatusLine};
8use crate::negotiate::{BIG, LITTLE};
9use labstream_wire::{ByteOrder, Codec, Format, Sample, TEST_PATTERN_OFFSETS};
10
11/// What the client asks for.
12#[derive(Debug, Clone, PartialEq)]
13pub struct FeedParams {
14    /// The version to ask for.
15    pub version: i32,
16    /// The UID of the stream to open.
17    pub uid: String,
18    /// The byte order of this machine.
19    pub native_byte_order: i32,
20    /// How fast this machine converts a byte order.
21    ///
22    /// A measured value. A test injects a fixed number, because no conformance
23    /// test can compare it. SPEC.md 5.2.
24    pub endian_performance: f64,
25    /// True when this machine holds IEEE-754 floats.
26    pub has_ieee754_floats: bool,
27    /// True when this machine holds subnormal values.
28    pub supports_subnormals: bool,
29    /// The width of one channel value. Zero for a string stream.
30    pub value_size: i32,
31    /// The buffer length to ask for.
32    pub max_buffer_length: i32,
33    /// The chunk length to ask for. Zero means no limit.
34    pub max_chunk_length: i32,
35    /// The host name of this machine.
36    pub hostname: String,
37    /// The source identifier of the stream.
38    pub source_id: String,
39    /// The session identifier.
40    pub session_id: String,
41}
42
43impl FeedParams {
44    /// Build the usual parameters for a stream.
45    pub fn new(uid: &str, format: Format) -> Self {
46        FeedParams {
47            version: crate::negotiate::LSL_PROTOCOL_VERSION,
48            uid: uid.to_string(),
49            native_byte_order: if cfg!(target_endian = "little") {
50                LITTLE
51            } else {
52                BIG
53            },
54            endian_performance: 0.0,
55            has_ieee754_floats: true,
56            supports_subnormals: true,
57            value_size: format.width().unwrap_or(0) as i32,
58            max_buffer_length: 360,
59            max_chunk_length: 0,
60            hostname: String::new(),
61            source_id: String::new(),
62            session_id: "default".to_string(),
63        }
64    }
65
66    /// Write the request line and the header block.
67    ///
68    /// The field order matches `src/data_receiver.cpp:170-190`. A real liblsl
69    /// server reads the names and not the order, but a transcript comparison
70    /// needs the same order.
71    pub fn to_wire(&self) -> Vec<u8> {
72        let mut s = format!("LSL:streamfeed/{} {}\r\n", self.version, self.uid);
73        s.push_str(&format!(
74            "Native-Byte-Order: {}\r\n",
75            self.native_byte_order
76        ));
77        s.push_str(&format!(
78            "Endian-Performance: {}\r\n",
79            self.endian_performance.floor()
80        ));
81        s.push_str(&format!(
82            "Has-IEEE754-Floats: {}\r\n",
83            self.has_ieee754_floats as i32
84        ));
85        s.push_str(&format!(
86            "Supports-Subnormals: {}\r\n",
87            self.supports_subnormals as i32
88        ));
89        s.push_str(&format!("Value-Size: {}\r\n", self.value_size));
90        // liblsl writes this name, and the server never reads it. SPEC.md 4.4.
91        s.push_str(&format!("Data-Protocol-Version: {}\r\n", self.version));
92        s.push_str(&format!(
93            "Max-Buffer-Length: {}\r\n",
94            self.max_buffer_length
95        ));
96        s.push_str(&format!("Max-Chunk-Length: {}\r\n", self.max_chunk_length));
97        s.push_str(&format!("Hostname: {}\r\n", self.hostname));
98        s.push_str(&format!("Source-Id: {}\r\n", self.source_id));
99        s.push_str(&format!("Session-Id: {}\r\n", self.session_id));
100        s.push_str("\r\n");
101        s.into_bytes()
102    }
103
104    /// Write the request with a `Labstream-Features` line, after the fields
105    /// of liblsl. With no tokens, the request is the same as
106    /// [`FeedParams::to_wire`]. `docs/extensions.md`.
107    pub fn to_wire_with(&self, features: &[Token]) -> Vec<u8> {
108        let mut bytes = self.to_wire();
109        if !features.is_empty() {
110            // Put the line before the empty line that ends the block.
111            bytes.truncate(bytes.len() - 2);
112            bytes.extend_from_slice(features::header_line(features).as_bytes());
113            bytes.extend_from_slice(b"\r\n");
114        }
115        bytes
116    }
117}
118
119/// The parameters that the answer settled.
120#[derive(Debug, Clone, PartialEq)]
121pub struct FeedAgreement {
122    /// The negotiated data protocol version.
123    pub data_protocol_version: i32,
124    /// The byte order for the sample stream.
125    pub order: ByteOrder,
126    /// True when the reader clears subnormal values.
127    pub suppress_subnormals: bool,
128    /// The UID that the answer named.
129    pub uid: String,
130}
131
132/// Where the client is in the handshake.
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub enum State {
135    /// The request went out. The client waits for the answer headers.
136    AwaitingHeaders,
137    /// The headers arrived. The client waits for two test pattern samples.
138    AwaitingTestPattern,
139    /// The handshake finished. Every later byte is a sample.
140    Streaming,
141    /// The handshake stopped.
142    Failed,
143}
144
145/// The client side of a data feed.
146pub struct FeedClient {
147    params: FeedParams,
148    format: Format,
149    channels: usize,
150    state: State,
151    agreement: Option<FeedAgreement>,
152    codec: Option<Codec>,
153    /// The features that the request offered.
154    offer: Vec<Token>,
155    /// The features that are on, once the headers arrive.
156    features: Vec<Token>,
157}
158
159impl FeedClient {
160    /// Build a client and return the bytes to send.
161    pub fn start(params: FeedParams, format: Format, channels: usize) -> (Self, Vec<u8>) {
162        Self::start_with(params, format, channels, Vec::new())
163    }
164
165    /// Build a client that offers features, and return the bytes to send.
166    ///
167    /// With no tokens, this is the same as [`FeedClient::start`].
168    /// `docs/extensions.md`.
169    pub fn start_with(
170        params: FeedParams,
171        format: Format,
172        channels: usize,
173        offer: Vec<Token>,
174    ) -> (Self, Vec<u8>) {
175        let bytes = params.to_wire_with(&offer);
176        (
177            FeedClient {
178                params,
179                format,
180                channels,
181                state: State::AwaitingHeaders,
182                agreement: None,
183                codec: None,
184                offer,
185                features: Vec::new(),
186            },
187            bytes,
188        )
189    }
190
191    /// The features that are on for this connection. Empty until the headers
192    /// arrive, and empty when the outlet gave no answer for them.
193    pub fn features(&self) -> &[Token] {
194        &self.features
195    }
196
197    /// The current state.
198    pub fn state(&self) -> State {
199        self.state
200    }
201
202    /// What the answer settled. Available once the headers arrive.
203    pub fn agreement(&self) -> Option<&FeedAgreement> {
204        self.agreement.as_ref()
205    }
206
207    /// The codec for the sample stream. Available once the headers arrive.
208    pub fn codec(&self) -> Option<&Codec> {
209        self.codec.as_ref()
210    }
211
212    /// Read the answer headers.
213    ///
214    /// Returns the number of bytes used. A buffer with no complete block
215    /// returns `Error::Incomplete`, and the caller reads more bytes.
216    pub fn on_headers(&mut self, buf: &[u8]) -> Result<usize, Error> {
217        let nl = match buf.iter().position(|&b| b == b'\n') {
218            Some(n) => n,
219            None => return Err(Error::Incomplete),
220        };
221        let status = StatusLine::parse(&String::from_utf8_lossy(&buf[..nl]))?;
222
223        // A newer major version stops the feed.
224        // `src/data_receiver.cpp:200-203`.
225        if status.version / 100 > self.params.version / 100 {
226            self.state = State::Failed;
227            return Err(Error::VersionTooNew {
228                theirs: status.version,
229                ours: self.params.version,
230            });
231        }
232
233        if status.action() != crate::header::StatusAction::Proceed {
234            self.state = State::Failed;
235            return Err(Error::Status(status));
236        }
237
238        let (headers, used) = match parse_block(&buf[nl + 1..]) {
239            Some(x) => x,
240            None => return Err(Error::Incomplete),
241        };
242
243        let agreement = self.read_answer(&headers)?;
244        // An outlet that does not know the header sends no answer for it, so
245        // no feature is on.
246        let answered = headers
247            .get(features::HEADER_KEY)
248            .map(features::parse)
249            .unwrap_or_default();
250        self.features = features::agreed(&self.offer, &answered);
251        let order = agreement.order;
252        self.codec = Some(
253            Codec::new(self.format, self.channels, order)
254                .with_suppress_subnormals(agreement.suppress_subnormals),
255        );
256        self.agreement = Some(agreement);
257        self.state = State::AwaitingTestPattern;
258        Ok(nl + 1 + used)
259    }
260
261    fn read_answer(&mut self, h: &Headers) -> Result<FeedAgreement, Error> {
262        // The UID must match. `src/data_receiver.cpp:242`.
263        let uid = h.get("uid").unwrap_or("").to_string();
264        if !uid.is_empty() && uid != self.params.uid {
265            self.state = State::Failed;
266            return Err(Error::UidMismatch {
267                expected: self.params.uid.clone(),
268                actual: uid,
269            });
270        }
271
272        // A value of 0 means the native order of the reader. This case exists
273        // for liblsl 1.13 and earlier. `src/data_receiver.cpp:231`.
274        let raw = h.get_int("byte-order").unwrap_or(LITTLE as i64) as i32;
275        let order_value = if raw == 0 {
276            self.params.native_byte_order
277        } else {
278            raw
279        };
280        let order = match ByteOrder::from_wire(order_value) {
281            Some(o) => o,
282            None => {
283                self.state = State::Failed;
284                return Err(Error::ByteOrderNotSupported(order_value));
285            }
286        };
287
288        let version = h
289            .get_int("data-protocol-version")
290            .unwrap_or(self.params.version as i64) as i32;
291        if version > self.params.version {
292            self.state = State::Failed;
293            return Err(Error::VersionTooNew {
294                theirs: version,
295                ours: self.params.version,
296            });
297        }
298        // A server can agree to a version below the one that was asked for.
299        // `src/tcp_server.cpp:576` only refuses a different major version, so
300        // a 1.10 request against a server set to 1.00 is answered with 1.00.
301        //
302        // Protocol 1.00 carries every sample in a Boost archive
303        // (`src/sample.cpp:330`), which this implementation does not read. It
304        // has to stop here. Without this test the bytes of the archive are
305        // decoded as 1.10 samples, and the first error is a wrong tag rather
306        // than a wrong version.
307        if version < 110 {
308            self.state = State::Failed;
309            return Err(Error::VersionTooOld { theirs: version });
310        }
311
312        Ok(FeedAgreement {
313            data_protocol_version: version,
314            order,
315            suppress_subnormals: h.get_bool("suppress-subnormals").unwrap_or(false),
316            uid,
317        })
318    }
319
320    /// Read the two test pattern samples and compare them. SPEC.md 6.
321    ///
322    /// The client builds the expected samples itself. A mismatch means the
323    /// formats differ, and liblsl stops the feed with a named error.
324    ///
325    /// Returns the number of bytes used.
326    pub fn on_test_pattern(&mut self, buf: &[u8]) -> Result<usize, TestPatternError> {
327        let codec = self.codec.as_ref().ok_or(TestPatternError::NotReady)?;
328        let mut off = 0usize;
329        for (i, pattern) in TEST_PATTERN_OFFSETS.iter().enumerate() {
330            let (got, n) = match codec.decode(&buf[off..]) {
331                Ok(x) => x,
332                Err(labstream_wire::Error::Truncated) => return Err(TestPatternError::Incomplete),
333                Err(e) => {
334                    self.state = State::Failed;
335                    return Err(TestPatternError::Decode(e));
336                }
337            };
338            let want = labstream_wire::test_pattern(self.format, self.channels, *pattern);
339            if !same_sample(&got, &want) {
340                self.state = State::Failed;
341                return Err(TestPatternError::Mismatch {
342                    index: i,
343                    expected: Box::new(want),
344                    actual: Box::new(got),
345                });
346            }
347            off += n;
348        }
349        self.state = State::Streaming;
350        Ok(off)
351    }
352
353    /// Read samples from the stream.
354    pub fn on_samples(&self, buf: &[u8]) -> Result<(Vec<Sample>, usize), labstream_wire::Error> {
355        let codec = self.codec.as_ref().expect("the handshake set the codec");
356        codec.decode_all(buf)
357    }
358}
359
360/// Compare two samples by bit pattern.
361///
362/// liblsl compares samples with `operator!=`. A direct comparison of floats
363/// fails for a value that is not a number, so this compares bits.
364fn same_sample(a: &Sample, b: &Sample) -> bool {
365    use labstream_wire::Value;
366    a.timestamp.to_bits() == b.timestamp.to_bits()
367        && a.values.len() == b.values.len()
368        && a.values.iter().zip(&b.values).all(|(x, y)| match (x, y) {
369            (Value::F32(p), Value::F32(q)) => p.to_bits() == q.to_bits(),
370            (Value::F64(p), Value::F64(q)) => p.to_bits() == q.to_bits(),
371            _ => x == y,
372        })
373}
374
375/// A failure while reading the test pattern.
376#[derive(Debug, Clone, PartialEq)]
377pub enum TestPatternError {
378    /// The buffer holds no complete sample yet.
379    Incomplete,
380    /// The handshake has not reached this stage.
381    NotReady,
382    /// The codec refused the bytes.
383    Decode(labstream_wire::Error),
384    /// A sample did not match the pattern.
385    ///
386    /// liblsl reports `The received test-pattern samples do not match the
387    /// specification. The protocol formats are likely incompatible.`
388    /// (`src/data_receiver.cpp:294`).
389    Mismatch {
390        /// Which of the two samples differed.
391        index: usize,
392        /// The sample that the specification produces.
393        expected: Box<Sample>,
394        /// The sample that arrived.
395        actual: Box<Sample>,
396    },
397}
398
399#[cfg(test)]
400mod tests {
401    use super::*;
402    use crate::header::parse_block;
403    use crate::negotiate::{negotiate, Accepted, FeedRequest, Outcome, ServerStream};
404
405    fn handshake(
406        format: Format,
407        channels: usize,
408        client_order: i32,
409        client_perf: f64,
410    ) -> FeedClient {
411        let mut p = FeedParams::new("uid-1", format);
412        p.native_byte_order = client_order;
413        p.endian_performance = client_perf;
414        let (mut client, request) = FeedClient::start(p, format, channels);
415
416        // Drive a server built from the same specification.
417        let text = String::from_utf8_lossy(&request);
418        let head = text.split("\r\n").next().unwrap().to_string();
419        let uid = head.split(' ').nth(1).unwrap_or("").to_string();
420        let block_start = request.iter().position(|&b| b == b'\n').unwrap() + 1;
421        let (headers, _) = parse_block(&request[block_start..]).expect("a block");
422
423        let srv = ServerStream::new("uid-1", format, LITTLE, 1000.0);
424        let req = FeedRequest::from_headers(110, &uid, &headers, srv.channel_bytes);
425        let accepted = match negotiate(&req, &srv) {
426            Outcome::Accept(a) => a,
427            Outcome::Refuse(s) => panic!("refused: {} {}", s.code, s.message),
428        };
429
430        let answer = accepted.to_wire(110, "uid-1");
431        client.on_headers(answer.as_bytes()).expect("headers");
432
433        // The server then sends the two test pattern samples.
434        let codec = *client.codec().expect("a codec");
435        let mut bytes = Vec::new();
436        for off in TEST_PATTERN_OFFSETS {
437            let s = labstream_wire::test_pattern(format, channels, off);
438            codec.encode(&s, &mut bytes).expect("encode");
439        }
440        let used = client.on_test_pattern(&bytes).expect("the test pattern");
441        assert_eq!(used, bytes.len());
442        client
443    }
444
445    #[test]
446    fn the_request_carries_every_header_that_liblsl_writes() {
447        let p = FeedParams::new("abc", Format::Float32);
448        let text = String::from_utf8(p.to_wire()).unwrap();
449        for name in [
450            "Native-Byte-Order",
451            "Endian-Performance",
452            "Has-IEEE754-Floats",
453            "Supports-Subnormals",
454            "Value-Size",
455            "Data-Protocol-Version",
456            "Max-Buffer-Length",
457            "Max-Chunk-Length",
458            "Hostname",
459            "Source-Id",
460            "Session-Id",
461        ] {
462            assert!(text.contains(name), "the request is missing {name}");
463        }
464        assert!(text.starts_with("LSL:streamfeed/110 abc\r\n"));
465        assert!(text.ends_with("\r\n\r\n"));
466    }
467
468    /// Run the feature exchange through both header parsers, as the outlet
469    /// and the inlet do. `answer_features` is the server side decision.
470    fn feature_handshake(offer: Vec<Token>, allowed: &[String]) -> FeedClient {
471        let p = FeedParams::new("uid-1", Format::Float32);
472        let (mut client, request) = FeedClient::start_with(p, Format::Float32, 2, offer);
473        let block_start = request.iter().position(|&b| b == b'\n').unwrap() + 1;
474        let (headers, _) = parse_block(&request[block_start..]).expect("a block");
475        let srv = ServerStream::new("uid-1", Format::Float32, LITTLE, 1000.0);
476        let req = FeedRequest::from_headers(110, "uid-1", &headers, srv.channel_bytes);
477        let accepted = match negotiate(&req, &srv) {
478            Outcome::Accept(a) => a,
479            Outcome::Refuse(s) => panic!("refused: {}", s.code),
480        };
481        let answered = headers
482            .get(features::HEADER_KEY)
483            .map(|v| features::answer(&features::parse(v), allowed));
484        let answer = accepted.to_wire_with(110, "uid-1", answered.as_deref());
485        client.on_headers(answer.as_bytes()).expect("headers");
486        client
487    }
488
489    #[test]
490    fn a_request_with_no_offer_is_the_plain_request() {
491        let p = FeedParams::new("abc", Format::Float32);
492        assert_eq!(p.to_wire_with(&[]), p.to_wire());
493    }
494
495    #[test]
496    fn the_offer_goes_last_in_the_block() {
497        let p = FeedParams::new("abc", Format::Float32);
498        let text = String::from_utf8(p.to_wire_with(&[Token::new("seq", 1)])).unwrap();
499        assert!(text.ends_with("Session-Id: default\r\nLabstream-Features: seq/1\r\n\r\n"));
500        assert!(text.starts_with(&String::from_utf8(p.to_wire()).unwrap()[..40]));
501    }
502
503    #[test]
504    fn two_labstream_peers_agree_on_seq() {
505        let all = vec![features::SEQ.to_string()];
506        let c = feature_handshake(features::offer(&all), &all);
507        assert!(features::has(c.features(), features::SEQ, 1));
508    }
509
510    #[test]
511    fn two_labstream_peers_agree_on_resume_with_a_parameter() {
512        let all = vec![features::SEQ.to_string(), features::RESUME.to_string()];
513        let asked = features::ResumeParam {
514            epoch: 0x9c3e_51a0_d2b7_f4e8,
515            number: 0x1f4a0,
516        };
517        let mut offer = features::offer(&all);
518        offer.extend(features::offer_resume(&all, Some(asked)));
519
520        let p = FeedParams::new("uid-1", Format::Float32);
521        let (mut client, request) = FeedClient::start_with(p, Format::Float32, 2, offer);
522        let block_start = request.iter().position(|&b| b == b'\n').unwrap() + 1;
523        let (headers, _) = parse_block(&request[block_start..]).expect("a block");
524        let srv = ServerStream::new("uid-1", Format::Float32, LITTLE, 1000.0);
525        let req = FeedRequest::from_headers(110, "uid-1", &headers, srv.channel_bytes);
526        let accepted = match negotiate(&req, &srv) {
527            Outcome::Accept(a) => a,
528            Outcome::Refuse(s) => panic!("refused: {}", s.code),
529        };
530
531        // The outlet side: the request survives the header parser, which
532        // converts the line to lowercase.
533        let offered = features::parse(headers.get(features::HEADER_KEY).unwrap());
534        let mut answered = features::answer(&offered, &all);
535        let request = features::resume_request(&offered, &answered, &all);
536        assert_eq!(request, Some(features::ResumeRequest::From(asked)));
537        let given = features::ResumeParam {
538            epoch: asked.epoch,
539            number: 0x20000,
540        };
541        answered.push(given.token());
542
543        let answer = accepted.to_wire_with(110, "uid-1", Some(&answered));
544        client.on_headers(answer.as_bytes()).expect("headers");
545        assert!(features::has(client.features(), features::SEQ, 1));
546        assert_eq!(features::resume_answer(client.features()), Some(given));
547    }
548
549    #[test]
550    fn an_outlet_that_allows_nothing_turns_seq_off() {
551        let all = vec![features::SEQ.to_string()];
552        let c = feature_handshake(features::offer(&all), &[]);
553        assert!(c.features().is_empty());
554    }
555
556    #[test]
557    fn an_answer_with_no_feature_line_turns_seq_off() {
558        // A liblsl outlet and an older labstream outlet answer this way.
559        let all = vec![features::SEQ.to_string()];
560        let p = FeedParams::new("uid-1", Format::Float32);
561        let (mut c, _) = FeedClient::start_with(p, Format::Float32, 2, features::offer(&all));
562        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")
563            .expect("headers");
564        assert!(c.features().is_empty());
565    }
566
567    #[test]
568    fn an_answer_with_no_request_line_has_no_feature_line() {
569        let a = Accepted {
570            data_protocol_version: 110,
571            byte_order: LITTLE,
572            reverse_byte_order: false,
573            suppress_subnormals: false,
574            max_buffer_length: 360,
575            max_chunk_length: 0,
576        };
577        assert_eq!(a.to_wire_with(110, "u", None), a.to_wire(110, "u"));
578        assert!(a
579            .to_wire_with(110, "u", Some(&[]))
580            .contains("Labstream-Features: \r\n"));
581    }
582
583    #[test]
584    fn a_full_handshake_reaches_the_streaming_state() {
585        let c = handshake(Format::Float32, 8, LITTLE, 0.0);
586        assert_eq!(c.state(), State::Streaming);
587        let a = c.agreement().expect("an agreement");
588        assert_eq!(a.data_protocol_version, 110);
589        assert_eq!(a.order, ByteOrder::Little);
590    }
591
592    #[test]
593    fn a_slow_client_makes_the_server_swap() {
594        let c = handshake(Format::Double64, 4, BIG, 0.0);
595        assert_eq!(c.agreement().unwrap().order, ByteOrder::Big);
596    }
597
598    #[test]
599    fn a_wrong_uid_in_the_answer_stops_the_feed() {
600        let p = FeedParams::new("uid-1", Format::Float32);
601        let (mut c, _) = FeedClient::start(p, Format::Float32, 1);
602        let answer = "LSL/110 200 OK\r\nUID: another\r\nByte-Order: 1234\r\n\
603                      Suppress-Subnormals: 0\r\nData-Protocol-Version: 110\r\n\r\n";
604        match c.on_headers(answer.as_bytes()) {
605            Err(Error::UidMismatch { actual, .. }) => assert_eq!(actual, "another"),
606            other => panic!("expected a UID mismatch, got {other:?}"),
607        }
608        assert_eq!(c.state(), State::Failed);
609    }
610
611    #[test]
612    fn a_404_answer_stops_the_feed() {
613        let p = FeedParams::new("uid-1", Format::Float32);
614        let (mut c, _) = FeedClient::start(p, Format::Float32, 1);
615        match c.on_headers(b"LSL/110 404 Not found\r\n\r\n") {
616            Err(Error::Status(s)) => assert_eq!(s.code, 404),
617            other => panic!("expected a status error, got {other:?}"),
618        }
619        assert_eq!(c.state(), State::Failed);
620    }
621
622    #[test]
623    fn a_byte_order_of_zero_means_the_native_order() {
624        // The case for liblsl 1.13 and earlier.
625        let p = FeedParams::new("uid-1", Format::Float32);
626        let (mut c, _) = FeedClient::start(p, Format::Float32, 1);
627        let answer = "LSL/110 200 OK\r\nUID: uid-1\r\nByte-Order: 0\r\n\
628                      Suppress-Subnormals: 0\r\nData-Protocol-Version: 110\r\n\r\n";
629        c.on_headers(answer.as_bytes()).expect("headers");
630        assert_eq!(c.agreement().unwrap().order, ByteOrder::native());
631    }
632
633    #[test]
634    fn a_wrong_test_pattern_stops_the_feed() {
635        let p = FeedParams::new("uid-1", Format::Float32);
636        let (mut c, _) = FeedClient::start(p, Format::Float32, 2);
637        let answer = "LSL/110 200 OK\r\nUID: uid-1\r\nByte-Order: 1234\r\n\
638                      Suppress-Subnormals: 0\r\nData-Protocol-Version: 110\r\n\r\n";
639        c.on_headers(answer.as_bytes()).expect("headers");
640
641        // Send the second pattern first. A wrong implementation does this.
642        let codec = *c.codec().unwrap();
643        let mut bytes = Vec::new();
644        for off in [2, 4] {
645            codec
646                .encode(
647                    &labstream_wire::test_pattern(Format::Float32, 2, off),
648                    &mut bytes,
649                )
650                .unwrap();
651        }
652        match c.on_test_pattern(&bytes) {
653            Err(TestPatternError::Mismatch { index, .. }) => assert_eq!(index, 0),
654            other => panic!("expected a mismatch, got {other:?}"),
655        }
656        assert_eq!(c.state(), State::Failed);
657    }
658
659    #[test]
660    fn an_incomplete_buffer_asks_for_more() {
661        let p = FeedParams::new("uid-1", Format::Float32);
662        let (mut c, _) = FeedClient::start(p, Format::Float32, 1);
663        assert_eq!(
664            c.on_headers(b"LSL/110 200 OK\r\nUID: uid-1\r\n"),
665            Err(Error::Incomplete)
666        );
667        assert_eq!(c.state(), State::AwaitingHeaders);
668    }
669}