Bug 1369020 - Remove nsContentUtils::ConvertStringFromEncoding and nsContentUtils::CheckForBOM. r=hsivonen
authorMasatoshi Kimura <VYV03354@nifty.ne.jp>
Fri, 16 Jun 2017 21:11:03 +0900
changeset 364545 8587375461d5d7f26895f81746ed0ce3dffc430c
parent 364544 b98d481de3b46fed52d4e0b2b12a6238068de2a4
child 364546 6e0dd372f23d2f0856ae6c98118cdcf59abd5617
push id32047
push userarchaeopteryx@coole-files.de
push dateSun, 18 Jun 2017 18:28:16 +0000
treeherdermozilla-central@ae20db43e815 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewershsivonen
bugs1369020
milestone56.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1369020 - Remove nsContentUtils::ConvertStringFromEncoding and nsContentUtils::CheckForBOM. r=hsivonen MozReview-Commit-ID: E0w8BsP1Rof
dom/base/nsContentUtils.cpp
dom/base/nsContentUtils.h
dom/base/nsDocument.cpp
dom/base/nsReferencedElement.cpp
dom/file/FileReader.cpp
dom/html/nsHTMLDocument.cpp
dom/indexedDB/ActorsChild.cpp
dom/media/eme/MediaKeySession.cpp
dom/workers/FileReaderSync.cpp
layout/style/Loader.cpp
parser/htmlparser/nsParser.cpp
--- a/dom/base/nsContentUtils.cpp
+++ b/dom/base/nsContentUtils.cpp
@@ -4493,55 +4493,16 @@ nsContentUtils::GetSubdocumentWithOuterW
     // Note that ContentIsCrossDocDescendantOf will return true if
     // foundDoc == aDocument.
     return foundDoc;
   }
 
   return nullptr;
 }
 
-// Convert the string from the given encoding to Unicode.
-/* static */
-nsresult
-nsContentUtils::ConvertStringFromEncoding(const nsACString& aEncoding,
-                                          const char* aInput,
-                                          uint32_t aInputLen,
-                                          nsAString& aOutput)
-{
-  const Encoding* encoding;
-  if (aEncoding.IsEmpty()) {
-    encoding = UTF_8_ENCODING;
-  } else {
-    encoding = Encoding::ForName(aEncoding);
-  }
-  nsresult rv = encoding->DecodeWithBOMRemoval(MakeSpan(reinterpret_cast<const uint8_t*>(aInput), aInputLen), aOutput);
-  if (NS_FAILED(rv)) {
-    return rv;
-  }
-  return NS_OK;
-}
-
-/* static */
-bool
-nsContentUtils::CheckForBOM(const unsigned char* aBuffer, uint32_t aLength,
-                            nsACString& aCharset)
-{
-  auto span = MakeSpan(reinterpret_cast<const uint8_t*>(aBuffer), aLength);
-  const Encoding* encoding;
-  size_t bomLength;
-  Tie(encoding, bomLength) = Encoding::ForBOM(span);
-  Unused << bomLength;
-  if (!encoding) {
-    aCharset.Truncate();
-    return false;
-  }
-  encoding->Name(aCharset);
-  return true;
-}
-
 /* static */
 void
 nsContentUtils::RegisterShutdownObserver(nsIObserver* aObserver)
 {
   nsCOMPtr<nsIObserverService> observerService =
     mozilla::services::GetObserverService();
   if (observerService) {
     observerService->AddObserver(aObserver,
--- a/dom/base/nsContentUtils.h
+++ b/dom/base/nsContentUtils.h
@@ -614,52 +614,16 @@ public:
    * aDocument.
    */
   static nsresult NewURIWithDocumentCharset(nsIURI** aResult,
                                             const nsAString& aSpec,
                                             nsIDocument* aDocument,
                                             nsIURI* aBaseURI);
 
   /**
-   * Convert aInput (in encoding aEncoding) to UTF16 in aOutput.
-   *
-   * @deprecated Use mozilla::Encoding::DecodeWithBOMRemoval() in new code.
-   * https://bugzilla.mozilla.org/show_bug.cgi?id=1369020
-   *
-   * @param aEncoding the Gecko-canonical name of the encoding or the empty
-   *                  string (meaning UTF-8)
-   */
-  static nsresult ConvertStringFromEncoding(const nsACString& aEncoding,
-                                            const char* aInput,
-                                            uint32_t aInputLen,
-                                            nsAString& aOutput);
-
-  static nsresult ConvertStringFromEncoding(const nsACString& aEncoding,
-                                            const nsACString& aInput,
-                                            nsAString& aOutput) {
-    return ConvertStringFromEncoding(
-        aEncoding, aInput.BeginReading(), aInput.Length(), aOutput);
-  }
-
-  /**
-   * Determine whether a buffer begins with a BOM for UTF-8, UTF-16LE,
-   * UTF-16BE
-   *
-   * @deprecated Use mozilla::Encoding::ForBOM() in new code.
-   * https://bugzilla.mozilla.org/show_bug.cgi?id=1369022
-   *
-   * @param aBuffer the buffer to check
-   * @param aLength the length of the buffer
-   * @param aCharset empty if not found
-   * @return boolean indicating whether a BOM was detected.
-   */
-  static bool CheckForBOM(const unsigned char* aBuffer, uint32_t aLength,
-                          nsACString& aCharset);
-
-  /**
    * Returns true if |aName| is a valid name to be registered via
    * document.registerElement.
    */
   static bool IsCustomElementName(nsIAtom* aName);
 
   static nsresult CheckQName(const nsAString& aQualifiedName,
                              bool aNamespaceAware = true,
                              const char16_t** aColon = nullptr);
--- a/dom/base/nsDocument.cpp
+++ b/dom/base/nsDocument.cpp
@@ -169,17 +169,17 @@
 #include "mozilla/dom/HTMLMediaElement.h"
 #include "mozilla/dom/HTMLIFrameElement.h"
 #include "mozilla/dom/HTMLImageElement.h"
 #include "mozilla/dom/MediaSource.h"
 #include "mozilla/dom/FlyWebService.h"
 
 #include "mozAutoDocUpdate.h"
 #include "nsGlobalWindow.h"
-#include "mozilla/dom/EncodingUtils.h"
+#include "mozilla/Encoding.h"
 #include "nsDOMNavigationTiming.h"
 
 #include "nsSMILAnimationController.h"
 #include "imgIContainer.h"
 #include "nsSVGUtils.h"
 
 #include "nsRefreshDriver.h"
 
@@ -3839,19 +3839,19 @@ nsDocument::TryChannelCharset(nsIChannel
                               int32_t& aCharsetSource,
                               nsACString& aCharset,
                               nsHtml5TreeOpExecutor* aExecutor)
 {
   if (aChannel) {
     nsAutoCString charsetVal;
     nsresult rv = aChannel->GetContentCharset(charsetVal);
     if (NS_SUCCEEDED(rv)) {
-      nsAutoCString preferred;
-      if(EncodingUtils::FindEncodingForLabel(charsetVal, preferred)) {
-        aCharset = preferred;
+      const Encoding* preferred = Encoding::ForLabel(charsetVal);
+      if (preferred) {
+        preferred->Name(aCharset);
         aCharsetSource = kCharsetFromChannel;
         return;
       } else if (aExecutor && !charsetVal.IsEmpty()) {
         aExecutor->ComplainAboutBogusProtocolCharset(this);
       }
     }
   }
 }
@@ -9925,20 +9925,19 @@ nsDocument::ScrollToRef()
       rv = NS_ERROR_FAILURE;
     }
 
     // If UTF-8 URI failed then try to assume the string as a
     // document's charset.
 
     if (NS_FAILED(rv)) {
       const nsACString &docCharset = GetDocumentCharacterSet();
-
-      rv = nsContentUtils::ConvertStringFromEncoding(docCharset,
-                                                     unescapedRef,
-                                                     ref);
+      const Encoding* encoding = Encoding::ForName(docCharset);
+
+      rv = encoding->DecodeWithoutBOMHandling(unescapedRef, ref);
 
       if (NS_SUCCEEDED(rv) && !ref.IsEmpty()) {
         rv = shell->GoToAnchor(ref, mChangeScrollPosWhenScrollingToRef);
       }
     }
     if (NS_SUCCEEDED(rv)) {
       mScrolledToRefAlready = true;
     }
--- a/dom/base/nsReferencedElement.cpp
+++ b/dom/base/nsReferencedElement.cpp
@@ -28,23 +28,24 @@ nsReferencedElement::Reset(nsIContent* a
   nsAutoCString refPart;
   aURI->GetRef(refPart);
   // Unescape %-escapes in the reference. The result will be in the
   // origin charset of the URL, hopefully...
   NS_UnescapeURL(refPart);
 
   nsAutoCString charset;
   aURI->GetOriginCharset(charset);
+  const Encoding* encoding = charset.IsEmpty() ?
+    UTF_8_ENCODING : Encoding::ForName(charset);
   nsAutoString ref;
-  nsresult rv = nsContentUtils::ConvertStringFromEncoding(charset,
-                                                          refPart,
-                                                          ref);
+  nsresult rv = encoding->DecodeWithoutBOMHandling(refPart, ref);
   if (NS_FAILED(rv) || ref.IsEmpty()) {
     return;
   }
+  rv = NS_OK;
 
   // Get the current document
   nsIDocument *doc = aFromContent->OwnerDoc();
   if (!doc)
     return;
 
   nsIContent* bindingParent = aFromContent->GetBindingParent();
   if (bindingParent) {
--- a/dom/file/FileReader.cpp
+++ b/dom/file/FileReader.cpp
@@ -10,21 +10,20 @@
 #include "nsIGlobalObject.h"
 #include "nsITimer.h"
 #include "nsITransport.h"
 #include "nsIStreamTransportService.h"
 
 #include "mozilla/Base64.h"
 #include "mozilla/CheckedInt.h"
 #include "mozilla/dom/DOMError.h"
-#include "mozilla/dom/EncodingUtils.h"
 #include "mozilla/dom/File.h"
 #include "mozilla/dom/FileReaderBinding.h"
 #include "mozilla/dom/ProgressEvent.h"
-#include "nsContentUtils.h"
+#include "mozilla/Encoding.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsDOMJSUtils.h"
 #include "nsError.h"
 #include "nsNetCID.h"
 #include "nsNetUtil.h"
 #include "xpcpublic.h"
 
 #include "WorkerPrivate.h"
@@ -446,47 +445,43 @@ FileReader::ReadFileContent(Blob& aBlob,
 
 nsresult
 FileReader::GetAsText(Blob *aBlob,
                       const nsACString &aCharset,
                       const char *aFileData,
                       uint32_t aDataLen,
                       nsAString& aResult)
 {
-  // The BOM sniffing is baked into the "decode" part of the Encoding
-  // Standard, which the File API references.
-  nsAutoCString encoding;
-  if (!nsContentUtils::CheckForBOM(
-        reinterpret_cast<const unsigned char *>(aFileData),
-        aDataLen,
-        encoding)) {
-    // BOM sniffing failed. Try the API argument.
-    if (!EncodingUtils::FindEncodingForLabel(aCharset,
-                                             encoding)) {
-      // API argument failed. Try the type property of the blob.
-      nsAutoString type16;
-      aBlob->GetType(type16);
-      NS_ConvertUTF16toUTF8 type(type16);
-      nsAutoCString specifiedCharset;
-      bool haveCharset;
-      int32_t charsetStart, charsetEnd;
-      NS_ExtractCharsetFromContentType(type,
-                                       specifiedCharset,
-                                       &haveCharset,
-                                       &charsetStart,
-                                       &charsetEnd);
-      if (!EncodingUtils::FindEncodingForLabel(specifiedCharset, encoding)) {
-        // Type property failed. Use UTF-8.
-        encoding.AssignLiteral("UTF-8");
-      }
+  // Try the API argument.
+  const Encoding* encoding = Encoding::ForLabel(aCharset);
+  if (!encoding) {
+    // API argument failed. Try the type property of the blob.
+    nsAutoString type16;
+    aBlob->GetType(type16);
+    NS_ConvertUTF16toUTF8 type(type16);
+    nsAutoCString specifiedCharset;
+    bool haveCharset;
+    int32_t charsetStart, charsetEnd;
+    NS_ExtractCharsetFromContentType(type,
+                                     specifiedCharset,
+                                     &haveCharset,
+                                     &charsetStart,
+                                     &charsetEnd);
+    encoding = Encoding::ForLabel(specifiedCharset);
+    if (!encoding) {
+      // Type property failed. Use UTF-8.
+      encoding = UTF_8_ENCODING;
     }
   }
 
-  return nsContentUtils::ConvertStringFromEncoding(
-      encoding, aFileData, aDataLen, aResult);
+  auto data = MakeSpan(reinterpret_cast<const uint8_t*>(aFileData),
+                       aDataLen);
+  nsresult rv;
+  Tie(rv, encoding) = encoding->Decode(data, aResult);
+  return NS_FAILED(rv) ? rv : NS_OK;
 }
 
 nsresult
 FileReader::GetAsDataURL(Blob *aBlob,
                          const char *aFileData,
                          uint32_t aDataLen,
                          nsAString& aResult)
 {
--- a/dom/html/nsHTMLDocument.cpp
+++ b/dom/html/nsHTMLDocument.cpp
@@ -79,16 +79,17 @@
 #include "nsArrayUtils.h"
 #include "nsIEffectiveTLDService.h"
 
 //AHMED 12-2
 #include "nsBidiUtils.h"
 
 #include "mozilla/dom/EncodingUtils.h"
 #include "mozilla/dom/FallbackEncoding.h"
+#include "mozilla/Encoding.h"
 #include "mozilla/LoadInfo.h"
 #include "nsIEditingSession.h"
 #include "nsIEditor.h"
 #include "nsNodeInfoManager.h"
 #include "nsIPlaintextEditor.h"
 #include "nsIHTMLEditor.h"
 #include "nsIEditorStyleSheets.h"
 #include "nsIInlineSpellChecker.h"
@@ -1353,18 +1354,17 @@ nsHTMLDocument::GetCookie(nsAString& aCo
         return;
       }
     }
 
     nsXPIDLCString cookie;
     service->GetCookieString(codebaseURI, channel, getter_Copies(cookie));
     // CopyUTF8toUTF16 doesn't handle error
     // because it assumes that the input is valid.
-    nsContentUtils::ConvertStringFromEncoding(NS_LITERAL_CSTRING("UTF-8"),
-                                              cookie, aCookie);
+    UTF_8_ENCODING->DecodeWithoutBOMHandling(cookie, aCookie);
   }
 }
 
 NS_IMETHODIMP
 nsHTMLDocument::SetCookie(const nsAString& aCookie)
 {
   ErrorResult rv;
   SetCookie(aCookie, rv);
--- a/dom/indexedDB/ActorsChild.cpp
+++ b/dom/indexedDB/ActorsChild.cpp
@@ -19,23 +19,23 @@
 #include "IDBTransaction.h"
 #include "IndexedDatabase.h"
 #include "IndexedDatabaseInlines.h"
 #include "mozilla/BasicEvents.h"
 #include "mozilla/CycleCollectedJSRuntime.h"
 #include "mozilla/Maybe.h"
 #include "mozilla/TypeTraits.h"
 #include "mozilla/dom/Element.h"
-#include "mozilla/dom/EncodingUtils.h"
 #include "mozilla/dom/PermissionMessageUtils.h"
 #include "mozilla/dom/TabChild.h"
 #include "mozilla/dom/indexedDB/PBackgroundIDBDatabaseFileChild.h"
 #include "mozilla/dom/indexedDB/PIndexedDBPermissionRequestChild.h"
 #include "mozilla/dom/ipc/PendingIPCBlobChild.h"
 #include "mozilla/dom/IPCBlobUtils.h"
+#include "mozilla/Encoding.h"
 #include "mozilla/ipc/BackgroundUtils.h"
 #include "mozilla/TaskQueue.h"
 #include "nsCOMPtr.h"
 #include "nsContentUtils.h"
 #include "nsIAsyncInputStream.h"
 #include "nsIBFCacheEntry.h"
 #include "nsIDocument.h"
 #include "nsIDOMEvent.h"
@@ -1325,38 +1325,32 @@ private:
       if (NS_WARN_IF(NS_FAILED(rv))) {
         return NS_ERROR_DOM_FILEHANDLE_UNKNOWN_ERR;
       }
 
       aResult.setObject(*arrayBuffer);
       return NS_OK;
     }
 
-    nsAutoCString encoding;
-    // The BOM sniffing is baked into the "decode" part of the Encoding
-    // Standard, which the File API references.
-    if (!nsContentUtils::CheckForBOM(
-          reinterpret_cast<const unsigned char *>(data.get()),
-          data.Length(),
-          encoding)) {
-      // BOM sniffing failed. Try the API argument.
-      if (!EncodingUtils::FindEncodingForLabel(mFileRequest->GetEncoding(),
-                                               encoding)) {
-        // API argument failed. Since we are dealing with a file system file,
-        // we don't have a meaningful type attribute for the blob available,
-        // so proceeding to the next step, which is defaulting to UTF-8.
-        encoding.AssignLiteral("UTF-8");
-      }
+    // Try the API argument.
+    const Encoding* encoding =
+      Encoding::ForLabel(mFileRequest->GetEncoding());
+    if (!encoding) {
+      // API argument failed. Since we are dealing with a file system file,
+      // we don't have a meaningful type attribute for the blob available,
+      // so proceeding to the next step, which is defaulting to UTF-8.
+      encoding = UTF_8_ENCODING;
     }
 
     nsString tmpString;
-    rv = nsContentUtils::ConvertStringFromEncoding(encoding, data, tmpString);
+    Tie(rv, encoding) = encoding->Decode(data, tmpString);
     if (NS_WARN_IF(NS_FAILED(rv))) {
       return NS_ERROR_DOM_FILEHANDLE_UNKNOWN_ERR;
     }
+    rv = NS_OK;
 
     if (NS_WARN_IF(!xpc::StringToJsval(aCx, tmpString, aResult))) {
       return NS_ERROR_DOM_FILEHANDLE_UNKNOWN_ERR;
     }
 
     return NS_OK;
   }
 
--- a/dom/media/eme/MediaKeySession.cpp
+++ b/dom/media/eme/MediaKeySession.cpp
@@ -11,18 +11,18 @@
 #include "mozilla/dom/MediaEncryptedEvent.h"
 #include "mozilla/dom/MediaKeyStatusMap.h"
 #include "mozilla/dom/MediaKeySystemAccess.h"
 #include "mozilla/dom/KeyIdsInitDataBinding.h"
 #include "nsCycleCollectionParticipant.h"
 #include "mozilla/CDMProxy.h"
 #include "mozilla/AsyncEventDispatcher.h"
 #include "mozilla/Move.h"
-#include "nsContentUtils.h"
 #include "mozilla/EMEUtils.h"
+#include "mozilla/Encoding.h"
 #include "GMPUtils.h"
 #include "nsPrintfCString.h"
 #include "psshparser/PsshParser.h"
 #include <ctime>
 
 namespace mozilla {
 namespace dom {
 
@@ -192,17 +192,17 @@ ValidateInitData(const nsTArray<uint8_t>
   } else if (aInitDataType.LowerCaseEqualsLiteral("keyids")) {
     if (aInitData.Length() > MAX_KEY_ID_LENGTH) {
       return false;
     }
     // Ensure that init data matches the expected JSON format.
     mozilla::dom::KeyIdsInitData keyIds;
     nsString json;
     nsDependentCSubstring raw(reinterpret_cast<const char*>(aInitData.Elements()), aInitData.Length());
-    if (NS_FAILED(nsContentUtils::ConvertStringFromEncoding(NS_LITERAL_CSTRING("UTF-8"), raw, json))) {
+    if (NS_FAILED(UTF_8_ENCODING->DecodeWithBOMRemoval(raw, json))) {
       return false;
     }
     if (!keyIds.Init(json)) {
       return false;
     }
     if (keyIds.mKids.Length() == 0) {
       return false;
     }
--- a/dom/workers/FileReaderSync.cpp
+++ b/dom/workers/FileReaderSync.cpp
@@ -4,19 +4,18 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "FileReaderSync.h"
 
 #include "jsfriendapi.h"
 #include "mozilla/Unused.h"
 #include "mozilla/Base64.h"
-#include "mozilla/dom/EncodingUtils.h"
 #include "mozilla/dom/File.h"
-#include "nsContentUtils.h"
+#include "mozilla/Encoding.h"
 #include "mozilla/dom/FileReaderSyncBinding.h"
 #include "nsCExternalHandlerService.h"
 #include "nsComponentManagerUtils.h"
 #include "nsCOMPtr.h"
 #include "nsDOMClassInfoID.h"
 #include "nsError.h"
 #include "nsIConverterInputStream.h"
 #include "nsIInputStream.h"
@@ -137,18 +136,16 @@ FileReaderSync::ReadAsText(Blob& aBlob,
                            ErrorResult& aRv)
 {
   nsCOMPtr<nsIInputStream> stream;
   aBlob.GetInternalStream(getter_AddRefs(stream), aRv);
   if (NS_WARN_IF(aRv.Failed())) {
     return;
   }
 
-  nsAutoCString encoding;
-
   nsCString sniffBuf;
   if (!sniffBuf.SetLength(3, fallible)) {
     aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
     return;
   }
 
   uint32_t numRead = 0;
   aRv = SyncRead(stream, sniffBuf.BeginWriting(), sniffBuf.Length(), &numRead);
@@ -157,40 +154,36 @@ FileReaderSync::ReadAsText(Blob& aBlob,
   }
 
   // No data, we don't need to continue.
   if (numRead == 0) {
     aResult.Truncate();
     return;
   }
 
-  // The BOM sniffing is baked into the "decode" part of the Encoding
-  // Standard, which the File API references.
-  if (!nsContentUtils::CheckForBOM((const unsigned char*)sniffBuf.BeginReading(),
-                                   numRead, encoding)) {
-    // BOM sniffing failed. Try the API argument.
-    if (!aEncoding.WasPassed() ||
-        !EncodingUtils::FindEncodingForLabel(aEncoding.Value(),
-                                             encoding)) {
-      // API argument failed. Try the type property of the blob.
-      nsAutoString type16;
-      aBlob.GetType(type16);
-      NS_ConvertUTF16toUTF8 type(type16);
-      nsAutoCString specifiedCharset;
-      bool haveCharset;
-      int32_t charsetStart, charsetEnd;
-      NS_ExtractCharsetFromContentType(type,
-                                       specifiedCharset,
-                                       &haveCharset,
-                                       &charsetStart,
-                                       &charsetEnd);
-      if (!EncodingUtils::FindEncodingForLabel(specifiedCharset, encoding)) {
-        // Type property failed. Use UTF-8.
-        encoding.AssignLiteral("UTF-8");
-      }
+  // Try the API argument.
+  const Encoding* encoding = aEncoding.WasPassed() ?
+    Encoding::ForLabel(aEncoding.Value()) : nullptr;
+  if (!encoding) {
+    // API argument failed. Try the type property of the blob.
+    nsAutoString type16;
+    aBlob.GetType(type16);
+    NS_ConvertUTF16toUTF8 type(type16);
+    nsAutoCString specifiedCharset;
+    bool haveCharset;
+    int32_t charsetStart, charsetEnd;
+    NS_ExtractCharsetFromContentType(type,
+                                     specifiedCharset,
+                                     &haveCharset,
+                                     &charsetStart,
+                                     &charsetEnd);
+    encoding = Encoding::ForLabel(specifiedCharset);
+    if (!encoding) {
+      // Type property failed. Use UTF-8.
+      encoding = UTF_8_ENCODING;
     }
   }
 
   if (numRead < sniffBuf.Length()) {
     sniffBuf.Truncate(numRead);
   }
 
   // Let's recreate the full stream using a:
@@ -226,17 +219,19 @@ FileReaderSync::ReadAsText(Blob& aBlob,
   // already closed or there is nothing to read.
   if (syncStream) {
     aRv = multiplexStream->AppendStream(syncStream);
     if (NS_WARN_IF(aRv.Failed())) {
       return;
     }
   }
 
-  aRv = ConvertStream(multiplexStream, encoding.get(), aResult);
+  nsAutoCString charset;
+  encoding->Name(charset);
+  aRv = ConvertStream(multiplexStream, charset.get(), aResult);
   if (NS_WARN_IF(aRv.Failed())) {
     return;
   }
 }
 
 void
 FileReaderSync::ReadAsDataURL(Blob& aBlob, nsAString& aResult,
                               ErrorResult& aRv)
--- a/layout/style/Loader.cpp
+++ b/layout/style/Loader.cpp
@@ -68,18 +68,17 @@
 #endif
 
 #include "nsIDOMStyleSheet.h"
 #include "nsError.h"
 
 #include "nsIContentSecurityPolicy.h"
 #include "mozilla/dom/SRICheck.h"
 
-#include "mozilla/dom/EncodingUtils.h"
-using mozilla::dom::EncodingUtils;
+#include "mozilla/Encoding.h"
 
 using namespace mozilla::dom;
 
 /**
  * OVERALL ARCHITECTURE
  *
  * The CSS Loader gets requests to load various sorts of style sheets:
  * inline style from <style> elements, linked style, @import-ed child
@@ -671,44 +670,51 @@ SheetLoadData::OnDetermineCharset(nsIUni
   // Channel
   // @charset rule
   // charset attribute on the referrer
   // encoding of the referrer
   // UTF-8
 
   aCharset.Truncate();
 
-  if (nsContentUtils::CheckForBOM((const unsigned char*)aSegment.BeginReading(),
-                                  aSegment.Length(),
-                                  aCharset)) {
+  const Encoding* encoding;
+  size_t bomLength;
+  Tie(encoding, bomLength) = Encoding::ForBOM(aSegment);
+  Unused << bomLength;
+  if (encoding) {
+    encoding->Name(aCharset);
     // aCharset is now either "UTF-16BE", "UTF-16BE" or "UTF-8"
     // which will swallow the BOM.
     mCharset.Assign(aCharset);
     LOG(("  Setting from BOM to: %s", PromiseFlatCString(aCharset).get()));
     return NS_OK;
   }
 
   nsCOMPtr<nsIChannel> channel;
   nsAutoCString specified;
   aLoader->GetChannel(getter_AddRefs(channel));
   if (channel) {
     channel->GetContentCharset(specified);
-    if (EncodingUtils::FindEncodingForLabel(specified, aCharset)) {
+    encoding = Encoding::ForLabel(specified);
+    if (encoding) {
+      encoding->Name(aCharset);
       mCharset.Assign(aCharset);
       LOG(("  Setting from HTTP to: %s", PromiseFlatCString(aCharset).get()));
       return NS_OK;
     }
   }
 
   if (GetCharsetFromData(aSegment.BeginReading(),
                          aSegment.Length(),
                          specified)) {
-    if (EncodingUtils::FindEncodingForLabel(specified, aCharset)) {
-      if (aCharset.EqualsLiteral("UTF-16BE") ||
-          aCharset.EqualsLiteral("UTF-16LE")) {
+    encoding = Encoding::ForLabel(specified);
+    if (encoding) {
+      encoding->Name(aCharset);
+      if (encoding == UTF_16BE_ENCODING ||
+          encoding == UTF_16LE_ENCODING) {
         // Be consistent with HTML <meta> handling in face of impossibility.
         // When the @charset rule itself evidently was not UTF-16-encoded,
         // it saying UTF-16 has to be a lie.
         aCharset.AssignLiteral("UTF-8");
       }
       mCharset.Assign(aCharset);
       LOG(("  Setting from @charset rule to: %s",
           PromiseFlatCString(aCharset).get()));
@@ -716,27 +722,31 @@ SheetLoadData::OnDetermineCharset(nsIUni
     }
   }
 
   // Now try the charset on the <link> or processing instruction
   // that loaded us
   if (mOwningElement) {
     nsAutoString specified16;
     mOwningElement->GetCharset(specified16);
-    if (EncodingUtils::FindEncodingForLabel(specified16, aCharset)) {
+    encoding = Encoding::ForLabel(specified16);
+    if (encoding) {
+      encoding->Name(aCharset);
       mCharset.Assign(aCharset);
       LOG(("  Setting from charset attribute to: %s",
           PromiseFlatCString(aCharset).get()));
       return NS_OK;
     }
   }
 
   // In the preload case, the value of the charset attribute on <link> comes
   // in via mCharsetHint instead.
-  if (EncodingUtils::FindEncodingForLabel(mCharsetHint, aCharset)) {
+  encoding = Encoding::ForLabel(mCharsetHint);
+  if (encoding) {
+    encoding->Name(aCharset);
     mCharset.Assign(aCharset);
       LOG(("  Setting from charset attribute (preload case) to: %s",
           PromiseFlatCString(aCharset).get()));
     return NS_OK;
   }
 
   // Try charset from the parent stylesheet.
   if (mParentData) {
--- a/parser/htmlparser/nsParser.cpp
+++ b/parser/htmlparser/nsParser.cpp
@@ -29,26 +29,24 @@
 #include "nsStreamUtils.h"
 #include "nsHTMLTokenizer.h"
 #include "nsDataHashtable.h"
 #include "nsXPCOMCIDInternal.h"
 #include "nsMimeTypes.h"
 #include "mozilla/CondVar.h"
 #include "mozilla/Mutex.h"
 #include "nsCharsetSource.h"
-#include "nsContentUtils.h"
 #include "nsThreadUtils.h"
 #include "nsIHTMLContentSink.h"
 
-#include "mozilla/dom/EncodingUtils.h"
+#include "mozilla/BinarySearch.h"
 #include "mozilla/dom/ScriptLoader.h"
-#include "mozilla/BinarySearch.h"
+#include "mozilla/Encoding.h"
 
 using namespace mozilla;
-using mozilla::dom::EncodingUtils;
 
 #define NS_PARSER_FLAG_OBSERVERS_ENABLED      0x00000004
 #define NS_PARSER_FLAG_PENDING_CONTINUE_EVENT 0x00000008
 #define NS_PARSER_FLAG_FLUSH_TOKENS           0x00000020
 #define NS_PARSER_FLAG_CAN_TOKENIZE           0x00000040
 
 //-------------- Begin ParseContinue Event Definition ------------------------
 /*
@@ -1329,33 +1327,37 @@ ParserWriteFunc(nsIInputStream* in,
   if (!pws) {
     return NS_ERROR_FAILURE;
   }
 
   if (pws->mNeedCharsetCheck) {
     pws->mNeedCharsetCheck = false;
     int32_t source;
     nsAutoCString preferred;
-    nsAutoCString maybePrefer;
     pws->mParser->GetDocumentCharset(preferred, source);
 
     // This code was bogus when I found it. It expects the BOM or the XML
     // declaration to be entirely in the first network buffer. -- hsivonen
-    if (nsContentUtils::CheckForBOM(buf, count, maybePrefer)) {
+    const Encoding* encoding;
+    size_t bomLength;
+    Tie(encoding, bomLength) = Encoding::ForBOM(MakeSpan(buf, count));
+    Unused << bomLength;
+    if (encoding) {
       // The decoder will swallow the BOM. The UTF-16 will re-sniff for
       // endianness. The value of preferred is now "UTF-8", "UTF-16LE"
       // or "UTF-16BE".
-      preferred.Assign(maybePrefer);
+      encoding->Name(preferred);
       source = kCharsetFromByteOrderMark;
     } else if (source < kCharsetFromChannel) {
       nsAutoCString declCharset;
 
       if (ExtractCharsetFromXmlDeclaration(buf, count, declCharset)) {
-        if (EncodingUtils::FindEncodingForLabel(declCharset, maybePrefer)) {
-          preferred.Assign(maybePrefer);
+        encoding = Encoding::ForLabel(declCharset);
+        if (encoding) {
+          encoding->Name(preferred);
           source = kCharsetFromMetaTag;
         }
       }
     }
 
     pws->mParser->SetDocumentCharset(preferred, source);
     pws->mParser->SetSinkCharset(preferred);