encoding.rs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. // Copyright 2013-2014 Simon Sapin.
  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")] extern crate encoding;
  11. use std::borrow::Cow;
  12. #[cfg(feature = "query_encoding")] use self::encoding::types::{DecoderTrap, EncoderTrap};
  13. #[cfg(feature = "query_encoding")] use self::encoding::label::encoding_from_whatwg_label;
  14. #[cfg(feature = "query_encoding")] pub use self::encoding::types::EncodingRef;
  15. #[cfg(feature = "query_encoding")]
  16. #[derive(Copy, Clone)]
  17. pub struct EncodingOverride {
  18. /// `None` means UTF-8.
  19. encoding: Option<EncodingRef>
  20. }
  21. #[cfg(feature = "query_encoding")]
  22. impl EncodingOverride {
  23. pub fn from_opt_encoding(encoding: Option<EncodingRef>) -> Self {
  24. encoding.map(Self::from_encoding).unwrap_or_else(Self::utf8)
  25. }
  26. pub fn from_encoding(encoding: EncodingRef) -> Self {
  27. EncodingOverride {
  28. encoding: if encoding.name() == "utf-8" { None } else { Some(encoding) }
  29. }
  30. }
  31. #[inline]
  32. pub fn utf8() -> Self {
  33. EncodingOverride { encoding: None }
  34. }
  35. pub fn lookup(label: &[u8]) -> Option<Self> {
  36. // Don't use String::from_utf8_lossy since no encoding label contains U+FFFD
  37. // https://encoding.spec.whatwg.org/#names-and-labels
  38. ::std::str::from_utf8(label)
  39. .ok()
  40. .and_then(encoding_from_whatwg_label)
  41. .map(Self::from_encoding)
  42. }
  43. /// https://encoding.spec.whatwg.org/#get-an-output-encoding
  44. pub fn to_output_encoding(self) -> Self {
  45. if let Some(encoding) = self.encoding {
  46. if matches!(encoding.name(), "utf-16le" | "utf-16be") {
  47. return Self::utf8()
  48. }
  49. }
  50. self
  51. }
  52. pub fn is_utf8(&self) -> bool {
  53. self.encoding.is_none()
  54. }
  55. pub fn name(&self) -> &'static str {
  56. match self.encoding {
  57. Some(encoding) => encoding.name(),
  58. None => "utf-8",
  59. }
  60. }
  61. pub fn decode<'a>(&self, input: Cow<'a, [u8]>) -> Cow<'a, str> {
  62. match self.encoding {
  63. // `encoding.decode` never returns `Err` when called with `DecoderTrap::Replace`
  64. Some(encoding) => encoding.decode(&input, DecoderTrap::Replace).unwrap().into(),
  65. None => decode_utf8_lossy(input),
  66. }
  67. }
  68. pub fn encode<'a>(&self, input: Cow<'a, str>) -> Cow<'a, [u8]> {
  69. match self.encoding {
  70. // `encoding.encode` never returns `Err` when called with `EncoderTrap::NcrEscape`
  71. Some(encoding) => Cow::Owned(encoding.encode(&input, EncoderTrap::NcrEscape).unwrap()),
  72. None => encode_utf8(input)
  73. }
  74. }
  75. }
  76. #[cfg(not(feature = "query_encoding"))]
  77. #[derive(Copy, Clone)]
  78. pub struct EncodingOverride;
  79. #[cfg(not(feature = "query_encoding"))]
  80. impl EncodingOverride {
  81. #[inline]
  82. pub fn utf8() -> Self {
  83. EncodingOverride
  84. }
  85. pub fn decode<'a>(&self, input: Cow<'a, [u8]>) -> Cow<'a, str> {
  86. decode_utf8_lossy(input)
  87. }
  88. pub fn encode<'a>(&self, input: Cow<'a, str>) -> Cow<'a, [u8]> {
  89. encode_utf8(input)
  90. }
  91. }
  92. pub fn decode_utf8_lossy(input: Cow<[u8]>) -> Cow<str> {
  93. match input {
  94. Cow::Borrowed(bytes) => String::from_utf8_lossy(bytes),
  95. Cow::Owned(bytes) => {
  96. let raw_utf8: *const [u8];
  97. match String::from_utf8_lossy(&bytes) {
  98. Cow::Borrowed(utf8) => raw_utf8 = utf8.as_bytes(),
  99. Cow::Owned(s) => return s.into(),
  100. }
  101. // from_utf8_lossy returned a borrow of `bytes` unchanged.
  102. debug_assert!(raw_utf8 == &*bytes as *const [u8]);
  103. // Reuse the existing `Vec` allocation.
  104. unsafe { String::from_utf8_unchecked(bytes) }.into()
  105. }
  106. }
  107. }
  108. pub fn encode_utf8(input: Cow<str>) -> Cow<[u8]> {
  109. match input {
  110. Cow::Borrowed(s) => Cow::Borrowed(s.as_bytes()),
  111. Cow::Owned(s) => Cow::Owned(s.into_bytes())
  112. }
  113. }