-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Detect encoding and decode text response #256
Changes from 1 commit
25378d6
f5d00b6
2337017
19c57f6
8c08daa
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,9 +3,11 @@ use std::fmt; | |
use std::io::{self, Read}; | ||
use std::time::Duration; | ||
|
||
use encoding_rs::{Encoding, UTF_8}; | ||
use futures::{Async, Poll, Stream}; | ||
use serde::de::DeserializeOwned; | ||
use serde_json; | ||
use uchardet; | ||
|
||
use client::KeepCoreThreadAlive; | ||
use header::Headers; | ||
|
@@ -180,9 +182,12 @@ impl Response { | |
let len = self.headers().get::<::header::ContentLength>() | ||
.map(|ct_len| **ct_len) | ||
.unwrap_or(0); | ||
let mut content = String::with_capacity(len as usize); | ||
self.read_to_string(&mut content).map_err(::error::from)?; | ||
Ok(content) | ||
let mut content = Vec::with_capacity(len as usize); | ||
self.read_to_end(&mut content).map_err(::error::from)?; | ||
let encoding_name = uchardet::detect_encoding_name(&content).unwrap_or_else(|_| "utf-8".to_string()); | ||
let encoding = Encoding::for_label(encoding_name.as_bytes()).unwrap_or(UTF_8); | ||
let (text, _, _) = encoding.decode(&content); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I am not sure about this. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It looks like So, seems this could be handled like so: // a block because of borrow checker
{
let (text, _, _) = encoding.decode(&content);
match text {
Cow::Owned(s) => return Ok(s),
_ => (),
}
}
unsafe {
// decoding returned Cow::Borrowed, meaning these bytes
// are already valid utf8
Ok(String::from_utf8_unchecked(content))
} |
||
Ok(text.to_string()) | ||
} | ||
|
||
/// Copy the response body into a writer. | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can't use chardet because of license issue, it's LGPL-3.0