Skip to content

Instantly share code, notes, and snippets.

@cite-reader
Created May 14, 2016 05:36
Show Gist options
  • Save cite-reader/245df62af11f920fd8251837c73a1a0b to your computer and use it in GitHub Desktop.
Save cite-reader/245df62af11f920fd8251837c73a1a0b to your computer and use it in GitHub Desktop.
Sometimes you want to parse as much UTF-8 as possible.
//! Parsing UTF-8 prefixes out of bytes
/*
Copyright 2016 Alex hill
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
use std::str;
pub fn valid_prefix<'a>(b: &'a [u8]) -> Prefix<'a> {
match str::from_utf8(b) {
Ok(everything) => Prefix { valid: Some(everything), rest: None },
Err(e) => {
let up_to = e.valid_up_to();
if up_to > 0 && up_to == b.len() {
Prefix {
valid: Some(unsafe{str::from_utf8_unchecked(&b[.. up_to])}),
rest: None
}
}
else if up_to > 0 {
Prefix {
valid: Some(unsafe{str::from_utf8_unchecked(&b[.. up_to])}),
rest: Some(&b[up_to ..])
}
}
else {
Prefix {
valid: None,
rest: Some(b)
}
}
}
}
}
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct Prefix<'a> {
pub valid: Option<&'a str>,
pub rest: Option<&'a [u8]>
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn valid_utf8() {
let input = "This string is valid UTF-8";
assert_eq!(Prefix{valid: Some(input), rest: None},
valid_prefix(input.as_bytes()));
}
#[test]
fn total_garbage() {
let input: &[u8] = &[0x80, 0x80, 0x80];
assert_eq!(Prefix{valid: None, rest: Some(input)},
valid_prefix(input));
}
#[test]
fn some_prefix() {
let input: &[u8] = b"spam\xff";
assert_eq!(Prefix{valid: Some("spam"), rest: Some(b"\xff" as &[u8])},
valid_prefix(input));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment