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
// OPCUA for Rust

// SPDX-License-Identifier: MPL-2.0

// Copyright (C) 2017-2020 Adam Lock


//! Contains the implementation of `UAString`.


use std::{
    fmt, io::{Read, Write},
};

use crate::{
    encoding::{BinaryEncoder, DecodingLimits, EncodingResult, process_decode_io_result, process_encode_io_result, write_i32},
    status_codes::StatusCode,
};

/// To avoid naming conflict hell, the OPC UA String type is typed `UAString` so it does not collide

/// with the Rust `String`.

///

/// A string contains UTF-8 encoded characters or a null value. A null value is distinct from

/// being an empty string so internally, the code maintains that distinction by holding the value

/// as an `Option<String>`.

#[derive(Eq, PartialEq, Debug, Clone, Hash, Serialize, Deserialize)]
pub struct UAString {
    value: Option<String>,
}

impl fmt::Display for UAString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(ref value) = self.value {
            write!(f, "{}", value)
        } else {
            write!(f, "[null]")
        }
    }
}

impl BinaryEncoder<UAString> for UAString {
    fn byte_len(&self) -> usize {
        // Length plus the actual string length in bytes for a non-null string.

        4 + if self.value.is_none() { 0 } else { self.value.as_ref().unwrap().len() }
    }

    fn encode<S: Write>(&self, stream: &mut S) -> EncodingResult<usize> {
        // Strings are encoded as UTF8 chars preceded by an Int32 length. A -1 indicates a null string

        if self.value.is_none() {
            write_i32(stream, -1)
        } else {
            let value = self.value.as_ref().unwrap();
            let mut size: usize = 0;
            size += write_i32(stream, value.len() as i32)?;
            let buf = value.as_bytes();
            size += process_encode_io_result(stream.write(&buf))?;
            assert_eq!(size, self.byte_len());
            Ok(size)
        }
    }

    fn decode<S: Read>(stream: &mut S, decoding_limits: &DecodingLimits) -> EncodingResult<Self> {
        let len = i32::decode(stream, decoding_limits)?;
        // Null string?

        if len == -1 {
            Ok(UAString::null())
        } else if len < -1 {
            error!("String buf length is a negative number {}", len);
            Err(StatusCode::BadDecodingError)
        } else if len as usize > decoding_limits.max_string_length {
            error!("String buf length {} exceeds decoding limit {}", len, decoding_limits.max_string_length);
            Err(StatusCode::BadDecodingError)
        } else {
            // Create a buffer filled with zeroes and read the string over the top

            let mut buf = vec![0u8; len as usize];
            process_decode_io_result(stream.read_exact(&mut buf))?;
            let value = String::from_utf8(buf)
                .map_err(|err| {
                    trace!("Decoded string was not valid UTF-8 - {}", err.to_string());
                    StatusCode::BadDecodingError
                })?;
            Ok(UAString::from(value))
        }
    }
}

impl From<UAString> for String {
    fn from(value: UAString) -> Self {
        value.as_ref().to_string()
    }
}

impl AsRef<str> for UAString {
    fn as_ref(&self) -> &str {
        if self.is_null() { "" } else { self.value.as_ref().unwrap() }
    }
}

impl<'a> From<&'a str> for UAString {
    fn from(value: &'a str) -> Self {
        Self::from(value.to_string())
    }
}

impl From<&String> for UAString {
    fn from(value: &String) -> Self {
        UAString { value: Some(value.clone()) }
    }
}

impl From<String> for UAString {
    fn from(value: String) -> Self {
        UAString { value: Some(value) }
    }
}

impl Default for UAString {
    fn default() -> Self {
        UAString::null()
    }
}

impl<'a, 'b> PartialEq<str> for UAString {
    fn eq(&self, other: &str) -> bool {
        match self.value {
            None => false,
            Some(ref v) => v.eq(other)
        }
    }
}

impl UAString {
    pub fn value(&self) -> &Option<String> {
        &self.value
    }

    pub fn set_value(&mut self, value: Option<String>) {
        self.value = value;
    }

    /// Returns true if the string is null or empty, false otherwise

    pub fn is_empty(&self) -> bool {
        if self.value.is_none() { true } else { self.value.as_ref().unwrap().is_empty() }
    }

    /// Returns the length of the string in bytes or -1 for null.

    pub fn len(&self) -> isize {
        if self.value.is_none() { -1 } else { self.value.as_ref().unwrap().len() as isize }
    }

    /// Create a null string (not the same as an empty string).

    pub fn null() -> UAString {
        UAString { value: None }
    }

    /// Test if the string is null.

    pub fn is_null(&self) -> bool {
        self.value.is_none()
    }

    /// This function is meant for use with NumericRange. It creates a substring from this string

    /// from min up to and inclusive of max. Note that min must have an index within the string

    /// but max is allowed to be beyond the end in which case the remainder of the string is

    /// returned (see docs for NumericRange).

    pub fn substring(&self, min: usize, max: usize) -> Result<UAString, ()> {
        if let Some(ref v) = self.value() {
            if min >= v.len() {
                Err(())
            } else {
                let max = if max >= v.len() { v.len() - 1 } else { max };
                Ok(UAString::from(&v[min..=max]))
            }
        } else {
            Err(())
        }
    }
}

#[test]
fn string_null() {
    let s = UAString::null();
    assert!(s.is_null());
    assert!(s.is_empty());
    assert_eq!(s.len(), -1);
}

#[test]
fn string_empty() {
    let s = UAString::from("");
    assert!(!s.is_null());
    assert!(s.is_empty());
    assert_eq!(s.len(), 0);
}

#[test]
fn string_value() {
    let v = "Mary had a little lamb";
    let s = UAString::from(v);
    assert!(!s.is_null());
    assert!(!s.is_empty());
    assert_eq!(s.as_ref(), v);
}

#[test]
fn string_eq() {
    let s = UAString::null();
    assert!(!s.eq(""));

    let s = UAString::from("");
    assert!(s.eq(""));

    let s = UAString::from("Sunshine");
    assert!(s.ne("Moonshine"));
    assert!(s.eq("Sunshine"));
    assert!(!s.eq("Sunshine "));
}

#[test]
fn string_substring() {
    let a = "Mary had a little lamb";
    let v = UAString::from(a);
    let v2 = v.substring(0, 4).unwrap();
    let a2 = v2.as_ref();
    assert_eq!(a2, "Mary ");

    let v2 = v.substring(2, 2).unwrap();
    let a2 = v2.as_ref();
    assert_eq!(a2, "r");

    let v2 = v.substring(0, 2000).unwrap();
    assert_eq!(v, v2);
    assert_eq!(v2.as_ref(), a);

    assert!(v.substring(22, 10000).is_err());

    assert!(UAString::null().substring(0, 0).is_err());
}

/// An XML element.

pub type XmlElement = UAString;