encoding.rs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. // Copyright 2013-2014 The rust-url developers.
  2. //
  3. // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
  4. // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
  5. // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
  6. // option. This file may not be copied, modified, or distributed
  7. // except according to those terms.
  8. //! Abstraction that conditionally compiles either to rust-encoding,
  9. //! or to only support UTF-8.
  10. #[cfg(feature = "query_encoding")]
  11. extern crate encoding;
  12. use std::borrow::Cow;
  13. #[cfg(feature = "query_encoding")]
  14. use std::fmt::{self, Debug, Formatter};
  15. #[cfg(feature = "query_encoding")]
  16. use self::encoding::label::encoding_from_whatwg_label;
  17. #[cfg(feature = "query_encoding")]
  18. pub use self::encoding::types::EncodingRef;
  19. #[cfg(feature = "query_encoding")]
  20. use self::encoding::types::{DecoderTrap, EncoderTrap};
  21. #[cfg(feature = "query_encoding")]
  22. #[derive(Copy, Clone)]
  23. pub struct EncodingOverride {
  24. /// `None` means UTF-8.
  25. encoding: Option<EncodingRef>,
  26. }
  27. #[cfg(feature = "query_encoding")]
  28. impl EncodingOverride {
  29. pub fn from_opt_encoding(encoding: Option<EncodingRef>) -> Self {
  30. encoding.map(Self::from_encoding).unwrap_or_else(Self::utf8)
  31. }
  32. pub fn from_encoding(encoding: EncodingRef) -> Self {
  33. EncodingOverride {
  34. encoding: if encoding.name() == "utf-8" {
  35. None
  36. } else {
  37. Some(encoding)
  38. },
  39. }
  40. }
  41. #[inline]
  42. pub fn utf8() -> Self {
  43. EncodingOverride { encoding: None }
  44. }
  45. pub fn lookup(label: &[u8]) -> Option<Self> {
  46. // Don't use String::from_utf8_lossy since no encoding label contains U+FFFD
  47. // https://encoding.spec.whatwg.org/#names-and-labels
  48. ::std::str::from_utf8(label)
  49. .ok()
  50. .and_then(encoding_from_whatwg_label)
  51. .map(Self::from_encoding)
  52. }
  53. /// https://encoding.spec.whatwg.org/#get-an-output-encoding
  54. pub fn to_output_encoding(self) -> Self {
  55. if let Some(encoding) = self.encoding {
  56. if matches!(encoding.name(), "utf-16le" | "utf-16be") {
  57. return Self::utf8();
  58. }
  59. }
  60. self
  61. }
  62. pub fn is_utf8(&self) -> bool {
  63. self.encoding.is_none()
  64. }
  65. pub fn name(&self) -> &'static str {
  66. match self.encoding {
  67. Some(encoding) => encoding.name(),
  68. None => "utf-8",
  69. }
  70. }
  71. pub fn decode<'a>(&self, input: Cow<'a, [u8]>) -> Cow<'a, str> {
  72. match self.encoding {
  73. // `encoding.decode` never returns `Err` when called with `DecoderTrap::Replace`
  74. Some(encoding) => encoding
  75. .decode(&input, DecoderTrap::Replace)
  76. .unwrap()
  77. .into(),
  78. None => decode_utf8_lossy(input),
  79. }
  80. }
  81. pub fn encode<'a>(&self, input: Cow<'a, str>) -> Cow<'a, [u8]> {
  82. match self.encoding {
  83. // `encoding.encode` never returns `Err` when called with `EncoderTrap::NcrEscape`
  84. Some(encoding) => Cow::Owned(encoding.encode(&input, EncoderTrap::NcrEscape).unwrap()),
  85. None => encode_utf8(input),
  86. }
  87. }
  88. }
  89. #[cfg(feature = "query_encoding")]
  90. impl Debug for EncodingOverride {
  91. fn fmt(&self, f: &mut Formatter) -> fmt::Result {
  92. write!(f, "EncodingOverride {{ encoding: ")?;
  93. match self.encoding {
  94. Some(e) => write!(f, "{} }}", e.name()),
  95. None => write!(f, "None }}"),
  96. }
  97. }
  98. }
  99. #[cfg(not(feature = "query_encoding"))]
  100. #[derive(Copy, Clone, Debug)]
  101. pub struct EncodingOverride;
  102. #[cfg(not(feature = "query_encoding"))]
  103. impl EncodingOverride {
  104. #[inline]
  105. pub fn utf8() -> Self {
  106. EncodingOverride
  107. }
  108. pub fn decode<'a>(&self, input: Cow<'a, [u8]>) -> Cow<'a, str> {
  109. decode_utf8_lossy(input)
  110. }
  111. pub fn encode<'a>(&self, input: Cow<'a, str>) -> Cow<'a, [u8]> {
  112. encode_utf8(input)
  113. }
  114. }
  115. pub fn decode_utf8_lossy(input: Cow<[u8]>) -> Cow<str> {
  116. match input {
  117. Cow::Borrowed(bytes) => String::from_utf8_lossy(bytes),
  118. Cow::Owned(bytes) => {
  119. let raw_utf8: *const [u8];
  120. match String::from_utf8_lossy(&bytes) {
  121. Cow::Borrowed(utf8) => raw_utf8 = utf8.as_bytes(),
  122. Cow::Owned(s) => return s.into(),
  123. }
  124. // from_utf8_lossy returned a borrow of `bytes` unchanged.
  125. debug_assert!(raw_utf8 == &*bytes as *const [u8]);
  126. // Reuse the existing `Vec` allocation.
  127. unsafe { String::from_utf8_unchecked(bytes) }.into()
  128. }
  129. }
  130. }
  131. pub fn encode_utf8(input: Cow<str>) -> Cow<[u8]> {
  132. match input {
  133. Cow::Borrowed(s) => Cow::Borrowed(s.as_bytes()),
  134. Cow::Owned(s) => Cow::Owned(s.into_bytes()),
  135. }
  136. }