Skip to content

Add ParseOptions::encoding_override_lookup #443

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

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,24 @@ impl<'a> ParseOptions<'a> {
self
}

/// Override the character encoding of query strings.
/// This is a legacy concept only relevant for HTML.
///
/// `label` is the WHATWG [encoding label](https://encoding.spec.whatwg.org/#names-and-labels).
///
/// Silently fails if `label` is invalid.
///
/// This method is only available if the `query_encoding`
/// [feature](http://doc.crates.io/manifest.html#the-features-section]) is enabled.
#[cfg(feature = "query_encoding")]
pub fn encoding_override_lookup(mut self, label: &[u8]) -> Self {
self.encoding_override = match EncodingOverride::lookup(label) {
Some(encoding_override) => encoding_override.to_output_encoding(),
None => self.encoding_override,
};
self
}

/// Call the provided function or closure on non-fatal parse errors, passing
/// a static string description. This method is deprecated in favor of
/// `syntax_violation_callback` and is implemented as an adaptor for the
Expand Down
19 changes: 19 additions & 0 deletions tests/unit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -543,3 +543,22 @@ fn test_options_reuse() {
assert_eq!(*violations.borrow(),
vec!(ExpectedDoubleSlash, Backslash));
}

#[cfg(feature = "query_encoding")]
#[test]
fn test_encoding_override_lookup() {
let url = Url::options()
.encoding_override_lookup(b"utf-8")
.parse("http://example.com/?例子").unwrap();
assert_eq!(url.query(), Some("%E4%BE%8B%E5%AD%90"));

let url = Url::options()
.encoding_override_lookup(b"gbk")
.parse("http://example.com/?例子").unwrap();
assert_eq!(url.query(), Some("%C0%FD%D7%D3"));

let url = Url::options()
.encoding_override_lookup(b"invalid label is ignored!")
.parse("http://example.com/?例子").unwrap();
assert_eq!(url.query(), Some("%E4%BE%8B%E5%AD%90"));
}