Skip to main content

rustorb_core/
iop.rs

1//! `IOP::CodecFactory` and `IOP::Codec`: CDR encapsulations of anys and
2//! values, the usual form of service context and tagged component data
3//! (see [`pi`](crate::pi) and docs/portable-interceptors.md).
4
5use std::fmt;
6use std::sync::Weak;
7
8use rustorb_cdr::{ByteOrder, Decoder, Encoder, Encoding as CdrEncoding};
9
10pub use rustorb_giop::{ServiceContext, TaggedComponent, TaggedProfile, component_tag, service_id};
11
12use crate::orb::OrbInner;
13use crate::stream::{InStream, OutStream};
14use crate::{Any, Orb, TypeCode};
15
16/// `IOP::ENCODING_CDR_ENCAPS`.
17pub const ENCODING_CDR_ENCAPS: i16 = 0;
18
19/// `IOP::Encoding`: a format and its version.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub struct Encoding {
22    /// The format, such as [`ENCODING_CDR_ENCAPS`].
23    pub format: i16,
24    /// Major version.
25    pub major_version: u8,
26    /// Minor version.
27    pub minor_version: u8,
28}
29
30impl Encoding {
31    /// `ENCODING_CDR_ENCAPS` of GIOP `major.minor`.
32    pub fn cdr(major_version: u8, minor_version: u8) -> Encoding {
33        Encoding {
34            format: ENCODING_CDR_ENCAPS,
35            major_version,
36            minor_version,
37        }
38    }
39}
40
41/// Why a [`Codec`] failed.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum CodecError {
44    /// `Codec::InvalidTypeForEncoding`: the value cannot be written in
45    /// this encoding (or does not match its TypeCode).
46    InvalidTypeForEncoding,
47    /// `Codec::FormatMismatch`: the data is not a valid encapsulation of
48    /// this encoding.
49    FormatMismatch,
50    /// `Codec::TypeMismatch`: the data does not hold a value of the
51    /// TypeCode given.
52    TypeMismatch,
53}
54
55impl fmt::Display for CodecError {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        f.write_str(match self {
58            CodecError::InvalidTypeForEncoding => "IOP::Codec::InvalidTypeForEncoding",
59            CodecError::FormatMismatch => "IOP::Codec::FormatMismatch",
60            CodecError::TypeMismatch => "IOP::Codec::TypeMismatch",
61        })
62    }
63}
64
65impl std::error::Error for CodecError {}
66
67/// `IOP::CodecFactory::UnknownEncoding`.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub struct UnknownEncoding;
70
71impl fmt::Display for UnknownEncoding {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.write_str("IOP::CodecFactory::UnknownEncoding")
74    }
75}
76
77impl std::error::Error for UnknownEncoding {}
78
79/// `IOP::CodecFactory` of an ORB ([`Orb::codec_factory`]).
80#[derive(Clone)]
81pub struct CodecFactory {
82    orb: Weak<OrbInner>,
83    order: ByteOrder,
84}
85
86impl fmt::Debug for CodecFactory {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        f.debug_struct("CodecFactory").finish_non_exhaustive()
89    }
90}
91
92impl CodecFactory {
93    pub(crate) fn new(orb: &Orb) -> CodecFactory {
94        CodecFactory {
95            orb: std::sync::Arc::downgrade(&orb.inner),
96            order: orb.inner.options.byte_order,
97        }
98    }
99
100    /// `create_codec`: a codec for `ENCODING_CDR_ENCAPS` 1.0 to 1.2;
101    /// others are `UnknownEncoding`.
102    pub fn create_codec(&self, encoding: Encoding) -> Result<Codec, UnknownEncoding> {
103        let version = match (
104            encoding.format,
105            encoding.major_version,
106            encoding.minor_version,
107        ) {
108            (ENCODING_CDR_ENCAPS, 1, 0) => CdrEncoding::Giop1_0,
109            (ENCODING_CDR_ENCAPS, 1, 1) => CdrEncoding::Giop1_1,
110            (ENCODING_CDR_ENCAPS, 1, 2) => CdrEncoding::Giop1_2,
111            _ => return Err(UnknownEncoding),
112        };
113        Ok(Codec {
114            orb: self.orb.clone(),
115            order: self.order,
116            version,
117        })
118    }
119}
120
121/// `IOP::Codec`: CDR encapsulations, with the native code sets (UTF-8
122/// and UTF-16). Object references read from data belong to the ORB of the
123/// factory.
124#[derive(Clone)]
125pub struct Codec {
126    orb: Weak<OrbInner>,
127    order: ByteOrder,
128    version: CdrEncoding,
129}
130
131impl fmt::Debug for Codec {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        f.debug_struct("Codec")
134            .field("version", &self.version)
135            .finish_non_exhaustive()
136    }
137}
138
139impl Codec {
140    /// `encode`: the TypeCode and the value of `data`.
141    pub fn encode(&self, data: &Any) -> Result<Vec<u8>, CodecError> {
142        self.write(|out| out.write_any(data))
143    }
144
145    /// `decode`: an any written by [`encode`](Codec::encode).
146    pub fn decode(&self, data: &[u8]) -> Result<Any, CodecError> {
147        self.read(data, |input| input.read_any())
148            .map_err(|_| CodecError::FormatMismatch)
149    }
150
151    /// `encode_value`: the value of `data` only.
152    pub fn encode_value(&self, data: &Any) -> Result<Vec<u8>, CodecError> {
153        self.write(|out| out.write_value(data.typecode(), data.value()))
154    }
155
156    /// `decode_value`: a value of type `tc` written by
157    /// [`encode_value`](Codec::encode_value).
158    pub fn decode_value(&self, data: &[u8], tc: &TypeCode) -> Result<Any, CodecError> {
159        let value = self
160            .read(data, |input| input.read_value(tc))
161            .map_err(|e| match e {
162                ReadError::Format => CodecError::FormatMismatch,
163                ReadError::Value => CodecError::TypeMismatch,
164            })?;
165        Ok(Any::new(tc.clone(), value))
166    }
167
168    fn write(
169        &self,
170        f: impl FnOnce(&mut OutStream<'_>) -> Result<(), crate::SystemException>,
171    ) -> Result<Vec<u8>, CodecError> {
172        let mut enc = Encoder::encapsulation(self.order, self.version);
173        {
174            let mut out = OutStream::standalone(&mut enc);
175            if self.version == CdrEncoding::Giop1_0 {
176                // GIOP 1.0 has no wchar.
177                out.set_code_sets(crate::CodeSets::NATIVE_NO_WCHAR);
178            }
179            f(&mut out).map_err(|_| CodecError::InvalidTypeForEncoding)?;
180        }
181        Ok(enc.into_parts().0)
182    }
183
184    fn read<T>(
185        &self,
186        data: &[u8],
187        f: impl FnOnce(&mut InStream<'_>) -> Result<T, crate::SystemException>,
188    ) -> Result<T, ReadError> {
189        let dec = Decoder::encapsulation(data, self.version).map_err(|_| ReadError::Format)?;
190        let orb = self.orb.upgrade().map(|inner| Orb { inner });
191        let mut input = InStream::standalone(dec, orb.as_ref());
192        if self.version == CdrEncoding::Giop1_0 {
193            input.set_code_sets(crate::CodeSets::NATIVE_NO_WCHAR);
194        }
195        f(&mut input).map_err(|_| ReadError::Value)
196    }
197}
198
199enum ReadError {
200    Format,
201    Value,
202}