Skip to main content

rustorb_core/
codeset.rs

1//! Code set negotiation (CORBA 3.0, 13.10.2) and conversion of `char` data.
2//!
3//! rustorb's native code set for `char` and `string` is UTF-8, which it
4//! can convert to ISO 8859-1. For `wchar` and `wstring` it is UTF-16, with
5//! no conversions.
6
7use rustorb_giop::{CodeSetComponent, CodeSetComponentInfo, CodeSetContext, code_set};
8
9use crate::{CompletionStatus, SystemException, SystemExceptionKind};
10
11/// Native `char` code set of rustorb.
12pub const NATIVE_CHAR: u32 = code_set::UTF_8;
13/// `char` code sets rustorb converts to and from.
14pub const CONVERSION_CHAR: &[u32] = &[code_set::ISO_8859_1];
15/// Native `wchar` code set of rustorb.
16pub const NATIVE_WCHAR: u32 = code_set::UTF_16;
17
18/// The transmission code sets used on a connection.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct CodeSets {
21    /// Transmission code set for `char` and `string`.
22    pub char_data: u32,
23    /// Transmission code set for `wchar` and `wstring`, or `None` when the
24    /// server did not publish one.
25    pub wchar_data: Option<u32>,
26}
27
28impl CodeSets {
29    /// The code sets that apply without negotiation: ISO 8859-1 for
30    /// `char` and no `wchar` code set. GIOP 1.0, and objects whose IOR has
31    /// no code set component, use these.
32    pub const DEFAULT: CodeSets = CodeSets {
33        char_data: code_set::ISO_8859_1,
34        wchar_data: None,
35    };
36
37    /// The native code sets of rustorb, UTF-8 and UTF-16: what values
38    /// marshalled outside a connection use.
39    pub const NATIVE: CodeSets = CodeSets {
40        char_data: NATIVE_CHAR,
41        wchar_data: Some(NATIVE_WCHAR),
42    };
43
44    /// The native `char` code set and no `wchar` code set: GIOP 1.0
45    /// encapsulations made by `IOP::Codec`, where `wchar` cannot be used.
46    pub(crate) const NATIVE_NO_WCHAR: CodeSets = CodeSets {
47        char_data: NATIVE_CHAR,
48        wchar_data: None,
49    };
50
51    /// Chooses the transmission code sets for a server that published
52    /// `info`, as the client side of the negotiation.
53    pub fn negotiate(info: &CodeSetComponentInfo) -> Result<CodeSets, SystemException> {
54        let char_data =
55            choose(&info.for_char_data, NATIVE_CHAR, CONVERSION_CHAR).ok_or_else(incompatible)?;
56        let wchar = &info.for_wchar_data;
57        let wchar_data = if wchar.native_code_set == 0 && wchar.conversion_code_sets.is_empty() {
58            None
59        } else {
60            Some(choose(wchar, NATIVE_WCHAR, &[]).ok_or_else(incompatible)?)
61        };
62        Ok(CodeSets {
63            char_data,
64            wchar_data,
65        })
66    }
67
68    /// The `CodeSets` service context announcing these code sets. A
69    /// missing `wchar` code set is sent as `0`.
70    pub fn context(&self) -> CodeSetContext {
71        CodeSetContext {
72            char_data: self.char_data,
73            wchar_data: self.wchar_data.unwrap_or(0),
74        }
75    }
76
77    /// Encodes `s` in the `char` transmission code set.
78    pub fn encode_string(&self, s: &str) -> Result<Vec<u8>, SystemException> {
79        match self.char_data {
80            code_set::UTF_8 => Ok(s.as_bytes().to_vec()),
81            code_set::ISO_8859_1 => s
82                .chars()
83                .map(|c| {
84                    u8::try_from(u32::from(c)).map_err(|_| data_conversion(CompletionStatus::No))
85                })
86                .collect(),
87            _ => Err(incompatible()),
88        }
89    }
90
91    /// Decodes `bytes` from the `char` transmission code set.
92    pub fn decode_string(&self, bytes: &[u8]) -> Result<String, SystemException> {
93        match self.char_data {
94            code_set::UTF_8 => String::from_utf8(bytes.to_vec())
95                .map_err(|_| data_conversion(CompletionStatus::Yes)),
96            code_set::ISO_8859_1 => Ok(bytes.iter().map(|&b| char::from(b)).collect()),
97            _ => Err(incompatible()),
98        }
99    }
100}
101
102/// The negotiation rules: the client's native code set if the server
103/// uses or converts to it, else the server's native code set if the
104/// client converts to it, else the first code set both convert to.
105fn choose(server: &CodeSetComponent, native: u32, conversion: &[u32]) -> Option<u32> {
106    if server.native_code_set == native || server.conversion_code_sets.contains(&native) {
107        Some(native)
108    } else if conversion.contains(&server.native_code_set) {
109        Some(server.native_code_set)
110    } else {
111        conversion
112            .iter()
113            .copied()
114            .find(|c| server.conversion_code_sets.contains(c))
115    }
116}
117
118fn incompatible() -> SystemException {
119    SystemException::new(
120        SystemExceptionKind::CODESET_INCOMPATIBLE,
121        0,
122        CompletionStatus::No,
123    )
124}
125
126fn data_conversion(completed: CompletionStatus) -> SystemException {
127    SystemException::new(SystemExceptionKind::DATA_CONVERSION, 0, completed)
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133
134    fn info(char_native: u32, char_conv: &[u32], wchar_native: u32) -> CodeSetComponentInfo {
135        CodeSetComponentInfo {
136            for_char_data: CodeSetComponent {
137                native_code_set: char_native,
138                conversion_code_sets: char_conv.to_vec(),
139            },
140            for_wchar_data: CodeSetComponent {
141                native_code_set: wchar_native,
142                conversion_code_sets: Vec::new(),
143            },
144        }
145    }
146
147    #[test]
148    fn prefers_utf8_when_the_server_converts_to_it() {
149        let cs = CodeSets::negotiate(&info(
150            code_set::ISO_8859_1,
151            &[code_set::UTF_8],
152            code_set::UTF_16,
153        ))
154        .unwrap();
155        assert_eq!(cs.char_data, code_set::UTF_8);
156        assert_eq!(cs.wchar_data, Some(code_set::UTF_16));
157    }
158
159    #[test]
160    fn falls_back_to_latin1() {
161        let cs = CodeSets::negotiate(&info(code_set::ISO_8859_1, &[], 0)).unwrap();
162        assert_eq!(cs.char_data, code_set::ISO_8859_1);
163        assert_eq!(cs.wchar_data, None);
164        assert_eq!(cs.encode_string("caf\u{e9}").unwrap(), b"caf\xe9");
165        assert_eq!(cs.decode_string(b"caf\xe9").unwrap(), "caf\u{e9}");
166        assert!(cs.encode_string("\u{3042}").is_err());
167    }
168
169    #[test]
170    fn rejects_unknown_code_sets() {
171        let e = CodeSets::negotiate(&info(0x0001_0020, &[], 0)).unwrap_err();
172        assert!(e.is(SystemExceptionKind::CODESET_INCOMPATIBLE));
173    }
174}