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    /// Chooses the transmission code sets for a server that published
45    /// `info`, as the client side of the negotiation.
46    pub fn negotiate(info: &CodeSetComponentInfo) -> Result<CodeSets, SystemException> {
47        let char_data =
48            choose(&info.for_char_data, NATIVE_CHAR, CONVERSION_CHAR).ok_or_else(incompatible)?;
49        let wchar = &info.for_wchar_data;
50        let wchar_data = if wchar.native_code_set == 0 && wchar.conversion_code_sets.is_empty() {
51            None
52        } else {
53            Some(choose(wchar, NATIVE_WCHAR, &[]).ok_or_else(incompatible)?)
54        };
55        Ok(CodeSets {
56            char_data,
57            wchar_data,
58        })
59    }
60
61    /// The `CodeSets` service context announcing these code sets. A
62    /// missing `wchar` code set is sent as `0`.
63    pub fn context(&self) -> CodeSetContext {
64        CodeSetContext {
65            char_data: self.char_data,
66            wchar_data: self.wchar_data.unwrap_or(0),
67        }
68    }
69
70    /// Encodes `s` in the `char` transmission code set.
71    pub fn encode_string(&self, s: &str) -> Result<Vec<u8>, SystemException> {
72        match self.char_data {
73            code_set::UTF_8 => Ok(s.as_bytes().to_vec()),
74            code_set::ISO_8859_1 => s
75                .chars()
76                .map(|c| {
77                    u8::try_from(u32::from(c)).map_err(|_| data_conversion(CompletionStatus::No))
78                })
79                .collect(),
80            _ => Err(incompatible()),
81        }
82    }
83
84    /// Decodes `bytes` from the `char` transmission code set.
85    pub fn decode_string(&self, bytes: &[u8]) -> Result<String, SystemException> {
86        match self.char_data {
87            code_set::UTF_8 => String::from_utf8(bytes.to_vec())
88                .map_err(|_| data_conversion(CompletionStatus::Yes)),
89            code_set::ISO_8859_1 => Ok(bytes.iter().map(|&b| char::from(b)).collect()),
90            _ => Err(incompatible()),
91        }
92    }
93}
94
95/// The negotiation rules: the client's native code set if the server
96/// uses or converts to it, else the server's native code set if the
97/// client converts to it, else the first code set both convert to.
98fn choose(server: &CodeSetComponent, native: u32, conversion: &[u32]) -> Option<u32> {
99    if server.native_code_set == native || server.conversion_code_sets.contains(&native) {
100        Some(native)
101    } else if conversion.contains(&server.native_code_set) {
102        Some(server.native_code_set)
103    } else {
104        conversion
105            .iter()
106            .copied()
107            .find(|c| server.conversion_code_sets.contains(c))
108    }
109}
110
111fn incompatible() -> SystemException {
112    SystemException::new(
113        SystemExceptionKind::CODESET_INCOMPATIBLE,
114        0,
115        CompletionStatus::No,
116    )
117}
118
119fn data_conversion(completed: CompletionStatus) -> SystemException {
120    SystemException::new(SystemExceptionKind::DATA_CONVERSION, 0, completed)
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    fn info(char_native: u32, char_conv: &[u32], wchar_native: u32) -> CodeSetComponentInfo {
128        CodeSetComponentInfo {
129            for_char_data: CodeSetComponent {
130                native_code_set: char_native,
131                conversion_code_sets: char_conv.to_vec(),
132            },
133            for_wchar_data: CodeSetComponent {
134                native_code_set: wchar_native,
135                conversion_code_sets: Vec::new(),
136            },
137        }
138    }
139
140    #[test]
141    fn prefers_utf8_when_the_server_converts_to_it() {
142        let cs = CodeSets::negotiate(&info(
143            code_set::ISO_8859_1,
144            &[code_set::UTF_8],
145            code_set::UTF_16,
146        ))
147        .unwrap();
148        assert_eq!(cs.char_data, code_set::UTF_8);
149        assert_eq!(cs.wchar_data, Some(code_set::UTF_16));
150    }
151
152    #[test]
153    fn falls_back_to_latin1() {
154        let cs = CodeSets::negotiate(&info(code_set::ISO_8859_1, &[], 0)).unwrap();
155        assert_eq!(cs.char_data, code_set::ISO_8859_1);
156        assert_eq!(cs.wchar_data, None);
157        assert_eq!(cs.encode_string("caf\u{e9}").unwrap(), b"caf\xe9");
158        assert_eq!(cs.decode_string(b"caf\xe9").unwrap(), "caf\u{e9}");
159        assert!(cs.encode_string("\u{3042}").is_err());
160    }
161
162    #[test]
163    fn rejects_unknown_code_sets() {
164        let e = CodeSets::negotiate(&info(0x0001_0020, &[], 0)).unwrap_err();
165        assert!(e.is(SystemExceptionKind::CODESET_INCOMPATIBLE));
166    }
167}