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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/* The MIT License (MIT)
 *
 * Copyright (c) 2015 William Orr <will@worrbase.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
#![no_std]
#![feature(convert, core_str_ext, no_std)]

use core::cmp::Ordering::{self,Less,Greater,Equal};
use core::marker::PhantomData;
use core::result::Result;
use core::slice;

/// Platform-specific c_char type. This is defined for cases where
/// the user cannot import libc.
///
/// Defined as u8 on arm and i8 everywhere else
#[cfg(not(any(target_arch = "arm", target_arch = "aarch64")))]
#[allow(non_camel_case_types)]
pub type c_char = i8;
#[cfg(any(target_arch = "arm", target_arch = "aarch64"))]
#[allow(non_camel_case_types)]
pub type c_char = u8;


/// Constructs a new `CString` from a string literal
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate rcstring;
/// # fn main () {
/// let cs = cstr!("foo");
/// # }
/// ```
#[macro_export]
macro_rules! cstr {
    ($arg:expr) => ($crate::CString::new(concat!($arg, "\0")).unwrap());
}

/// Type representing a C-compatible string.
pub struct CString<'a> {
    data: *const c_char,
    len: usize,
    _marker: PhantomData<&'a c_char>
}

/// Error returned when a `CString` was initialized without a trailing
/// `NULL` byte, or if there are non-ASCII characters in the string
#[derive(Debug)]
pub struct Error(&'static str);

fn strlen(ptr: *const c_char) -> isize {
    let mut ctr = 0isize;
    loop {
        if unsafe { *ptr.offset(ctr) == 0 as c_char } {
            break
        }

        ctr += 1;
    }

    ctr
}

fn ascii_guard(ptr: *const c_char, len: usize) -> bool {
    let mut ctr = 0usize;
    while ctr < len {
        if unsafe { *ptr.offset(ctr as isize) < 0 as c_char } {
            return false;
        }

        ctr += 1;
    }

    true
}

impl<'a> CString<'a> {
    /// Constructs a new CString from a string slice
    ///
    /// The caller **MUST** ensure that there is a trailing NULL to terminate
    /// the string. To make this easier, the `cstr!` macro is provided.
    ///
    /// CStrings **MUST NOT** have any non-ASCII characters, even extended
    /// ASCII characters aren't allowed.
    ///
    /// # Examples
    ///
    /// ```
    /// use rcstring::CString;
    ///
    /// let cs = CString::new("foo\0").unwrap();
    /// ```
    pub fn new(s: &'a str) -> Result<CString<'a>, Error> {
        if s.len() == 0 {
            return Err(Error("0-length cstring found"));
        }

        let ret = CString {
            data: s.as_ptr() as *const c_char,
            len: s.len(),
            _marker: PhantomData
        };

        if ! ascii_guard(ret.data, ret.len) {
            return Err(Error("Invalid character in string"));
        }

        if unsafe { *ret.into_raw().offset(ret.len as isize - 1) != 0 } {
            Err(Error("No NULL terminator present"))
        } else {
            Ok(ret)
        }
    }

    /// Converts an exising raw pointer to a string and converts it to a
    /// `CString` with a length determined by an internal `strlen`
    /// implementation.
    pub unsafe fn from_raw(ptr: *const c_char) -> Result<CString<'a>, Error> {
        let siz = strlen(ptr) as usize + 1usize;

        let ret = CString {
            data: ptr,
            len: siz,
            _marker: PhantomData
        };

        if ! ascii_guard(ret.data, ret.len) {
            Err(Error("Invalid character in string"))
        } else {
            Ok(ret)
        }
    }

    /// Returns a mutable pointer to a CString for use in functions taking
    /// a classic C string
    pub unsafe fn into_raw(&self) -> *const c_char {
        self.data
    }

    /// Returns length of string, *including* trailing NULL
    pub fn len(&self) -> usize {
        self.len
    }
}

impl<'a> Eq for CString<'a> { }
impl<'a> PartialEq for CString<'a> {
    fn eq(&self, other: &CString) -> bool {
        unsafe {
            slice::from_raw_parts(self.data, other.len()) ==
                slice::from_raw_parts(other.data, other.len())
        }
    }

    fn ne(&self, other: &CString) -> bool {
        ! self.eq(other)
    }
}

impl<'a> PartialOrd for CString<'a> {
    fn partial_cmp(&self, other: &CString) -> Option<Ordering> {
        unsafe {
            slice::from_raw_parts(self.data, self.len())
                .partial_cmp(slice::from_raw_parts(other.data, other.len()))
        }
    }

    fn le(&self, other: &CString) -> bool {
        match self.partial_cmp(other) {
            Some(Less) => true,
            Some(Equal) => true,
            _ => false
        }
    }

    fn ge(&self, other: &CString) -> bool {
        match self.partial_cmp(other) {
            Some(Greater) => true,
            Some(Equal) => true,
            _ => false
        }
    }

    fn lt(&self, other: &CString) -> bool {
        match self.partial_cmp(other) {
            Some(Less) => true,
            _ => false
        }
    }

    fn gt(&self, other: &CString) -> bool {
        match self.partial_cmp(other) {
            Some(Greater) => true,
            _ => false
        }
    }
}

impl<'a> Ord for CString<'a> {
    fn cmp(&self, other: &CString) -> Ordering {
        self.data.cmp(&other.data)
    }
}

#[cfg(test)] #[macro_use] extern crate std;

#[cfg(test)]
mod test {
    use super::{c_char,CString,Error};
    use std::ffi::CString as OldString;
    use std::slice;
    use std::string::String;

    #[test]
    fn new_cstring() {
        {
            let cstr = cstr!("foo");
            let buf = "foo\0".as_ptr() as *const c_char;

            unsafe {
                assert_eq!(slice::from_raw_parts(cstr.data, cstr.len()),
                    slice::from_raw_parts(buf, 4));
            }
        }
        {
            let raw = OldString::new("foo").unwrap().into_raw();
            let cstr = unsafe { CString::from_raw(raw).unwrap() };
            let buf = "foo\0".as_ptr() as *const c_char;

            unsafe {
                assert_eq!(slice::from_raw_parts(cstr.data, cstr.len()),
                    slice::from_raw_parts(buf, 4));
            }
        }
        {
            let cstr_res = CString::new("foo");

            assert!(! cstr_res.is_ok());
        }
        {
            let cstr_res = CString::new("");

            assert!(! cstr_res.is_ok());
        }
        {
            let cstr_res = CString::new("ñ\0");

            assert!(! cstr_res.is_ok());
        }
        {
            let cstr_res = CString::new("ай да, пирожки\0");

            assert!(! cstr_res.is_ok());
        }
        {
            {
                let s = String::from("foo\0");
                let cstr_res: Result<CString, Error> = CString::new(s.as_str());
                assert!(cstr_res.is_ok());
            }
        }
    }

    #[test]
    fn from_cstring() {
        {
            let cstr = cstr!("foo");
            let raw = unsafe { cstr.into_raw() };
            let other = OldString::new("foo").unwrap().into_raw();

            unsafe {
                assert_eq!(*raw, *other);
            }
        }
    }

    #[test]
    fn cstring_len() {
        {
            let cstr = cstr!("foo");
            assert_eq!(cstr.len(), 4);
        }
        {
            let raw = OldString::new("foo").unwrap().into_raw();
            let cstr = unsafe { CString::from_raw(raw).unwrap() };
            assert_eq!(cstr.len(), 4);
        }
    }

    #[test]
    fn eq() {
        {
            let cstr = cstr!("foo");
            let other = cstr!("bar");

            assert!(cstr != other);
        }
        {
            let cstr = cstr!("foo");
            let other = cstr!("foo");

            assert!(cstr == other);
        }
    }

    #[test]
    fn cmp() {
        {
            let cstr = cstr!("foo");
            let other = cstr!("bar");

            assert!(cstr > other);
        }
        {
            let cstr = cstr!("foo");
            let other = cstr!("bar");

            assert!(other < cstr);
        }
    }
}