1use std::convert::{From, TryFrom};
61use std::fmt;
62use std::fmt::{Display, Formatter};
63
64use crate::transport::{TReadTransport, TWriteTransport};
65use crate::{ProtocolError, ProtocolErrorKind};
66
67#[cfg(test)]
68macro_rules! assert_eq_written_bytes {
69 ($o_prot:ident, $expected_bytes:ident) => {{
70 assert_eq!($o_prot.transport.write_bytes(), &$expected_bytes);
71 }};
72}
73
74#[cfg(test)]
76macro_rules! copy_write_buffer_to_read_buffer {
77 ($o_prot:ident) => {{
78 $o_prot.transport.copy_write_buffer_to_read_buffer();
79 }};
80}
81
82#[cfg(test)]
83macro_rules! set_readable_bytes {
84 ($i_prot:ident, $bytes:expr) => {
85 $i_prot.transport.set_readable_bytes($bytes);
86 };
87}
88
89mod binary;
90mod compact;
91mod multiplexed;
92mod stored;
93
94pub use self::binary::{
95 TBinaryInputProtocol, TBinaryInputProtocolFactory, TBinaryOutputProtocol,
96 TBinaryOutputProtocolFactory,
97};
98pub use self::compact::{
99 TCompactInputProtocol, TCompactInputProtocolFactory, TCompactOutputProtocol,
100 TCompactOutputProtocolFactory,
101};
102pub use self::multiplexed::TMultiplexedOutputProtocol;
103pub use self::stored::TStoredInputProtocol;
104
105const MAXIMUM_SKIP_DEPTH: i8 = 64;
110
111pub trait TInputProtocol {
140 fn read_message_begin(&mut self) -> crate::Result<TMessageIdentifier>;
142 fn read_message_end(&mut self) -> crate::Result<()>;
144 fn read_struct_begin(&mut self) -> crate::Result<Option<TStructIdentifier>>;
146 fn read_struct_end(&mut self) -> crate::Result<()>;
148 fn read_field_begin(&mut self) -> crate::Result<TFieldIdentifier>;
150 fn read_field_end(&mut self) -> crate::Result<()>;
152 fn read_bool(&mut self) -> crate::Result<bool>;
154 fn read_bytes(&mut self) -> crate::Result<Vec<u8>>;
156 fn read_i8(&mut self) -> crate::Result<i8>;
158 fn read_i16(&mut self) -> crate::Result<i16>;
160 fn read_i32(&mut self) -> crate::Result<i32>;
162 fn read_i64(&mut self) -> crate::Result<i64>;
164 fn read_double(&mut self) -> crate::Result<f64>;
166 fn read_string(&mut self) -> crate::Result<String>;
168 fn read_list_begin(&mut self) -> crate::Result<TListIdentifier>;
170 fn read_list_end(&mut self) -> crate::Result<()>;
172 fn read_set_begin(&mut self) -> crate::Result<TSetIdentifier>;
174 fn read_set_end(&mut self) -> crate::Result<()>;
176 fn read_map_begin(&mut self) -> crate::Result<TMapIdentifier>;
178 fn read_map_end(&mut self) -> crate::Result<()>;
180 fn skip(&mut self, field_type: TType) -> crate::Result<()> {
183 self.skip_till_depth(field_type, MAXIMUM_SKIP_DEPTH)
184 }
185 fn skip_till_depth(&mut self, field_type: TType, depth: i8) -> crate::Result<()> {
187 if depth == 0 {
188 return Err(crate::Error::Protocol(ProtocolError {
189 kind: ProtocolErrorKind::DepthLimit,
190 message: format!("cannot parse past {:?}", field_type),
191 }));
192 }
193
194 match field_type {
195 TType::Bool => self.read_bool().map(|_| ()),
196 TType::I08 => self.read_i8().map(|_| ()),
197 TType::I16 => self.read_i16().map(|_| ()),
198 TType::I32 => self.read_i32().map(|_| ()),
199 TType::I64 => self.read_i64().map(|_| ()),
200 TType::Double => self.read_double().map(|_| ()),
201 TType::String => self.read_string().map(|_| ()),
202 TType::Struct => {
203 self.read_struct_begin()?;
204 loop {
205 let field_ident = self.read_field_begin()?;
206 if field_ident.field_type == TType::Stop {
207 break;
208 }
209 self.skip_till_depth(field_ident.field_type, depth - 1)?;
210 }
211 self.read_struct_end()
212 }
213 TType::List => {
214 let list_ident = self.read_list_begin()?;
215 for _ in 0..list_ident.size {
216 self.skip_till_depth(list_ident.element_type, depth - 1)?;
217 }
218 self.read_list_end()
219 }
220 TType::Set => {
221 let set_ident = self.read_set_begin()?;
222 for _ in 0..set_ident.size {
223 self.skip_till_depth(set_ident.element_type, depth - 1)?;
224 }
225 self.read_set_end()
226 }
227 TType::Map => {
228 let map_ident = self.read_map_begin()?;
229 for _ in 0..map_ident.size {
230 let key_type = map_ident
231 .key_type
232 .expect("non-zero sized map should contain key type");
233 let val_type = map_ident
234 .value_type
235 .expect("non-zero sized map should contain value type");
236 self.skip_till_depth(key_type, depth - 1)?;
237 self.skip_till_depth(val_type, depth - 1)?;
238 }
239 self.read_map_end()
240 }
241 u => Err(crate::Error::Protocol(ProtocolError {
242 kind: ProtocolErrorKind::Unknown,
243 message: format!("cannot skip field type {:?}", &u),
244 })),
245 }
246 }
247
248 fn read_byte(&mut self) -> crate::Result<u8>;
255}
256
257pub trait TOutputProtocol {
289 fn write_message_begin(&mut self, identifier: &TMessageIdentifier) -> crate::Result<()>;
291 fn write_message_end(&mut self) -> crate::Result<()>;
293 fn write_struct_begin(&mut self, identifier: &TStructIdentifier) -> crate::Result<()>;
295 fn write_struct_end(&mut self) -> crate::Result<()>;
297 fn write_field_begin(&mut self, identifier: &TFieldIdentifier) -> crate::Result<()>;
299 fn write_field_end(&mut self) -> crate::Result<()>;
301 fn write_field_stop(&mut self) -> crate::Result<()>;
304 fn write_bool(&mut self, b: bool) -> crate::Result<()>;
306 fn write_bytes(&mut self, b: &[u8]) -> crate::Result<()>;
308 fn write_i8(&mut self, i: i8) -> crate::Result<()>;
310 fn write_i16(&mut self, i: i16) -> crate::Result<()>;
312 fn write_i32(&mut self, i: i32) -> crate::Result<()>;
314 fn write_i64(&mut self, i: i64) -> crate::Result<()>;
316 fn write_double(&mut self, d: f64) -> crate::Result<()>;
318 fn write_string(&mut self, s: &str) -> crate::Result<()>;
320 fn write_list_begin(&mut self, identifier: &TListIdentifier) -> crate::Result<()>;
322 fn write_list_end(&mut self) -> crate::Result<()>;
324 fn write_set_begin(&mut self, identifier: &TSetIdentifier) -> crate::Result<()>;
326 fn write_set_end(&mut self) -> crate::Result<()>;
328 fn write_map_begin(&mut self, identifier: &TMapIdentifier) -> crate::Result<()>;
330 fn write_map_end(&mut self) -> crate::Result<()>;
332 fn flush(&mut self) -> crate::Result<()>;
334
335 fn write_byte(&mut self, b: u8) -> crate::Result<()>; }
343
344impl<P> TInputProtocol for Box<P>
345where
346 P: TInputProtocol + ?Sized,
347{
348 fn read_message_begin(&mut self) -> crate::Result<TMessageIdentifier> {
349 (**self).read_message_begin()
350 }
351
352 fn read_message_end(&mut self) -> crate::Result<()> {
353 (**self).read_message_end()
354 }
355
356 fn read_struct_begin(&mut self) -> crate::Result<Option<TStructIdentifier>> {
357 (**self).read_struct_begin()
358 }
359
360 fn read_struct_end(&mut self) -> crate::Result<()> {
361 (**self).read_struct_end()
362 }
363
364 fn read_field_begin(&mut self) -> crate::Result<TFieldIdentifier> {
365 (**self).read_field_begin()
366 }
367
368 fn read_field_end(&mut self) -> crate::Result<()> {
369 (**self).read_field_end()
370 }
371
372 fn read_bool(&mut self) -> crate::Result<bool> {
373 (**self).read_bool()
374 }
375
376 fn read_bytes(&mut self) -> crate::Result<Vec<u8>> {
377 (**self).read_bytes()
378 }
379
380 fn read_i8(&mut self) -> crate::Result<i8> {
381 (**self).read_i8()
382 }
383
384 fn read_i16(&mut self) -> crate::Result<i16> {
385 (**self).read_i16()
386 }
387
388 fn read_i32(&mut self) -> crate::Result<i32> {
389 (**self).read_i32()
390 }
391
392 fn read_i64(&mut self) -> crate::Result<i64> {
393 (**self).read_i64()
394 }
395
396 fn read_double(&mut self) -> crate::Result<f64> {
397 (**self).read_double()
398 }
399
400 fn read_string(&mut self) -> crate::Result<String> {
401 (**self).read_string()
402 }
403
404 fn read_list_begin(&mut self) -> crate::Result<TListIdentifier> {
405 (**self).read_list_begin()
406 }
407
408 fn read_list_end(&mut self) -> crate::Result<()> {
409 (**self).read_list_end()
410 }
411
412 fn read_set_begin(&mut self) -> crate::Result<TSetIdentifier> {
413 (**self).read_set_begin()
414 }
415
416 fn read_set_end(&mut self) -> crate::Result<()> {
417 (**self).read_set_end()
418 }
419
420 fn read_map_begin(&mut self) -> crate::Result<TMapIdentifier> {
421 (**self).read_map_begin()
422 }
423
424 fn read_map_end(&mut self) -> crate::Result<()> {
425 (**self).read_map_end()
426 }
427
428 fn read_byte(&mut self) -> crate::Result<u8> {
429 (**self).read_byte()
430 }
431}
432
433impl<P> TOutputProtocol for Box<P>
434where
435 P: TOutputProtocol + ?Sized,
436{
437 fn write_message_begin(&mut self, identifier: &TMessageIdentifier) -> crate::Result<()> {
438 (**self).write_message_begin(identifier)
439 }
440
441 fn write_message_end(&mut self) -> crate::Result<()> {
442 (**self).write_message_end()
443 }
444
445 fn write_struct_begin(&mut self, identifier: &TStructIdentifier) -> crate::Result<()> {
446 (**self).write_struct_begin(identifier)
447 }
448
449 fn write_struct_end(&mut self) -> crate::Result<()> {
450 (**self).write_struct_end()
451 }
452
453 fn write_field_begin(&mut self, identifier: &TFieldIdentifier) -> crate::Result<()> {
454 (**self).write_field_begin(identifier)
455 }
456
457 fn write_field_end(&mut self) -> crate::Result<()> {
458 (**self).write_field_end()
459 }
460
461 fn write_field_stop(&mut self) -> crate::Result<()> {
462 (**self).write_field_stop()
463 }
464
465 fn write_bool(&mut self, b: bool) -> crate::Result<()> {
466 (**self).write_bool(b)
467 }
468
469 fn write_bytes(&mut self, b: &[u8]) -> crate::Result<()> {
470 (**self).write_bytes(b)
471 }
472
473 fn write_i8(&mut self, i: i8) -> crate::Result<()> {
474 (**self).write_i8(i)
475 }
476
477 fn write_i16(&mut self, i: i16) -> crate::Result<()> {
478 (**self).write_i16(i)
479 }
480
481 fn write_i32(&mut self, i: i32) -> crate::Result<()> {
482 (**self).write_i32(i)
483 }
484
485 fn write_i64(&mut self, i: i64) -> crate::Result<()> {
486 (**self).write_i64(i)
487 }
488
489 fn write_double(&mut self, d: f64) -> crate::Result<()> {
490 (**self).write_double(d)
491 }
492
493 fn write_string(&mut self, s: &str) -> crate::Result<()> {
494 (**self).write_string(s)
495 }
496
497 fn write_list_begin(&mut self, identifier: &TListIdentifier) -> crate::Result<()> {
498 (**self).write_list_begin(identifier)
499 }
500
501 fn write_list_end(&mut self) -> crate::Result<()> {
502 (**self).write_list_end()
503 }
504
505 fn write_set_begin(&mut self, identifier: &TSetIdentifier) -> crate::Result<()> {
506 (**self).write_set_begin(identifier)
507 }
508
509 fn write_set_end(&mut self) -> crate::Result<()> {
510 (**self).write_set_end()
511 }
512
513 fn write_map_begin(&mut self, identifier: &TMapIdentifier) -> crate::Result<()> {
514 (**self).write_map_begin(identifier)
515 }
516
517 fn write_map_end(&mut self) -> crate::Result<()> {
518 (**self).write_map_end()
519 }
520
521 fn flush(&mut self) -> crate::Result<()> {
522 (**self).flush()
523 }
524
525 fn write_byte(&mut self, b: u8) -> crate::Result<()> {
526 (**self).write_byte(b)
527 }
528}
529
530pub trait TInputProtocolFactory {
548 fn create(&self, transport: Box<dyn TReadTransport + Send>) -> Box<dyn TInputProtocol + Send>;
550}
551
552impl<T> TInputProtocolFactory for Box<T>
553where
554 T: TInputProtocolFactory + ?Sized,
555{
556 fn create(&self, transport: Box<dyn TReadTransport + Send>) -> Box<dyn TInputProtocol + Send> {
557 (**self).create(transport)
558 }
559}
560
561pub trait TOutputProtocolFactory {
579 fn create(&self, transport: Box<dyn TWriteTransport + Send>)
581 -> Box<dyn TOutputProtocol + Send>;
582}
583
584impl<T> TOutputProtocolFactory for Box<T>
585where
586 T: TOutputProtocolFactory + ?Sized,
587{
588 fn create(
589 &self,
590 transport: Box<dyn TWriteTransport + Send>,
591 ) -> Box<dyn TOutputProtocol + Send> {
592 (**self).create(transport)
593 }
594}
595
596#[derive(Clone, Debug, Eq, PartialEq)]
598pub struct TMessageIdentifier {
599 pub name: String,
601 pub message_type: TMessageType,
603 pub sequence_number: i32,
605}
606
607impl TMessageIdentifier {
608 pub fn new<S: Into<String>>(
611 name: S,
612 message_type: TMessageType,
613 sequence_number: i32,
614 ) -> TMessageIdentifier {
615 TMessageIdentifier {
616 name: name.into(),
617 message_type,
618 sequence_number,
619 }
620 }
621}
622
623#[derive(Clone, Debug, Eq, PartialEq)]
625pub struct TStructIdentifier {
626 pub name: String,
628}
629
630impl TStructIdentifier {
631 pub fn new<S: Into<String>>(name: S) -> TStructIdentifier {
633 TStructIdentifier { name: name.into() }
634 }
635}
636
637#[derive(Clone, Debug, Eq, PartialEq)]
639pub struct TFieldIdentifier {
640 pub name: Option<String>,
644 pub field_type: TType,
648 pub id: Option<i16>,
652}
653
654impl TFieldIdentifier {
655 pub fn new<N, S, I>(name: N, field_type: TType, id: I) -> TFieldIdentifier
660 where
661 N: Into<Option<S>>,
662 S: Into<String>,
663 I: Into<Option<i16>>,
664 {
665 TFieldIdentifier {
666 name: name.into().map(|n| n.into()),
667 field_type,
668 id: id.into(),
669 }
670 }
671}
672
673#[derive(Clone, Debug, Eq, PartialEq)]
675pub struct TListIdentifier {
676 pub element_type: TType,
678 pub size: i32,
680}
681
682impl TListIdentifier {
683 pub fn new(element_type: TType, size: i32) -> TListIdentifier {
686 TListIdentifier { element_type, size }
687 }
688}
689
690#[derive(Clone, Debug, Eq, PartialEq)]
692pub struct TSetIdentifier {
693 pub element_type: TType,
695 pub size: i32,
697}
698
699impl TSetIdentifier {
700 pub fn new(element_type: TType, size: i32) -> TSetIdentifier {
703 TSetIdentifier { element_type, size }
704 }
705}
706
707#[derive(Clone, Debug, Eq, PartialEq)]
709pub struct TMapIdentifier {
710 pub key_type: Option<TType>,
712 pub value_type: Option<TType>,
714 pub size: i32,
716}
717
718impl TMapIdentifier {
719 pub fn new<K, V>(key_type: K, value_type: V, size: i32) -> TMapIdentifier
722 where
723 K: Into<Option<TType>>,
724 V: Into<Option<TType>>,
725 {
726 TMapIdentifier {
727 key_type: key_type.into(),
728 value_type: value_type.into(),
729 size,
730 }
731 }
732}
733
734#[derive(Clone, Copy, Debug, Eq, PartialEq)]
736pub enum TMessageType {
737 Call,
739 Reply,
741 Exception,
743 OneWay,
745}
746
747impl Display for TMessageType {
748 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
749 match *self {
750 TMessageType::Call => write!(f, "Call"),
751 TMessageType::Reply => write!(f, "Reply"),
752 TMessageType::Exception => write!(f, "Exception"),
753 TMessageType::OneWay => write!(f, "OneWay"),
754 }
755 }
756}
757
758impl From<TMessageType> for u8 {
759 fn from(message_type: TMessageType) -> Self {
760 match message_type {
761 TMessageType::Call => 0x01,
762 TMessageType::Reply => 0x02,
763 TMessageType::Exception => 0x03,
764 TMessageType::OneWay => 0x04,
765 }
766 }
767}
768
769impl TryFrom<u8> for TMessageType {
770 type Error = crate::Error;
771 fn try_from(b: u8) -> Result<Self, Self::Error> {
772 match b {
773 0x01 => Ok(TMessageType::Call),
774 0x02 => Ok(TMessageType::Reply),
775 0x03 => Ok(TMessageType::Exception),
776 0x04 => Ok(TMessageType::OneWay),
777 unkn => Err(crate::Error::Protocol(ProtocolError {
778 kind: ProtocolErrorKind::InvalidData,
779 message: format!("cannot convert {} to TMessageType", unkn),
780 })),
781 }
782 }
783}
784
785#[derive(Clone, Copy, Debug, Eq, PartialEq)]
787pub enum TType {
788 Stop,
790 Void,
792 Bool,
794 I08,
796 Double,
798 I16,
800 I32,
802 I64,
804 String,
806 Utf7,
808 Struct,
810 Map,
812 Set,
814 List,
816 Utf8,
818 Utf16,
820}
821
822impl Display for TType {
823 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
824 match *self {
825 TType::Stop => write!(f, "STOP"),
826 TType::Void => write!(f, "void"),
827 TType::Bool => write!(f, "bool"),
828 TType::I08 => write!(f, "i08"),
829 TType::Double => write!(f, "double"),
830 TType::I16 => write!(f, "i16"),
831 TType::I32 => write!(f, "i32"),
832 TType::I64 => write!(f, "i64"),
833 TType::String => write!(f, "string"),
834 TType::Utf7 => write!(f, "UTF7"),
835 TType::Struct => write!(f, "struct"),
836 TType::Map => write!(f, "map"),
837 TType::Set => write!(f, "set"),
838 TType::List => write!(f, "list"),
839 TType::Utf8 => write!(f, "UTF8"),
840 TType::Utf16 => write!(f, "UTF16"),
841 }
842 }
843}
844
845pub fn verify_expected_sequence_number(expected: i32, actual: i32) -> crate::Result<()> {
850 if expected == actual {
851 Ok(())
852 } else {
853 Err(crate::Error::Application(crate::ApplicationError {
854 kind: crate::ApplicationErrorKind::BadSequenceId,
855 message: format!("expected {} got {}", expected, actual),
856 }))
857 }
858}
859
860pub fn verify_expected_service_call(expected: &str, actual: &str) -> crate::Result<()> {
865 if expected == actual {
866 Ok(())
867 } else {
868 Err(crate::Error::Application(crate::ApplicationError {
869 kind: crate::ApplicationErrorKind::WrongMethodName,
870 message: format!("expected {} got {}", expected, actual),
871 }))
872 }
873}
874
875pub fn verify_expected_message_type(
880 expected: TMessageType,
881 actual: TMessageType,
882) -> crate::Result<()> {
883 if expected == actual {
884 Ok(())
885 } else {
886 Err(crate::Error::Application(crate::ApplicationError {
887 kind: crate::ApplicationErrorKind::InvalidMessageType,
888 message: format!("expected {} got {}", expected, actual),
889 }))
890 }
891}
892
893pub fn verify_required_field_exists<T>(field_name: &str, field: &Option<T>) -> crate::Result<()> {
897 match *field {
898 Some(_) => Ok(()),
899 None => Err(crate::Error::Protocol(crate::ProtocolError {
900 kind: crate::ProtocolErrorKind::Unknown,
901 message: format!("missing required field {}", field_name),
902 })),
903 }
904}
905
906pub fn field_id(field_ident: &TFieldIdentifier) -> crate::Result<i16> {
912 field_ident.id.ok_or_else(|| {
913 crate::Error::Protocol(crate::ProtocolError {
914 kind: crate::ProtocolErrorKind::Unknown,
915 message: format!("missing field in in {:?}", field_ident),
916 })
917 })
918}
919
920#[cfg(test)]
921mod tests {
922
923 use std::io::Cursor;
924
925 use super::*;
926 use crate::transport::{TReadTransport, TWriteTransport};
927
928 #[test]
929 fn must_create_usable_input_protocol_from_concrete_input_protocol() {
930 let r: Box<dyn TReadTransport> = Box::new(Cursor::new([0, 1, 2]));
931 let mut t = TCompactInputProtocol::new(r);
932 takes_input_protocol(&mut t)
933 }
934
935 #[test]
936 fn must_create_usable_input_protocol_from_boxed_input() {
937 let r: Box<dyn TReadTransport> = Box::new(Cursor::new([0, 1, 2]));
938 let mut t: Box<dyn TInputProtocol> = Box::new(TCompactInputProtocol::new(r));
939 takes_input_protocol(&mut t)
940 }
941
942 #[test]
943 fn must_create_usable_output_protocol_from_concrete_output_protocol() {
944 let w: Box<dyn TWriteTransport> = Box::new(vec![0u8; 10]);
945 let mut t = TCompactOutputProtocol::new(w);
946 takes_output_protocol(&mut t)
947 }
948
949 #[test]
950 fn must_create_usable_output_protocol_from_boxed_output() {
951 let w: Box<dyn TWriteTransport> = Box::new(vec![0u8; 10]);
952 let mut t: Box<dyn TOutputProtocol> = Box::new(TCompactOutputProtocol::new(w));
953 takes_output_protocol(&mut t)
954 }
955
956 fn takes_input_protocol<R>(t: &mut R)
957 where
958 R: TInputProtocol,
959 {
960 t.read_byte().unwrap();
961 }
962
963 fn takes_output_protocol<W>(t: &mut W)
964 where
965 W: TOutputProtocol,
966 {
967 t.flush().unwrap();
968 }
969}