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
//! General utility methods for the las library.

use std::str::{from_utf8, Utf8Error};

/// Trim trailing null characters from a u8 buffer.
///
/// # Examples
///
/// Trailing nulls are trimmed.
///
/// ```
/// let buffer = [80u8, 101u8, 116u8, 101u8, 0u8];
/// assert_eq!("Pete", las::util::trim_to_string(&buffer).unwrap());
/// ```
///
/// Characters after the first trailing null are ignored.
///
/// ```
/// let buffer = [80u8, 0u8, 116u8, 101u8, 0u8];
/// assert_eq!("P", las::util::trim_to_string(&buffer).unwrap());
/// ```
pub fn trim_to_string(buffer: &[u8]) -> Result<&str, Utf8Error> {
    let mut index = 0;
    for &x in buffer {
        if x != 0 {
            index += 1;
        } else {
            break;
        }
    }
    from_utf8(&buffer[0..index])
}