gel-protocol 0.9.2

Low-level protocol implementation for Gel database client. For applications, use gel-tokio. Formerly published as edgedb-protocol.
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
/*!
([Website reference](https://www.edgedb.com/docs/reference/protocol/messages)) The [ClientMessage] enum and related types.

```rust,ignore
pub enum ClientMessage {
    ClientHandshake(ClientHandshake),
    Parse(Parse),
    Execute1(Execute1),
    UnknownMessage(u8, Bytes),
    AuthenticationSaslInitialResponse(SaslInitialResponse),
    AuthenticationSaslResponse(SaslResponse),
    Dump(Dump),
    Restore(Restore),
    RestoreBlock(RestoreBlock),
    RestoreEof,
    Sync,
    Terminate,
}
```
*/

use std::collections::HashMap;
use std::convert::TryFrom;
use std::sync::Arc;

use bytes::{Buf, BufMut, Bytes};
use snafu::OptionExt;
use uuid::Uuid;

pub use crate::common::CompilationOptions;
pub use crate::common::DumpFlags;
pub use crate::common::{Capabilities, Cardinality, CompilationFlags};
pub use crate::common::{RawTypedesc, State};
use crate::encoding::{encode, Decode, Encode, Input, Output};
use crate::encoding::{Annotations, KeyValues};
use crate::errors::{self, DecodeError, EncodeError};
use crate::new_protocol;

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ClientMessage {
    AuthenticationSaslInitialResponse(SaslInitialResponse),
    AuthenticationSaslResponse(SaslResponse),
    ClientHandshake(ClientHandshake),
    Dump2(Dump2),
    Dump3(Dump3),
    Parse(Parse),
    Execute1(Execute1),
    Restore(Restore),
    RestoreBlock(RestoreBlock),
    RestoreEof,
    Sync,
    Terminate,
    UnknownMessage(u8, Bytes),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SaslInitialResponse {
    pub method: String,
    pub data: Bytes,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SaslResponse {
    pub data: Bytes,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientHandshake {
    pub major_ver: u16,
    pub minor_ver: u16,
    pub params: HashMap<String, String>,
    pub extensions: HashMap<String, Annotations>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Parse {
    pub annotations: Option<Arc<Annotations>>,
    pub allowed_capabilities: Capabilities,
    pub compilation_flags: CompilationFlags,
    pub implicit_limit: Option<u64>,
    pub output_format: IoFormat,
    pub expected_cardinality: Cardinality,
    pub command_text: String,
    pub state: State,
    pub input_language: InputLanguage,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Execute1 {
    pub annotations: Option<Arc<Annotations>>,
    pub allowed_capabilities: Capabilities,
    pub compilation_flags: CompilationFlags,
    pub implicit_limit: Option<u64>,
    pub output_format: IoFormat,
    pub expected_cardinality: Cardinality,
    pub command_text: String,
    pub state: State,
    pub input_typedesc_id: Uuid,
    pub output_typedesc_id: Uuid,
    pub arguments: Bytes,
    pub input_language: InputLanguage,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dump2 {
    pub headers: KeyValues,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dump3 {
    pub annotations: Option<Arc<Annotations>>,
    pub flags: DumpFlags,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Restore {
    pub headers: KeyValues,
    pub jobs: u16,
    pub data: Bytes,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RestoreBlock {
    pub data: Bytes,
}

pub use crate::new_protocol::{InputLanguage, IoFormat};

struct Empty;
impl ClientMessage {
    pub fn encode(&self, buf: &mut Output) -> Result<(), EncodeError> {
        use ClientMessage::*;
        match self {
            ClientHandshake(h) => encode(buf, 0x56, h),
            AuthenticationSaslInitialResponse(h) => encode(buf, 0x70, h),
            AuthenticationSaslResponse(h) => encode(buf, 0x72, h),
            Parse(h) => encode(buf, 0x50, h),
            Execute1(h) => encode(buf, 0x4f, h),
            Dump2(h) => encode(buf, 0x3e, h),
            Dump3(h) => encode(buf, 0x3e, h),
            Restore(h) => encode(buf, 0x3c, h),
            RestoreBlock(h) => encode(buf, 0x3d, h),
            RestoreEof => encode(buf, 0x2e, &Empty),
            Sync => encode(buf, 0x53, &Empty),
            Terminate => encode(buf, 0x58, &Empty),

            UnknownMessage(_, _) => errors::UnknownMessageCantBeEncoded.fail()?,
        }
    }
    /// Decode exactly one frame from the buffer.
    ///
    /// This expects a full frame to already be in the buffer. It can return
    /// an arbitrary error or be silent if a message is only partially present
    /// in the buffer or if extra data is present.
    pub fn decode(buf: &mut Input) -> Result<ClientMessage, DecodeError> {
        let message = new_protocol::Message::new(buf)?;
        let mut next = buf.slice(..message.mlen() + 1);
        buf.advance(message.mlen() + 1);
        let buf = &mut next;

        use self::ClientMessage as M;
        let result = match buf[0] {
            0x56 => ClientHandshake::decode(buf).map(M::ClientHandshake)?,
            0x70 => SaslInitialResponse::decode(buf).map(M::AuthenticationSaslInitialResponse)?,
            0x72 => SaslResponse::decode(buf).map(M::AuthenticationSaslResponse)?,
            0x50 => Parse::decode(buf).map(M::Parse)?,
            0x4f => Execute1::decode(buf).map(M::Execute1)?,
            0x3e => {
                if buf.proto().is_3() {
                    Dump3::decode(buf).map(M::Dump3)?
                } else {
                    Dump2::decode(buf).map(M::Dump2)?
                }
            }
            0x3c => Restore::decode(buf).map(M::Restore)?,
            0x3d => RestoreBlock::decode(buf).map(M::RestoreBlock)?,
            0x2e => M::RestoreEof,
            0x53 => M::Sync,
            0x58 => M::Terminate,
            code => M::UnknownMessage(code, buf.copy_to_bytes(buf.remaining())),
        };
        Ok(result)
    }
}

impl Encode for Empty {
    fn encode(&self, _buf: &mut Output) -> Result<(), EncodeError> {
        Ok(())
    }
}

impl Encode for ClientHandshake {
    fn encode(&self, buf: &mut Output) -> Result<(), EncodeError> {
        buf.reserve(8);
        buf.put_u16(self.major_ver);
        buf.put_u16(self.minor_ver);
        buf.put_u16(
            u16::try_from(self.params.len())
                .ok()
                .context(errors::TooManyParams)?,
        );
        for (k, v) in &self.params {
            k.encode(buf)?;
            v.encode(buf)?;
        }
        buf.reserve(2);
        buf.put_u16(
            u16::try_from(self.extensions.len())
                .ok()
                .context(errors::TooManyExtensions)?,
        );
        for (name, headers) in &self.extensions {
            String::encode(name, buf)?;
            buf.reserve(2);
            buf.put_u16(
                u16::try_from(headers.len())
                    .ok()
                    .context(errors::TooManyHeaders)?,
            );
            for (name, value) in headers {
                String::encode(name, buf)?;
                String::encode(value, buf)?;
            }
        }
        Ok(())
    }
}

impl Decode for ClientHandshake {
    fn decode(buf: &mut Input) -> Result<Self, DecodeError> {
        let message = new_protocol::ClientHandshake::new(buf)?;
        let mut params = HashMap::new();
        for param in message.params() {
            params.insert(
                param.name().to_string_lossy().to_string(),
                param.value().to_string_lossy().to_string(),
            );
        }

        let mut extensions = HashMap::new();
        for ext in message.extensions() {
            let mut headers = HashMap::new();
            for ann in ext.annotations() {
                headers.insert(
                    ann.name().to_string_lossy().to_string(),
                    ann.value().to_string_lossy().to_string(),
                );
            }
            extensions.insert(ext.name().to_string_lossy().to_string(), headers);
        }

        let decoded = ClientHandshake {
            major_ver: message.major_ver(),
            minor_ver: message.minor_ver(),
            params,
            extensions,
        };
        buf.advance(message.as_ref().len());
        Ok(decoded)
    }
}

impl Encode for SaslInitialResponse {
    fn encode(&self, buf: &mut Output) -> Result<(), EncodeError> {
        self.method.encode(buf)?;
        self.data.encode(buf)?;
        Ok(())
    }
}

impl Decode for SaslInitialResponse {
    fn decode(buf: &mut Input) -> Result<SaslInitialResponse, DecodeError> {
        let message = new_protocol::AuthenticationSASLInitialResponse::new(buf)?;
        let decoded = SaslInitialResponse {
            method: message.method().to_string_lossy().to_string(),
            data: message.sasl_data().into_slice().to_owned().into(),
        };
        buf.advance(message.as_ref().len());
        Ok(decoded)
    }
}

impl Encode for SaslResponse {
    fn encode(&self, buf: &mut Output) -> Result<(), EncodeError> {
        self.data.encode(buf)?;
        Ok(())
    }
}

impl Decode for SaslResponse {
    fn decode(buf: &mut Input) -> Result<SaslResponse, DecodeError> {
        let message = new_protocol::AuthenticationSASLResponse::new(buf)?;
        let decoded = SaslResponse {
            data: message.sasl_data().into_slice().to_owned().into(),
        };
        buf.advance(message.as_ref().len());
        Ok(decoded)
    }
}

impl Encode for Execute1 {
    fn encode(&self, buf: &mut Output) -> Result<(), EncodeError> {
        buf.reserve(2 + 3 * 8 + 1 + 1 + 4 + 16 + 4 + 16 + 16 + 4);
        if let Some(annotations) = self.annotations.as_deref() {
            buf.put_u16(
                u16::try_from(annotations.len())
                    .ok()
                    .context(errors::TooManyHeaders)?,
            );
            for (name, value) in annotations {
                buf.reserve(4);
                name.encode(buf)?;
                value.encode(buf)?;
            }
        } else {
            buf.put_u16(0);
        }
        buf.reserve(3 * 8 + 1 + 1 + 4 + 16 + 4 + 16 + 16 + 4);
        buf.put_u64(self.allowed_capabilities.bits());
        buf.put_u64(self.compilation_flags.bits());
        buf.put_u64(self.implicit_limit.unwrap_or(0));
        if buf.proto().is_multilingual() {
            buf.put_u8(self.input_language as u8);
        }
        buf.put_u8(self.output_format as u8);
        buf.put_u8(self.expected_cardinality as u8);
        self.command_text.encode(buf)?;
        self.state.typedesc_id.encode(buf)?;
        self.state.data.encode(buf)?;
        self.input_typedesc_id.encode(buf)?;
        self.output_typedesc_id.encode(buf)?;
        self.arguments.encode(buf)?;
        Ok(())
    }
}

impl Decode for Execute1 {
    fn decode(buf: &mut Input) -> Result<Self, DecodeError> {
        if buf.proto().is_multilingual() {
            let message = new_protocol::Execute::new(buf)?;

            // Convert annotations
            let annotations = if !message.annotations().is_empty() {
                let mut ann_map = HashMap::new();
                for ann in message.annotations() {
                    ann_map.insert(
                        ann.name().to_string_lossy().to_string(),
                        ann.value().to_string_lossy().to_string(),
                    );
                }
                Some(Arc::new(ann_map))
            } else {
                None
            };

            // Convert state
            let state = State {
                typedesc_id: message.state_typedesc_id(),
                data: message.state_data().into_slice().to_owned().into(),
            };

            let decoded = Execute1 {
                annotations,
                allowed_capabilities: Capabilities::from_bits_retain(
                    message.allowed_capabilities(),
                ),
                compilation_flags: decode_compilation_flags(message.compilation_flags())?,
                implicit_limit: match message.implicit_limit() {
                    0 => None,
                    val => Some(val),
                },
                output_format: message.output_format(),
                expected_cardinality: TryFrom::try_from(message.expected_cardinality())?,
                command_text: message.command_text().to_string_lossy().to_string(),
                state,
                input_typedesc_id: message.input_typedesc_id(),
                output_typedesc_id: message.output_typedesc_id(),
                arguments: message.arguments().into_slice().to_owned().into(),
                input_language: message.input_language(),
            };
            buf.advance(message.as_ref().len());
            Ok(decoded)
        } else {
            let message = new_protocol::Execute2::new(buf)?;

            // Convert annotations
            let annotations = if !message.annotations().is_empty() {
                let mut ann_map = HashMap::new();
                for ann in message.annotations() {
                    ann_map.insert(
                        ann.name().to_string_lossy().to_string(),
                        ann.value().to_string_lossy().to_string(),
                    );
                }
                Some(Arc::new(ann_map))
            } else {
                None
            };

            // Convert state
            let state = State {
                typedesc_id: message.state_typedesc_id(),
                data: message.state_data().into_slice().to_owned().into(),
            };

            let decoded = Execute1 {
                annotations,
                allowed_capabilities: decode_capabilities(message.allowed_capabilities())?,
                compilation_flags: decode_compilation_flags(message.compilation_flags())?,
                implicit_limit: match message.implicit_limit() {
                    0 => None,
                    val => Some(val),
                },
                output_format: message.output_format(),
                expected_cardinality: TryFrom::try_from(message.expected_cardinality())?,
                command_text: message.command_text().to_string_lossy().to_string(),
                state,
                input_typedesc_id: message.input_typedesc_id(),
                output_typedesc_id: message.output_typedesc_id(),
                arguments: message.arguments().into_slice().to_owned().into(),
                input_language: InputLanguage::EdgeQL,
            };
            buf.advance(message.as_ref().len());
            Ok(decoded)
        }
    }
}

impl Encode for Dump2 {
    fn encode(&self, buf: &mut Output) -> Result<(), EncodeError> {
        buf.reserve(10);
        buf.put_u16(
            u16::try_from(self.headers.len())
                .ok()
                .context(errors::TooManyHeaders)?,
        );
        for (&name, value) in &self.headers {
            buf.reserve(2);
            buf.put_u16(name);
            value.encode(buf)?;
        }
        Ok(())
    }
}

impl Decode for Dump2 {
    fn decode(buf: &mut Input) -> Result<Self, DecodeError> {
        let message = new_protocol::Dump2::new(buf)?;
        let mut headers = HashMap::new();
        for header in message.headers() {
            headers.insert(header.code(), header.value().into_slice().to_owned().into());
        }

        let decoded = Dump2 { headers };
        buf.advance(message.as_ref().len());
        Ok(decoded)
    }
}

impl Encode for Dump3 {
    fn encode(&self, buf: &mut Output) -> Result<(), EncodeError> {
        buf.reserve(2 + 8);
        if let Some(annotations) = self.annotations.as_deref() {
            buf.put_u16(
                u16::try_from(annotations.len())
                    .ok()
                    .context(errors::TooManyHeaders)?,
            );
            for (name, value) in annotations {
                buf.reserve(4);
                name.encode(buf)?;
                value.encode(buf)?;
            }
        } else {
            buf.put_u16(0);
        }
        buf.put_u64(self.flags.bits());
        Ok(())
    }
}

impl Decode for Dump3 {
    fn decode(buf: &mut Input) -> Result<Self, DecodeError> {
        let message = new_protocol::Dump3::new(buf)?;
        let mut annotations = HashMap::new();
        for ann in message.annotations() {
            annotations.insert(
                ann.name().to_string_lossy().to_string(),
                ann.value().to_string_lossy().to_string(),
            );
        }

        let decoded = Dump3 {
            annotations: Some(Arc::new(annotations)),
            flags: decode_dump_flags(message.flags())?,
        };
        buf.advance(message.as_ref().len());
        Ok(decoded)
    }
}

impl Encode for Restore {
    fn encode(&self, buf: &mut Output) -> Result<(), EncodeError> {
        buf.reserve(4 + self.data.len());
        buf.put_u16(
            u16::try_from(self.headers.len())
                .ok()
                .context(errors::TooManyHeaders)?,
        );
        for (&name, value) in &self.headers {
            buf.reserve(2);
            buf.put_u16(name);
            value.encode(buf)?;
        }
        buf.put_u16(self.jobs);
        buf.extend(&self.data);
        Ok(())
    }
}

impl Decode for Restore {
    fn decode(buf: &mut Input) -> Result<Self, DecodeError> {
        let message = new_protocol::Restore::new(buf)?;
        let mut headers = HashMap::new();
        for header in message.headers() {
            headers.insert(header.code(), header.value().into_slice().to_owned().into());
        }

        let decoded = Restore {
            headers,
            jobs: message.jobs(),
            data: message.data().as_ref().to_owned().into(),
        };
        buf.advance(message.as_ref().len());
        Ok(decoded)
    }
}

impl Encode for RestoreBlock {
    fn encode(&self, buf: &mut Output) -> Result<(), EncodeError> {
        buf.extend(&self.data);
        Ok(())
    }
}

impl Decode for RestoreBlock {
    fn decode(buf: &mut Input) -> Result<Self, DecodeError> {
        let message = new_protocol::RestoreBlock::new(buf)?;
        let decoded = RestoreBlock {
            data: message.block_data().into_slice().to_owned().into(),
        };
        buf.advance(message.as_ref().len());
        Ok(decoded)
    }
}

impl Parse {
    pub fn new(
        opts: &CompilationOptions,
        query: &str,
        state: State,
        annotations: Option<Arc<Annotations>>,
    ) -> Parse {
        Parse {
            annotations,
            allowed_capabilities: opts.allow_capabilities,
            compilation_flags: opts.flags(),
            implicit_limit: opts.implicit_limit,
            output_format: opts.io_format,
            expected_cardinality: opts.expected_cardinality,
            command_text: query.into(),
            state,
            input_language: opts.input_language,
        }
    }
}

fn decode_capabilities(val: u64) -> Result<Capabilities, DecodeError> {
    Capabilities::from_bits(val)
        .ok_or_else(|| errors::InvalidCapabilities { capabilities: val }.build())
}

fn decode_compilation_flags(val: u64) -> Result<CompilationFlags, DecodeError> {
    CompilationFlags::from_bits(val).ok_or_else(|| {
        errors::InvalidCompilationFlags {
            compilation_flags: val,
        }
        .build()
    })
}

fn decode_dump_flags(val: u64) -> Result<DumpFlags, DecodeError> {
    DumpFlags::from_bits(val).ok_or_else(|| errors::InvalidDumpFlags { dump_flags: val }.build())
}

impl Decode for Parse {
    fn decode(buf: &mut Input) -> Result<Self, DecodeError> {
        if buf.proto().is_multilingual() {
            let message = new_protocol::Parse::new(buf)?;

            // Convert annotations
            let annotations = if !message.annotations().is_empty() {
                let mut ann_map = HashMap::new();
                for ann in message.annotations() {
                    ann_map.insert(
                        ann.name().to_string_lossy().to_string(),
                        ann.value().to_string_lossy().to_string(),
                    );
                }
                Some(Arc::new(ann_map))
            } else {
                None
            };

            // Convert state
            let state = State {
                typedesc_id: message.state_typedesc_id(),
                data: message.state_data().into_slice().to_owned().into(),
            };

            let decoded = Parse {
                annotations,
                allowed_capabilities: decode_capabilities(message.allowed_capabilities())?,
                compilation_flags: decode_compilation_flags(message.compilation_flags())?,
                implicit_limit: match message.implicit_limit() {
                    0 => None,
                    val => Some(val),
                },
                output_format: message.output_format(),
                expected_cardinality: TryFrom::try_from(message.expected_cardinality())?,
                command_text: message.command_text().to_string_lossy().to_string(),
                state,
                input_language: message.input_language(),
            };
            buf.advance(message.as_ref().len());
            Ok(decoded)
        } else {
            let message = new_protocol::Parse2::new(buf)?;

            // Convert annotations
            let annotations = if !message.annotations().is_empty() {
                let mut ann_map = HashMap::new();
                for ann in message.annotations() {
                    ann_map.insert(
                        ann.name().to_string_lossy().to_string(),
                        ann.value().to_string_lossy().to_string(),
                    );
                }
                Some(Arc::new(ann_map))
            } else {
                None
            };

            // Convert state
            let state = State {
                typedesc_id: message.state_typedesc_id(),
                data: message.state_data().into_slice().to_owned().into(),
            };

            let decoded = Parse {
                annotations,
                allowed_capabilities: decode_capabilities(message.allowed_capabilities())?,
                compilation_flags: decode_compilation_flags(message.compilation_flags())?,
                implicit_limit: match message.implicit_limit() {
                    0 => None,
                    val => Some(val),
                },
                output_format: message.output_format(),
                expected_cardinality: TryFrom::try_from(message.expected_cardinality())?,
                command_text: message.command_text().to_string_lossy().to_string(),
                state,
                input_language: InputLanguage::EdgeQL, // Default for non-multilingual
            };
            buf.advance(message.as_ref().len());
            Ok(decoded)
        }
    }
}

impl Encode for Parse {
    fn encode(&self, buf: &mut Output) -> Result<(), EncodeError> {
        buf.reserve(52);
        if let Some(annotations) = self.annotations.as_deref() {
            buf.put_u16(
                u16::try_from(annotations.len())
                    .ok()
                    .context(errors::TooManyHeaders)?,
            );
            for (name, value) in annotations {
                buf.reserve(8);
                name.encode(buf)?;
                value.encode(buf)?;
            }
        } else {
            buf.put_u16(0);
        }
        buf.reserve(50);
        buf.put_u64(self.allowed_capabilities.bits());
        buf.put_u64(self.compilation_flags.bits());
        buf.put_u64(self.implicit_limit.unwrap_or(0));
        if buf.proto().is_multilingual() {
            buf.put_u8(self.input_language as u8);
        }
        buf.put_u8(self.output_format as u8);
        buf.put_u8(self.expected_cardinality as u8);
        self.command_text.encode(buf)?;
        self.state.typedesc_id.encode(buf)?;
        self.state.data.encode(buf)?;
        Ok(())
    }
}