Replace the utf-8 library with std::str::from_utf8 usage

pull/198/head
Stanislav Tkach 4 years ago
parent 550cc49cc6
commit 05b8dd913e
  1. 1
      Cargo.toml
  2. 49
      src/protocol/message.rs

@ -33,7 +33,6 @@ rand = "0.8.0"
sha-1 = "0.9" sha-1 = "0.9"
thiserror = "1.0.23" thiserror = "1.0.23"
url = "2.1.0" url = "2.1.0"
utf-8 = "0.7.5"
[dependencies.native-tls-crate] [dependencies.native-tls-crate]
optional = true optional = true

@ -9,14 +9,12 @@ use super::frame::CloseFrame;
use crate::error::{CapacityError, Error, Result}; use crate::error::{CapacityError, Error, Result};
mod string_collect { mod string_collect {
use utf8::DecodeError;
use crate::error::{Error, Result}; use crate::error::{Error, Result};
#[derive(Debug)] #[derive(Debug)]
pub struct StringCollector { pub struct StringCollector {
data: String, data: String,
incomplete: Option<utf8::Incomplete>, incomplete: Option<Vec<u8>>,
} }
impl StringCollector { impl StringCollector {
@ -25,48 +23,41 @@ mod string_collect {
} }
pub fn len(&self) -> usize { pub fn len(&self) -> usize {
self.data self.data.len().saturating_add(self.incomplete.as_ref().map(|i| i.len()).unwrap_or(0))
.len()
.saturating_add(self.incomplete.map(|i| i.buffer_len as usize).unwrap_or(0))
} }
pub fn extend<T: AsRef<[u8]>>(&mut self, tail: T) -> Result<()> { pub fn extend<T: AsRef<[u8]>>(&mut self, tail: T) -> Result<()> {
let mut input: &[u8] = tail.as_ref(); let mut input: &[u8] = tail.as_ref();
if input.is_empty() {
if let Some(mut incomplete) = self.incomplete.take() { return Ok(());
if let Some((result, rest)) = incomplete.try_complete(input) {
input = rest;
if let Ok(text) = result {
self.data.push_str(text);
} else {
return Err(Error::Utf8);
}
} else {
input = &[];
self.incomplete = Some(incomplete);
} }
let incomplete = self.incomplete.take().map(|mut i| {
i.extend_from_slice(input);
i
});
if let Some(i) = incomplete.as_ref() {
input = i.as_slice();
} }
if !input.is_empty() { match std::str::from_utf8(input) {
match utf8::decode(input) {
Ok(text) => { Ok(text) => {
self.data.push_str(text); self.data.push_str(text);
Ok(()) Ok(())
} }
Err(DecodeError::Incomplete { valid_prefix, incomplete_suffix }) => { Err(e) => {
self.data.push_str(valid_prefix); // The incomplete part cannot be longer than 4 bytes (char).
self.incomplete = Some(incomplete_suffix); if e.valid_up_to() == 0 || input.len() - e.valid_up_to() > 4 {
Ok(())
}
Err(DecodeError::Invalid { valid_prefix, .. }) => {
self.data.push_str(valid_prefix);
Err(Error::Utf8) Err(Error::Utf8)
}
}
} else { } else {
let (valid, incomplete) = input.split_at(e.valid_up_to());
self.data.push_str(unsafe { std::str::from_utf8_unchecked(valid) });
self.incomplete = Some(incomplete.to_owned());
Ok(()) Ok(())
} }
} }
}
}
pub fn into_string(self) -> Result<String> { pub fn into_string(self) -> Result<String> {
if self.incomplete.is_some() { if self.incomplete.is_some() {

Loading…
Cancel
Save