Bug 1369025 - Remove mozilla::dom::EncodingUtils. r?hsivonen draft
authorMasatoshi Kimura <VYV03354@nifty.ne.jp>
Sat, 17 Jun 2017 11:54:40 +0900
changeset 596007 e99d875e0fe86e7723625ea0761e81c838494f69
parent 595926 3afbb85d76fd348326d699239f6c08e0710421d9
child 633842 0e1079617663b61839a8f6f0f2b230b53b62860f
push id64493
push userVYV03354@nifty.ne.jp
push dateSat, 17 Jun 2017 09:23:29 +0000
reviewershsivonen
bugs1369025
milestone56.0a1
Bug 1369025 - Remove mozilla::dom::EncodingUtils. r?hsivonen MozReview-Commit-ID: 5O5WtxbmATQ
docshell/base/nsDocShell.cpp
dom/base/nsDocumentEncoder.cpp
dom/encoding/EncodingUtils.cpp
dom/encoding/EncodingUtils.h
dom/encoding/FallbackEncoding.cpp
dom/encoding/TextDecoder.cpp
dom/encoding/TextDecoder.h
dom/encoding/encodingsgroups.properties
dom/encoding/moz.build
dom/fetch/BodyExtractor.cpp
dom/html/HTMLFormSubmission.cpp
dom/html/nsHTMLDocument.cpp
dom/script/ScriptLoader.cpp
dom/workers/ServiceWorkerEvents.cpp
dom/xhr/XMLHttpRequestMainThread.cpp
dom/xslt/xslt/txMozillaStylesheetCompiler.cpp
dom/xslt/xslt/txMozillaTextOutput.cpp
dom/xslt/xslt/txMozillaXMLOutput.cpp
gfx/thebes/gfxFontUtils.cpp
intl/locale/encodingsgroups.properties
intl/locale/moz.build
intl/locale/nsLanguageAtomService.cpp
intl/locale/unix/nsUNIXCharset.cpp
layout/base/nsDocumentViewer.cpp
netwerk/base/nsUnicharStreamLoader.cpp
netwerk/mime/nsMIMEHeaderParamImpl.cpp
netwerk/streamconv/converters/nsIndexedToHTML.cpp
parser/html/nsHtml5MetaScannerCppSupplement.h
parser/html/nsHtml5StreamParser.cpp
parser/htmlparser/nsScanner.cpp
parser/xml/nsSAXXMLReader.cpp
toolkit/components/osfile/NativeOSFileInternals.cpp
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -210,19 +210,19 @@
 #include "nsISecureBrowserUI.h"
 #include "nsISocketProvider.h"
 #include "nsIStringBundle.h"
 #include "nsIURIFixup.h"
 #include "nsIURILoader.h"
 #include "nsIURL.h"
 #include "nsIWebBrowserFind.h"
 #include "nsIWidget.h"
-#include "mozilla/dom/EncodingUtils.h"
 #include "mozilla/dom/PerformanceNavigation.h"
 #include "mozilla/dom/ScriptSettings.h"
+#include "mozilla/Encoding.h"
 
 #ifdef MOZ_TOOLKIT_SEARCH
 #include "nsIBrowserSearchService.h"
 #endif
 
 #include "mozIThirdPartyUtil.h"
 
 static NS_DEFINE_CID(kAppShellCID, NS_APPSHELL_CID);
@@ -2111,26 +2111,26 @@ nsDocShell::SetCharset(const nsACString&
 
 NS_IMETHODIMP
 nsDocShell::SetForcedCharset(const nsACString& aCharset)
 {
   if (aCharset.IsEmpty()) {
     mForcedCharset.Truncate();
     return NS_OK;
   }
-  nsAutoCString encoding;
-  if (!EncodingUtils::FindEncodingForLabel(aCharset, encoding)) {
+  const Encoding* encoding = Encoding::ForLabel(aCharset);
+  if (!encoding) {
     // Reject unknown labels
     return NS_ERROR_INVALID_ARG;
   }
-  if (!EncodingUtils::IsAsciiCompatible(encoding)) {
+  if (!encoding->IsAsciiCompatible() && encoding != ISO_2022_JP_ENCODING) {
     // Reject XSS hazards
     return NS_ERROR_INVALID_ARG;
   }
-  mForcedCharset = encoding;
+  encoding->Name(mForcedCharset);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDocShell::GetForcedCharset(nsACString& aResult)
 {
   aResult = mForcedCharset;
   return NS_OK;
--- a/dom/base/nsDocumentEncoder.cpp
+++ b/dom/base/nsDocumentEncoder.cpp
@@ -43,17 +43,16 @@
 #include "nsNodeUtils.h"
 #include "nsUnicharUtils.h"
 #include "nsReadableUtils.h"
 #include "nsTArray.h"
 #include "nsIFrame.h"
 #include "nsStringBuffer.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/ShadowRoot.h"
-#include "mozilla/dom/EncodingUtils.h"
 #include "nsLayoutUtils.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 nsresult NS_NewDomSelection(nsISelection **aDomSelection);
 
 enum nsRangeIterationDirection {
deleted file mode 100644
--- a/dom/encoding/EncodingUtils.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * 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 "mozilla/dom/EncodingUtils.h"
-
-#include "mozilla/ArrayUtils.h" // ArrayLength
-#include "nsUConvPropertySearch.h"
-
-namespace mozilla {
-namespace dom {
-
-static constexpr nsUConvProp labelsEncodings[] = {
-#include "labelsencodings.properties.h"
-};
-
-static constexpr nsUConvProp encodingsGroups[] = {
-#include "encodingsgroups.properties.h"
-};
-
-bool
-EncodingUtils::FindEncodingForLabel(const nsACString& aLabel,
-                                    nsACString& aOutEncoding)
-{
-  auto encoding = Encoding::ForLabel(aLabel);
-  if (!encoding) {
-    aOutEncoding.Truncate();
-    return false;
-  }
-  encoding->Name(aOutEncoding);
-  return true;
-}
-
-bool
-EncodingUtils::FindEncodingForLabelNoReplacement(const nsACString& aLabel,
-                                                 nsACString& aOutEncoding)
-{
-  auto encoding = Encoding::ForLabelNoReplacement(aLabel);
-  if (!encoding) {
-    aOutEncoding.Truncate();
-    return false;
-  }
-  encoding->Name(aOutEncoding);
-  return true;
-}
-
-bool
-EncodingUtils::IsAsciiCompatible(const nsACString& aPreferredName)
-{
-  // HZ and UTF-7 are no longer in mozilla-central, but keeping them here
-  // just in case for the benefit of comm-central.
-  return !(aPreferredName.LowerCaseEqualsLiteral("utf-16") ||
-           aPreferredName.LowerCaseEqualsLiteral("utf-16be") ||
-           aPreferredName.LowerCaseEqualsLiteral("utf-16le") ||
-           aPreferredName.LowerCaseEqualsLiteral("replacement") ||
-           aPreferredName.LowerCaseEqualsLiteral("hz-gb-2312") ||
-           aPreferredName.LowerCaseEqualsLiteral("utf-7") ||
-           aPreferredName.LowerCaseEqualsLiteral("x-imap4-modified-utf7"));
-}
-
-UniquePtr<Decoder>
-EncodingUtils::DecoderForEncoding(const nsACString& aEncoding)
-{
-  return Encoding::ForName(aEncoding)->NewDecoderWithBOMRemoval();
-}
-
-UniquePtr<Encoder>
-EncodingUtils::EncoderForEncoding(const nsACString& aEncoding)
-{
-  return Encoding::ForName(aEncoding)->NewEncoder();
-}
-
-void
-EncodingUtils::LangGroupForEncoding(const nsACString& aEncoding,
-                                    nsACString& aOutGroup)
-{
-  if (NS_FAILED(nsUConvPropertySearch::SearchPropertyValue(
-      encodingsGroups, ArrayLength(encodingsGroups), aEncoding, aOutGroup))) {
-    aOutGroup.AssignLiteral("x-unicode");
-  }
-}
-
-} // namespace dom
-} // namespace mozilla
deleted file mode 100644
--- a/dom/encoding/EncodingUtils.h
+++ /dev/null
@@ -1,167 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * 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/. */
-
-#ifndef mozilla_dom_encodingutils_h_
-#define mozilla_dom_encodingutils_h_
-
-#include "nsDataHashtable.h"
-#include "nsString.h"
-#include "mozilla/Encoding.h"
-
-namespace mozilla {
-namespace dom {
-
-class EncodingUtils
-{
-public:
-  /**
-   * Implements get an encoding algorithm from Encoding spec.
-   * http://encoding.spec.whatwg.org/#concept-encoding-get
-   * Given a label, this function returns the corresponding encoding or a
-   * false.
-   * The returned name may not be lowercased due to compatibility with
-   * our internal implementations.
-   *
-   * @deprecated Use mozilla::Encoding::ForLabel() in new code.
-   * https://bugzilla.mozilla.org/show_bug.cgi?id=1369025
-   *
-   * @param      aLabel, incoming label describing charset to be decoded.
-   * @param      aOutEncoding, returning corresponding encoding for label.
-   * @return     false if no encoding was found for label.
-   *             true if valid encoding found.
-   */
-  static bool FindEncodingForLabel(const nsACString& aLabel,
-                                   nsACString& aOutEncoding);
-
-  static bool FindEncodingForLabel(const nsAString& aLabel,
-                                   nsACString& aOutEncoding)
-  {
-    return FindEncodingForLabel(NS_ConvertUTF16toUTF8(aLabel), aOutEncoding);
-  }
-
-  /**
-   * Like FindEncodingForLabel() except labels that map to "replacement"
-   * are treated as unknown.
-   *
-   * @deprecated Use mozilla::Encoding::ForLabelNoReplacement() in new code.
-   * https://bugzilla.mozilla.org/show_bug.cgi?id=1369025
-   *
-   * @param      aLabel, incoming label describing charset to be decoded.
-   * @param      aOutEncoding, returning corresponding encoding for label.
-   * @return     false if no encoding was found for label.
-   *             true if valid encoding found.
-   */
-  static bool FindEncodingForLabelNoReplacement(const nsACString& aLabel,
-                                                nsACString& aOutEncoding);
-
-  static bool FindEncodingForLabelNoReplacement(const nsAString& aLabel,
-                                                nsACString& aOutEncoding)
-  {
-    return FindEncodingForLabelNoReplacement(NS_ConvertUTF16toUTF8(aLabel),
-                                             aOutEncoding);
-  }
-
-  /**
-   * Remove any leading and trailing space characters, following the
-   * definition of space characters from Encoding spec.
-   * http://encoding.spec.whatwg.org/#terminology
-   * Note that nsAString::StripWhitespace() doesn't exactly match the
-   * definition. It also removes all matching chars in the string,
-   * not just leading and trailing.
-   *
-   * @param      aString, string to be trimmed.
-   */
-  template<class T>
-  static void TrimSpaceCharacters(T& aString)
-  {
-    aString.Trim(" \t\n\f\r");
-  }
-
-  /**
-   * Check is the encoding is ASCII-compatible in the sense that Basic Latin
-   * encodes to ASCII bytes. (The reverse may not be true!)
-   *
-   * @param aPreferredName a preferred encoding label
-   * @return whether the encoding is ASCII-compatible
-   */
-  static bool IsAsciiCompatible(const nsACString& aPreferredName);
-
-  /**
-   * Instantiates a decoder for an encoding. The input must be a
-   * Gecko-canonical encoding name.
-   *
-   * @deprecated Use mozilla::Encoding::NewDecoderWithBOMRemoval()
-   *             (or more appropriate variant) in new code.
-   * https://bugzilla.mozilla.org/show_bug.cgi?id=1369032
-   *
-   * @param aEncoding a Gecko-canonical encoding name
-   * @return a decoder
-   */
-  static UniquePtr<Decoder> DecoderForEncoding(const char* aEncoding)
-  {
-    nsDependentCString encoding(aEncoding);
-    return DecoderForEncoding(encoding);
-  }
-
-  /**
-   * Instantiates a decoder for an encoding. The input must be a
-   *
-   * @deprecated Use mozilla::Encoding::NewDecoderWithBOMRemoval()
-   *             (or more appropriate variant) in new code.
-   * https://bugzilla.mozilla.org/show_bug.cgi?id=1369032
-   *
-   * Gecko-canonical encoding name
-   * @param aEncoding a Gecko-canonical encoding name
-   * @return a decoder
-   */
-  static UniquePtr<Decoder> DecoderForEncoding(const nsACString& aEncoding);
-
-  /**
-   * Instantiates an encoder for an encoding. The input must be a
-   *
-   * @deprecated Use mozilla::Encoding::NewEncoder() in new code.
-   * https://bugzilla.mozilla.org/show_bug.cgi?id=1369032
-   *
-   * Gecko-canonical encoding name.
-   * @param aEncoding a Gecko-canonical encoding name
-   * @return an encoder
-   */
-  static UniquePtr<Encoder> EncoderForEncoding(const char* aEncoding)
-  {
-    nsDependentCString encoding(aEncoding);
-    return EncoderForEncoding(encoding);
-  }
-
-  /**
-   * Instantiates an encoder for an encoding. The input must be a
-   * Gecko-canonical encoding name.
-   *
-   * @deprecated Use mozilla::Encoding::NewEncoder() in new code.
-   * https://bugzilla.mozilla.org/show_bug.cgi?id=1369032
-   *
-   * @param aEncoding a Gecko-canonical encoding name
-   * @return an encoder
-   */
-  static UniquePtr<Encoder> EncoderForEncoding(const nsACString& aEncoding);
-
-  /**
-   * Finds a Gecko language group string (e.g. x-western) for a Gecko-canonical
-   * encoding name.
-   *
-   * @param      aEncoding, incoming label describing charset to be decoded.
-   * @param      aOutGroup, returning corresponding language group.
-   */
-  static void LangGroupForEncoding(const nsACString& aEncoding,
-                                   nsACString& aOutGroup);
-
-private:
-  EncodingUtils() = delete;
-};
-
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_encodingutils_h_
--- a/dom/encoding/FallbackEncoding.cpp
+++ b/dom/encoding/FallbackEncoding.cpp
@@ -1,22 +1,22 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * 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 "mozilla/dom/FallbackEncoding.h"
 
-#include "mozilla/dom/EncodingUtils.h"
-#include "nsUConvPropertySearch.h"
+#include "mozilla/Encoding.h"
+#include "mozilla/intl/LocaleService.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Services.h"
 #include "nsIObserverService.h"
-#include "mozilla/intl/LocaleService.h"
+#include "nsUConvPropertySearch.h"
 
 using mozilla::intl::LocaleService;
 
 namespace mozilla {
 namespace dom {
 
 static constexpr nsUConvProp localesFallbacks[] = {
 #include "localesfallbacks.properties.h"
@@ -48,20 +48,22 @@ FallbackEncoding::Get(nsACString& aFallb
     aFallback = mFallback;
     return;
   }
 
   const nsAdoptingCString& override =
     Preferences::GetCString("intl.charset.fallback.override");
   // Don't let the user break things by setting the override to unreasonable
   // values via about:config
-  if (!EncodingUtils::FindEncodingForLabel(override, mFallback) ||
-      !EncodingUtils::IsAsciiCompatible(mFallback) ||
-      mFallback.EqualsLiteral("UTF-8")) {
+  const Encoding* encoding = Encoding::ForLabel(override);
+  if (!encoding || !encoding->IsAsciiCompatible() ||
+      encoding == UTF_8_ENCODING) {
     mFallback.Truncate();
+  } else {
+    encoding->Name(mFallback);
   }
 
   if (!mFallback.IsEmpty()) {
     aFallback = mFallback;
     return;
   }
 
   nsAutoCString locale;
--- a/dom/encoding/TextDecoder.cpp
+++ b/dom/encoding/TextDecoder.cpp
@@ -1,54 +1,55 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * 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 "mozilla/dom/TextDecoder.h"
-#include "mozilla/dom/EncodingUtils.h"
 #include "mozilla/dom/UnionTypes.h"
+#include "mozilla/Encoding.h"
 #include "mozilla/UniquePtrExtensions.h"
 #include "nsContentUtils.h"
 #include <stdint.h>
 
 namespace mozilla {
 namespace dom {
 
 static const char16_t kReplacementChar = static_cast<char16_t>(0xFFFD);
 
 void
 TextDecoder::Init(const nsAString& aLabel, const bool aFatal,
                   ErrorResult& aRv)
 {
-  nsAutoCString encoding;
   // Let encoding be the result of getting an encoding from label.
   // If encoding is failure or replacement, throw a RangeError
   // (https://encoding.spec.whatwg.org/#dom-textdecoder).
-  if (!EncodingUtils::FindEncodingForLabelNoReplacement(aLabel, encoding)) {
+  const Encoding* encoding = Encoding::ForLabelNoReplacement(aLabel);
+  if (!encoding) {
     nsAutoString label(aLabel);
-    EncodingUtils::TrimSpaceCharacters(label);
+    label.Trim(" \t\n\f\r");
     aRv.ThrowRangeError<MSG_ENCODING_NOT_SUPPORTED>(label);
     return;
   }
-  InitWithEncoding(encoding, aFatal);
+  InitWithEncoding(WrapNotNull(encoding), aFatal);
 }
 
 void
-TextDecoder::InitWithEncoding(const nsACString& aEncoding, const bool aFatal)
+TextDecoder::InitWithEncoding(NotNull<const Encoding*> aEncoding,
+                              const bool aFatal)
 {
-  mEncoding = aEncoding;
+  aEncoding->Name(mEncoding);
   // If the constructor is called with an options argument,
   // and the fatal property of the dictionary is set,
   // set the internal fatal flag of the decoder object.
   mFatal = aFatal;
 
   // Create a decoder object for mEncoding.
-  mDecoder = EncodingUtils::DecoderForEncoding(mEncoding);
+  mDecoder = aEncoding->NewDecoderWithBOMRemoval();
 }
 
 void
 TextDecoder::Decode(Span<const uint8_t> aInput,
                     const bool aStream,
                     nsAString& aOutDecodedString,
                     ErrorResult& aRv)
 {
--- a/dom/encoding/TextDecoder.h
+++ b/dom/encoding/TextDecoder.h
@@ -65,21 +65,22 @@ public:
    * @return aRv         EncodingError exception else null.
    */
   void Init(const nsAString& aLabel, const bool aFatal, ErrorResult& aRv);
 
   /**
    * Performs initialization with a Gecko-canonical encoding name (as opposed
    * to a label.)
    *
-   * @param aEncoding    A Gecko-canonical encoding name
+   * @param aEncoding    An Encoding object
    * @param aFatal       indicates whether to throw an 'EncodingError'
    *                     exception or not when decoding.
    */
-  void InitWithEncoding(const nsACString& aEncoding, const bool aFatal);
+  void InitWithEncoding(NotNull<const Encoding*> aEncoding,
+                        const bool aFatal);
 
   /**
    * Return the encoding name.
    *
    * @param aEncoding, current encoding.
    */
   void GetEncoding(nsAString& aEncoding);
 
--- a/dom/encoding/moz.build
+++ b/dom/encoding/moz.build
@@ -3,38 +3,35 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # 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/.
 
 with Files("**"):
     BUG_COMPONENT = ("Core", "Internationalization")
 
 EXPORTS.mozilla.dom += [
-    'EncodingUtils.h',
     'FallbackEncoding.h',
     'TextDecoder.h',
     'TextEncoder.h',
 ]
 
 UNIFIED_SOURCES += [
-    'EncodingUtils.cpp',
     'FallbackEncoding.cpp',
     'TextDecoder.cpp',
     'TextEncoder.cpp',
 ]
 
 FINAL_LIBRARY = 'xul'
 LOCAL_INCLUDES += [
     '/intl/locale',
 ]
 
 props2arrays = '/intl/locale/props2arrays.py'
 prefixes = (
     'domainsfallbacks',
-    'encodingsgroups',
     'labelsencodings',
     'localesfallbacks',
     'nonparticipatingdomains',
 )
 
 for prefix in prefixes:
     input_file = prefix + '.properties'
     header = prefix + '.properties.h'
--- a/dom/fetch/BodyExtractor.cpp
+++ b/dom/fetch/BodyExtractor.cpp
@@ -1,16 +1,15 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * 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 "BodyExtractor.h"
-#include "mozilla/dom/EncodingUtils.h"
 #include "mozilla/dom/File.h"
 #include "mozilla/dom/FormData.h"
 #include "mozilla/dom/TypedArray.h"
 #include "mozilla/dom/URLSearchParams.h"
 #include "mozilla/dom/XMLHttpRequest.h"
 #include "nsContentUtils.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMSerializer.h"
--- a/dom/html/HTMLFormSubmission.cpp
+++ b/dom/html/HTMLFormSubmission.cpp
@@ -33,17 +33,16 @@
 #include "nsIScriptError.h"
 #include "nsIStringBundle.h"
 #include "nsCExternalHandlerService.h"
 #include "nsIFileStreams.h"
 #include "nsContentUtils.h"
 #include "mozilla/Telemetry.h"
 
 #include "mozilla/dom/Directory.h"
-#include "mozilla/dom/EncodingUtils.h"
 #include "mozilla/dom/File.h"
 
 namespace mozilla {
 namespace dom {
 
 namespace {
 
 void
--- a/dom/html/nsHTMLDocument.cpp
+++ b/dom/html/nsHTMLDocument.cpp
@@ -77,17 +77,16 @@
 #include "nsIScriptError.h"
 #include "nsIMutableArray.h"
 #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"
@@ -146,16 +145,30 @@ static bool ConvertToMidasInternalComman
 
 static bool ConvertToMidasInternalCommand(const nsAString & inCommandID,
                                             nsACString& outCommandID);
 
 // ==================================================================
 // =
 // ==================================================================
 
+static bool
+IsAsciiCompatible(const nsACString& aPreferredName)
+{
+  // HZ and UTF-7 are no longer in mozilla-central, but keeping them here
+  // just in case for the benefit of comm-central.
+  return !(aPreferredName.LowerCaseEqualsLiteral("utf-16") ||
+           aPreferredName.LowerCaseEqualsLiteral("utf-16be") ||
+           aPreferredName.LowerCaseEqualsLiteral("utf-16le") ||
+           aPreferredName.LowerCaseEqualsLiteral("replacement") ||
+           aPreferredName.LowerCaseEqualsLiteral("hz-gb-2312") ||
+           aPreferredName.LowerCaseEqualsLiteral("utf-7") ||
+           aPreferredName.LowerCaseEqualsLiteral("x-imap4-modified-utf7"));
+}
+
 nsresult
 NS_NewHTMLDocument(nsIDocument** aInstancePtrResult, bool aLoadedAsData)
 {
   RefPtr<nsHTMLDocument> doc = new nsHTMLDocument();
 
   nsresult rv = doc->Init();
 
   if (NS_FAILED(rv)) {
@@ -282,17 +295,17 @@ nsHTMLDocument::TryHintCharset(nsIConten
     if(NS_SUCCEEDED(rv) && kCharsetUninitialized != requestCharsetSource) {
       nsAutoCString requestCharset;
       rv = aCv->GetHintCharacterSet(requestCharset);
       aCv->SetHintCharacterSetSource((int32_t)(kCharsetUninitialized));
 
       if(requestCharsetSource <= aCharsetSource)
         return;
 
-      if(NS_SUCCEEDED(rv) && EncodingUtils::IsAsciiCompatible(requestCharset)) {
+      if(NS_SUCCEEDED(rv) && IsAsciiCompatible(requestCharset)) {
         aCharsetSource = requestCharsetSource;
         aCharset = requestCharset;
 
         return;
       }
     }
   }
   return;
@@ -306,41 +319,41 @@ nsHTMLDocument::TryUserForcedCharset(nsI
                                      nsACString& aCharset)
 {
   nsresult rv = NS_OK;
 
   if(kCharsetFromUserForced <= aCharsetSource)
     return;
 
   // mCharacterSet not updated yet for channel, so check aCharset, too.
-  if (WillIgnoreCharsetOverride() || !EncodingUtils::IsAsciiCompatible(aCharset)) {
+  if (WillIgnoreCharsetOverride() || !IsAsciiCompatible(aCharset)) {
     return;
   }
 
   nsAutoCString forceCharsetFromDocShell;
   if (aCv) {
     // XXX mailnews-only
     rv = aCv->GetForceCharacterSet(forceCharsetFromDocShell);
   }
 
   if(NS_SUCCEEDED(rv) &&
      !forceCharsetFromDocShell.IsEmpty() &&
-     EncodingUtils::IsAsciiCompatible(forceCharsetFromDocShell)) {
+     IsAsciiCompatible(forceCharsetFromDocShell)) {
     aCharset = forceCharsetFromDocShell;
     aCharsetSource = kCharsetFromUserForced;
     return;
   }
 
   if (aDocShell) {
     // This is the Character Encoding menu code path in Firefox
     nsAutoCString charset;
     rv = aDocShell->GetForcedCharset(charset);
 
     if (NS_SUCCEEDED(rv) && !charset.IsEmpty()) {
-      if (!EncodingUtils::IsAsciiCompatible(charset)) {
+      if (!IsAsciiCompatible(charset)) {
         return;
       }
       aCharset = charset;
       aCharsetSource = kCharsetFromUserForced;
       aDocShell->SetForcedCharset(NS_LITERAL_CSTRING(""));
     }
   }
 }
@@ -356,30 +369,34 @@ nsHTMLDocument::TryCacheCharset(nsICachi
     return;
   }
 
   nsCString cachedCharset;
   rv = aCachingChannel->GetCacheTokenCachedCharset(cachedCharset);
   if (NS_FAILED(rv) || cachedCharset.IsEmpty()) {
     return;
   }
+  // The replacement encoding is not ASCII-compatible.
+  if (cachedCharset.EqualsLiteral("replacement")) {
+    return;
+  }
   // The canonical names changed, so the cache may have an old name.
-  if (!cachedCharset.EqualsLiteral("replacement")) {
-    if (!EncodingUtils::FindEncodingForLabel(cachedCharset, cachedCharset)) {
-      return;
-    }
+  const Encoding* encoding = Encoding::ForLabel(cachedCharset);
+  if (!encoding) {
+    return;
   }
-  // Check EncodingUtils::IsAsciiCompatible() even in the cache case, because the value
+  // Check IsAsciiCompatible() even in the cache case, because the value
   // might be stale and in the case of a stale charset that is not a rough
   // ASCII superset, the parser has no way to recover.
-  if (EncodingUtils::IsAsciiCompatible(cachedCharset))
-  {
-    aCharset = cachedCharset;
-    aCharsetSource = kCharsetFromCache;
+  if (!encoding->IsAsciiCompatible() && encoding != ISO_2022_JP_ENCODING) {
+    return;
   }
+  encoding->Name(cachedCharset);
+  aCharset = cachedCharset;
+  aCharsetSource = kCharsetFromCache;
 }
 
 void
 nsHTMLDocument::TryParentCharset(nsIDocShell*  aDocShell,
                                  int32_t& aCharsetSource,
                                  nsACString& aCharset)
 {
   if (!aDocShell) {
@@ -396,33 +413,33 @@ nsHTMLDocument::TryParentCharset(nsIDocS
                               &parentSource,
                               getter_AddRefs(parentPrincipal));
   if (parentCharset.IsEmpty()) {
     return;
   }
   if (kCharsetFromParentForced == parentSource ||
       kCharsetFromUserForced == parentSource) {
     if (WillIgnoreCharsetOverride() ||
-        !EncodingUtils::IsAsciiCompatible(aCharset) || // if channel said UTF-16
-        !EncodingUtils::IsAsciiCompatible(parentCharset)) {
+        !IsAsciiCompatible(aCharset) || // if channel said UTF-16
+        !IsAsciiCompatible(parentCharset)) {
       return;
     }
     aCharset.Assign(parentCharset);
     aCharsetSource = kCharsetFromParentForced;
     return;
   }
 
   if (aCharsetSource >= kCharsetFromParentFrame) {
     return;
   }
 
   if (kCharsetFromCache <= parentSource) {
     // Make sure that's OK
     if (!NodePrincipal()->Equals(parentPrincipal) ||
-        !EncodingUtils::IsAsciiCompatible(parentCharset)) {
+        !IsAsciiCompatible(parentCharset)) {
       return;
     }
 
     aCharset.Assign(parentCharset);
     aCharsetSource = kCharsetFromParentFrame;
   }
 }
 
@@ -3720,17 +3737,17 @@ nsHTMLDocument::WillIgnoreCharsetOverrid
 {
   if (mType != eHTML) {
     MOZ_ASSERT(mType == eXHTML);
     return true;
   }
   if (mCharacterSetSource >= kCharsetFromByteOrderMark) {
     return true;
   }
-  if (!EncodingUtils::IsAsciiCompatible(mCharacterSet)) {
+  if (!IsAsciiCompatible(mCharacterSet)) {
     return true;
   }
   nsCOMPtr<nsIWyciwygChannel> wyciwyg = do_QueryInterface(mChannel);
   if (wyciwyg) {
     return true;
   }
   nsIURI* uri = GetOriginalURI();
   if (uri) {
--- a/dom/script/ScriptLoader.cpp
+++ b/dom/script/ScriptLoader.cpp
@@ -49,17 +49,16 @@
 #include "nsIContentSecurityPolicy.h"
 #include "mozilla/Logging.h"
 #include "nsCRT.h"
 #include "nsContentCreatorFunctions.h"
 #include "nsProxyRelease.h"
 #include "nsSandboxFlags.h"
 #include "nsContentTypeParser.h"
 #include "nsINetworkPredictor.h"
-#include "mozilla/dom/EncodingUtils.h"
 #include "mozilla/ConsoleReportCollector.h"
 
 #include "mozilla/AsyncEventDispatcher.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/Telemetry.h"
 #include "mozilla/TimeStamp.h"
 #include "mozilla/Unused.h"
 #include "nsIScriptError.h"
--- a/dom/workers/ServiceWorkerEvents.cpp
+++ b/dom/workers/ServiceWorkerEvents.cpp
@@ -27,17 +27,16 @@
 #include "ServiceWorkerManager.h"
 
 #include "mozilla/ErrorResult.h"
 #include "mozilla/LoadInfo.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/dom/BodyUtil.h"
 #include "mozilla/dom/DOMException.h"
 #include "mozilla/dom/DOMExceptionBinding.h"
-#include "mozilla/dom/EncodingUtils.h"
 #include "mozilla/dom/FetchEventBinding.h"
 #include "mozilla/dom/MessagePort.h"
 #include "mozilla/dom/PromiseNativeHandler.h"
 #include "mozilla/dom/PushEventBinding.h"
 #include "mozilla/dom/PushMessageDataBinding.h"
 #include "mozilla/dom/PushUtil.h"
 #include "mozilla/dom/Request.h"
 #include "mozilla/dom/TypedArray.h"
--- a/dom/xhr/XMLHttpRequestMainThread.cpp
+++ b/dom/xhr/XMLHttpRequestMainThread.cpp
@@ -20,16 +20,17 @@
 #include "mozilla/dom/FileBinding.h"
 #include "mozilla/dom/FileCreatorHelper.h"
 #include "mozilla/dom/FetchUtil.h"
 #include "mozilla/dom/FormData.h"
 #include "mozilla/dom/MutableBlobStorage.h"
 #include "mozilla/dom/XMLDocument.h"
 #include "mozilla/dom/URLSearchParams.h"
 #include "mozilla/dom/PromiseNativeHandler.h"
+#include "mozilla/Encoding.h"
 #include "mozilla/EventDispatcher.h"
 #include "mozilla/EventListenerManager.h"
 #include "mozilla/EventStateManager.h"
 #include "mozilla/LoadInfo.h"
 #include "mozilla/LoadContext.h"
 #include "mozilla/MemoryReporting.h"
 #include "nsIDOMDocument.h"
 #include "mozilla/dom/ProgressEvent.h"
@@ -71,17 +72,16 @@
 #include "nsIConsoleService.h"
 #include "nsIContentSecurityPolicy.h"
 #include "nsAsyncRedirectVerifyHelper.h"
 #include "nsStringBuffer.h"
 #include "nsIFileChannel.h"
 #include "mozilla/Telemetry.h"
 #include "jsfriendapi.h"
 #include "GeckoProfiler.h"
-#include "mozilla/dom/EncodingUtils.h"
 #include "mozilla/dom/XMLHttpRequestBinding.h"
 #include "mozilla/Attributes.h"
 #include "MultipartBlobImpl.h"
 #include "nsIPermissionManager.h"
 #include "nsMimeTypes.h"
 #include "nsIHttpChannelInternal.h"
 #include "nsIClassOfService.h"
 #include "nsCharSeparatedTokenizer.h"
@@ -497,32 +497,34 @@ XMLHttpRequestMainThread::DetectCharset(
   if (mResponseType != XMLHttpRequestResponseType::_empty &&
       mResponseType != XMLHttpRequestResponseType::Text &&
       mResponseType != XMLHttpRequestResponseType::Json &&
       mResponseType != XMLHttpRequestResponseType::Moz_chunked_text) {
     return NS_OK;
   }
 
   nsAutoCString charsetVal;
+  const Encoding* encoding;
   bool ok = mChannel &&
             NS_SUCCEEDED(mChannel->GetContentCharset(charsetVal)) &&
-            EncodingUtils::FindEncodingForLabel(charsetVal, mResponseCharset);
-  if (!ok || mResponseCharset.IsEmpty()) {
+            (encoding = Encoding::ForLabel(charsetVal));
+  if (!ok) {
     // MS documentation states UTF-8 is default for responseText
-    mResponseCharset.AssignLiteral("UTF-8");
+    encoding = UTF_8_ENCODING;
   }
 
   if (mResponseType == XMLHttpRequestResponseType::Json &&
-      !mResponseCharset.EqualsLiteral("UTF-8")) {
+      encoding != UTF_8_ENCODING) {
     // The XHR spec says only UTF-8 is supported for responseType == "json"
     LogMessage("JSONCharsetWarning", GetOwner());
-    mResponseCharset.AssignLiteral("UTF-8");
-  }
-
-  mDecoder = EncodingUtils::DecoderForEncoding(mResponseCharset);
+    encoding = UTF_8_ENCODING;
+  }
+
+  encoding->Name(mResponseCharset);
+  mDecoder = encoding->NewDecoderWithBOMRemoval();
 
   return NS_OK;
 }
 
 nsresult
 XMLHttpRequestMainThread::AppendToResponseText(const char * aSrcBuffer,
                                                uint32_t aSrcBufferLen)
 {
@@ -2386,17 +2388,17 @@ XMLHttpRequestMainThread::OnBodyParseEnd
 
 void
 XMLHttpRequestMainThread::MatchCharsetAndDecoderToResponseDocument()
 {
   if (mResponseXML && mResponseCharset != mResponseXML->GetDocumentCharacterSet()) {
     mResponseCharset = mResponseXML->GetDocumentCharacterSet();
     TruncateResponseText();
     mResponseBodyDecodedPos = 0;
-    mDecoder = EncodingUtils::DecoderForEncoding(mResponseCharset);
+    mDecoder = Encoding::ForName(mResponseCharset)->NewDecoderWithBOMRemoval();
   }
 }
 
 void
 XMLHttpRequestMainThread::ChangeStateToDone()
 {
   StopProgressEventTimer();
 
--- a/dom/xslt/xslt/txMozillaStylesheetCompiler.cpp
+++ b/dom/xslt/xslt/txMozillaStylesheetCompiler.cpp
@@ -32,21 +32,20 @@
 #include "txStylesheetCompiler.h"
 #include "txXMLUtils.h"
 #include "nsAttrName.h"
 #include "nsIScriptError.h"
 #include "nsIURL.h"
 #include "nsError.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/dom/Element.h"
-#include "mozilla/dom/EncodingUtils.h"
+#include "mozilla/Encoding.h"
 #include "mozilla/UniquePtr.h"
 
 using namespace mozilla;
-using mozilla::dom::EncodingUtils;
 using mozilla::net::ReferrerPolicy;
 
 static NS_DEFINE_CID(kCParserCID, NS_PARSER_CID);
 
 static void
 getSpec(nsIChannel* aChannel, nsAString& aSpec)
 {
     if (!aChannel) {
@@ -252,28 +251,31 @@ txStylesheetSink::OnDataAvailable(nsIReq
 NS_IMETHODIMP
 txStylesheetSink::OnStartRequest(nsIRequest *aRequest, nsISupports *aContext)
 {
     int32_t charsetSource = kCharsetFromDocTypeDefault;
 
     nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
 
     // check channel's charset...
+    const Encoding* encoding = nullptr;
     nsAutoCString charsetVal;
-    nsAutoCString charset;
     if (NS_SUCCEEDED(channel->GetContentCharset(charsetVal))) {
-        if (EncodingUtils::FindEncodingForLabel(charsetVal, charset)) {
+        encoding = Encoding::ForLabel(charsetVal);
+        if (encoding) {
             charsetSource = kCharsetFromChannel;
         }
     }
 
-    if (charset.IsEmpty()) {
-      charset.AssignLiteral("UTF-8");
+    if (!encoding) {
+        encoding = UTF_8_ENCODING;
     }
 
+    nsAutoCString charset;
+    encoding->Name(charset);
     mParser->SetDocumentCharset(charset, charsetSource);
 
     nsAutoCString contentType;
     channel->GetContentType(contentType);
 
     // Time to sniff! Note: this should go away once file channels do
     // sniffing themselves.
     nsCOMPtr<nsIURI> uri;
--- a/dom/xslt/xslt/txMozillaTextOutput.cpp
+++ b/dom/xslt/xslt/txMozillaTextOutput.cpp
@@ -11,17 +11,17 @@
 #include "nsIDOMDocumentFragment.h"
 #include "nsIDocumentTransformer.h"
 #include "nsCharsetSource.h"
 #include "nsIPrincipal.h"
 #include "txURIUtils.h"
 #include "nsContentCreatorFunctions.h"
 #include "nsContentUtils.h"
 #include "nsGkAtoms.h"
-#include "mozilla/dom/EncodingUtils.h"
+#include "mozilla/Encoding.h"
 #include "nsTextNode.h"
 #include "nsNameSpaceManager.h"
 
 using namespace mozilla::dom;
 
 txMozillaTextOutput::txMozillaTextOutput(nsITransformObserver* aObserver)
 {
     MOZ_COUNT_CTOR(txMozillaTextOutput);
@@ -155,21 +155,21 @@ txMozillaTextOutput::createResultDocumen
     // Reset and set up document
     URIUtils::ResetWithSource(mDocument, aSourceDocument);
     // Only do this after resetting the document to ensure we have the
     // correct principal.
     mDocument->SetScriptHandlingObject(sgo);
 
     // Set the charset
     if (!mOutputFormat.mEncoding.IsEmpty()) {
-        nsAutoCString canonicalCharset;
-
-        if (EncodingUtils::FindEncodingForLabel(mOutputFormat.mEncoding,
-                                                canonicalCharset)) {
+        const Encoding* encoding = Encoding::ForLabel(mOutputFormat.mEncoding);
+        if (encoding) {
             mDocument->SetDocumentCharacterSetSource(kCharsetFromOtherComponent);
+            nsAutoCString canonicalCharset;
+            encoding->Name(canonicalCharset);
             mDocument->SetDocumentCharacterSet(canonicalCharset);
         }
     }
 
     // Notify the contentsink that the document is created
     nsCOMPtr<nsITransformObserver> observer = do_QueryReferent(mObserver);
     if (observer) {
         rv = observer->OnDocumentCreated(mDocument);
--- a/dom/xslt/xslt/txMozillaXMLOutput.cpp
+++ b/dom/xslt/xslt/txMozillaXMLOutput.cpp
@@ -24,18 +24,18 @@
 #include "txStringUtils.h"
 #include "txURIUtils.h"
 #include "nsIHTMLDocument.h"
 #include "nsIStyleSheetLinkingElement.h"
 #include "nsIDocumentTransformer.h"
 #include "mozilla/StyleSheetInlines.h"
 #include "mozilla/css/Loader.h"
 #include "mozilla/dom/Element.h"
-#include "mozilla/dom/EncodingUtils.h"
 #include "mozilla/dom/ScriptLoader.h"
+#include "mozilla/Encoding.h"
 #include "nsContentUtils.h"
 #include "txXMLUtils.h"
 #include "nsContentSink.h"
 #include "nsINode.h"
 #include "nsContentCreatorFunctions.h"
 #include "nsError.h"
 #include "nsIFrame.h"
 #include <algorithm>
@@ -815,20 +815,21 @@ txMozillaXMLOutput::createResultDocument
     URIUtils::ResetWithSource(mDocument, aSourceDocument);
 
     // Make sure we set the script handling object after resetting with the
     // source, so that we have the right principal.
     mDocument->SetScriptHandlingObject(sgo);
 
     // Set the charset
     if (!mOutputFormat.mEncoding.IsEmpty()) {
-        nsAutoCString canonicalCharset;
-        if (EncodingUtils::FindEncodingForLabel(mOutputFormat.mEncoding,
-                                                canonicalCharset)) {
+        const Encoding* encoding = Encoding::ForLabel(mOutputFormat.mEncoding);
+        if (encoding) {
             mDocument->SetDocumentCharacterSetSource(kCharsetFromOtherComponent);
+            nsAutoCString canonicalCharset;
+            encoding->Name(canonicalCharset);
             mDocument->SetDocumentCharacterSet(canonicalCharset);
         }
     }
 
     // Set the mime-type
     if (!mOutputFormat.mMediaType.IsEmpty()) {
         mDocument->SetContentType(mOutputFormat.mMediaType);
     }
--- a/gfx/thebes/gfxFontUtils.cpp
+++ b/gfx/thebes/gfxFontUtils.cpp
@@ -5,17 +5,16 @@
 
 #include "mozilla/ArrayUtils.h"
 #include "mozilla/BinarySearch.h"
 
 #include "gfxFontUtils.h"
 
 #include "nsServiceManagerUtils.h"
 
-#include "mozilla/dom/EncodingUtils.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Services.h"
 #include "mozilla/BinarySearch.h"
 #include "mozilla/Sprintf.h"
 
 #include "nsCOMPtr.h"
 #include "nsIUUIDGenerator.h"
 #include "mozilla/Encoding.h"
rename from dom/encoding/encodingsgroups.properties
rename to intl/locale/encodingsgroups.properties
--- a/intl/locale/moz.build
+++ b/intl/locale/moz.build
@@ -84,17 +84,23 @@ FINAL_LIBRARY = 'xul'
 LOCAL_INCLUDES += [
     '/intl/uconv',
 ]
 
 RESOURCE_FILES += [
     'language.properties',
 ]
 
-GENERATED_FILES += [
-    'langGroups.properties.h',
-]
-langgroups = GENERATED_FILES['langGroups.properties.h']
-langgroups.script = 'props2arrays.py'
-langgroups.inputs = ['langGroups.properties']
+prefixes = (
+    'encodingsgroups',
+    'langGroups',
+)
+
+for prefix in prefixes:
+    input_file = prefix + '.properties'
+    header = prefix + '.properties.h'
+    GENERATED_FILES += [header]
+    props = GENERATED_FILES[header]
+    props.script = 'props2arrays.py'
+    props.inputs = [input_file]
 
 if CONFIG['ENABLE_TESTS']:
     DIRS += ['tests/gtest']
--- a/intl/locale/nsLanguageAtomService.cpp
+++ b/intl/locale/nsLanguageAtomService.cpp
@@ -3,24 +3,27 @@
  * 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 "nsLanguageAtomService.h"
 #include "nsUConvPropertySearch.h"
 #include "nsUnicharUtils.h"
 #include "nsIAtom.h"
 #include "mozilla/ArrayUtils.h"
+#include "mozilla/ClearOnShutdown.h"
 #include "mozilla/intl/OSPreferences.h"
-#include "mozilla/dom/EncodingUtils.h"
-#include "mozilla/ClearOnShutdown.h"
 #include "mozilla/ServoBindings.h"
 
 using namespace mozilla;
 using mozilla::intl::OSPreferences;
 
+static constexpr nsUConvProp encodingsGroups[] = {
+#include "encodingsgroups.properties.h"
+};
+
 static constexpr nsUConvProp kLangGroups[] = {
 #include "langGroups.properties.h"
 };
 
 // static
 nsLanguageAtomService*
 nsLanguageAtomService::GetService()
 {
@@ -41,17 +44,20 @@ nsLanguageAtomService::LookupLanguage(co
   nsCOMPtr<nsIAtom> lang = NS_Atomize(lowered);
   return GetLanguageGroup(lang);
 }
 
 already_AddRefed<nsIAtom>
 nsLanguageAtomService::LookupCharSet(const nsACString& aCharSet)
 {
   nsAutoCString group;
-  dom::EncodingUtils::LangGroupForEncoding(aCharSet, group);
+  if (NS_FAILED(nsUConvPropertySearch::SearchPropertyValue(
+      encodingsGroups, ArrayLength(encodingsGroups), aCharSet, group))) {
+    return RefPtr<nsIAtom>(nsGkAtoms::Unicode).forget();
+  }
   return NS_Atomize(group);
 }
 
 nsIAtom*
 nsLanguageAtomService::GetLocaleLanguage()
 {
   do {
     if (!mLocaleLanguage) {
--- a/intl/locale/unix/nsUNIXCharset.cpp
+++ b/intl/locale/unix/nsUNIXCharset.cpp
@@ -18,19 +18,18 @@
 #include <nl_types.h>
 #endif
 #if HAVE_LANGINFO_CODESET
 #include <langinfo.h>
 #endif
 #include "nsPlatformCharset.h"
 #include "prinit.h"
 #include "nsUnicharUtils.h"
-#include "mozilla/dom/EncodingUtils.h"
+#include "mozilla/Encoding.h"
 
-using mozilla::dom::EncodingUtils;
 using namespace mozilla;
 
 static constexpr nsUConvProp kUnixCharsets[] = {
 #include "unixcharset.properties.h"
 };
 
 NS_IMPL_ISUPPORTS(nsPlatformCharset, nsIPlatformCharset)
 
@@ -121,16 +120,16 @@ nsPlatformCharset::Init()
 nsresult
 nsPlatformCharset::VerifyCharset(nsCString &aCharset)
 {
   // fast path for UTF-8.  Most platform uses UTF-8 as charset now.
   if (aCharset.EqualsLiteral("UTF-8")) {
     return NS_OK;
   }
 
-  nsAutoCString encoding;
-  if (!EncodingUtils::FindEncodingForLabelNoReplacement(aCharset, encoding)) {
+  const Encoding* encoding = Encoding::ForLabelNoReplacement(aCharset);
+  if (!encoding) {
     return NS_ERROR_UCONV_NOCONV;
   }
 
-  aCharset.Assign(encoding);
+  encoding->Name(aCharset);
   return NS_OK;
 }
--- a/layout/base/nsDocumentViewer.cpp
+++ b/layout/base/nsDocumentViewer.cpp
@@ -36,18 +36,18 @@
 #include "nsIDOMHTMLDocument.h"
 #include "nsIDOMHTMLElement.h"
 #include "nsContentUtils.h"
 #include "nsLayoutStylesheetCache.h"
 #ifdef ACCESSIBILITY
 #include "mozilla/a11y/DocAccessible.h"
 #endif
 #include "mozilla/BasicEvents.h"
+#include "mozilla/Encoding.h"
 #include "mozilla/Preferences.h"
-#include "mozilla/dom/EncodingUtils.h"
 #include "mozilla/WeakPtr.h"
 #include "mozilla/StyleSheet.h"
 #include "mozilla/StyleSheetInlines.h"
 
 #include "nsViewManager.h"
 #include "nsView.h"
 
 #include "nsIPageSequenceFrame.h"
@@ -3377,27 +3377,30 @@ SetChildForceCharacterSet(nsIContentView
 
 NS_IMETHODIMP
 nsDocumentViewer::SetForceCharacterSet(const nsACString& aForceCharacterSet)
 {
   // This method is scriptable, so add-ons could pass in something other
   // than a canonical name. However, in case where the input is a canonical
   // name, "replacement" doesn't survive label resolution. Additionally, the
   // empty string means no hint.
-  nsAutoCString encoding;
+  const Encoding* encoding = nullptr;
   if (!aForceCharacterSet.IsEmpty()) {
     if (aForceCharacterSet.EqualsLiteral("replacement")) {
-      encoding.AssignLiteral("replacement");
-    } else if (!EncodingUtils::FindEncodingForLabel(aForceCharacterSet,
-                                                    encoding)) {
+      encoding = REPLACEMENT_ENCODING;
+    } else if (!(encoding = Encoding::ForLabel(aForceCharacterSet))) {
       // Reject unknown labels
       return NS_ERROR_INVALID_ARG;
     }
   }
-  mForceCharacterSet = encoding;
+  if (encoding) {
+    encoding->Name(mForceCharacterSet);
+  } else {
+    mForceCharacterSet.Truncate();
+  }
   // now set the force char set on all children of mContainer
   CallChildren(SetChildForceCharacterSet, (void*) &aForceCharacterSet);
   return NS_OK;
 }
 
 NS_IMETHODIMP nsDocumentViewer::GetHintCharacterSet(nsACString& aHintCharacterSet)
 {
 
@@ -3444,27 +3447,30 @@ SetChildHintCharacterSet(nsIContentViewe
 
 NS_IMETHODIMP
 nsDocumentViewer::SetHintCharacterSet(const nsACString& aHintCharacterSet)
 {
   // This method is scriptable, so add-ons could pass in something other
   // than a canonical name. However, in case where the input is a canonical
   // name, "replacement" doesn't survive label resolution. Additionally, the
   // empty string means no hint.
-  nsAutoCString encoding;
+  const Encoding* encoding = nullptr;
   if (!aHintCharacterSet.IsEmpty()) {
     if (aHintCharacterSet.EqualsLiteral("replacement")) {
-      encoding.AssignLiteral("replacement");
-    } else if (!EncodingUtils::FindEncodingForLabel(aHintCharacterSet,
-                                                    encoding)) {
+      encoding = REPLACEMENT_ENCODING;
+    } else if (!(encoding = Encoding::ForLabel(aHintCharacterSet))) {
       // Reject unknown labels
       return NS_ERROR_INVALID_ARG;
     }
   }
-  mHintCharset = encoding;
+  if (encoding) {
+    encoding->Name(mHintCharset);
+  } else {
+    mHintCharset.Truncate();
+  }
   // now set the hint char set on all children of mContainer
   CallChildren(SetChildHintCharacterSet, (void*) &aHintCharacterSet);
   return NS_OK;
 }
 
 static void
 AppendChildSubtree(nsIContentViewer* aChild, void* aClosure)
 {
--- a/netwerk/base/nsUnicharStreamLoader.cpp
+++ b/netwerk/base/nsUnicharStreamLoader.cpp
@@ -3,26 +3,25 @@
  * 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 "mozilla/DebugOnly.h"
 
 #include "nsUnicharStreamLoader.h"
 #include "nsIInputStream.h"
 #include <algorithm>
-#include "mozilla/dom/EncodingUtils.h"
+#include "mozilla/Encoding.h"
 
 // 1024 bytes is specified in
 // http://www.whatwg.org/specs/web-apps/current-work/#charset for HTML; for
 // other resource types (e.g. CSS) typically fewer bytes are fine too, since
 // they only look at things right at the beginning of the data.
 #define SNIFFING_BUFFER_SIZE 1024
 
 using namespace mozilla;
-using mozilla::dom::EncodingUtils;
 
 NS_IMETHODIMP
 nsUnicharStreamLoader::Init(nsIUnicharStreamLoaderObserver *aObserver)
 {
   NS_ENSURE_ARG_POINTER(aObserver);
 
   mObserver = aObserver;
 
@@ -179,25 +178,25 @@ nsUnicharStreamLoader::DetermineCharset(
     mCharset.AssignLiteral("UTF-8");
   }
 
   // Sadly, nsIUnicharStreamLoader is exposed to extensions, so we can't
   // assume mozilla::css::Loader to be the only caller. Special-casing
   // replacement, since it's not invariant under a second label resolution
   // operation.
   if (mCharset.EqualsLiteral("replacement")) {
-    mDecoder = EncodingUtils::DecoderForEncoding(mCharset);
+    mDecoder = REPLACEMENT_ENCODING->NewDecoderWithBOMRemoval();
   } else {
-    nsAutoCString charset;
-    if (!EncodingUtils::FindEncodingForLabelNoReplacement(mCharset, charset)) {
+    const Encoding* encoding = Encoding::ForLabelNoReplacement(mCharset);
+    if (!encoding) {
       // If we got replacement here, the caller was not mozilla::css::Loader
       // but an extension.
       return NS_ERROR_UCONV_NOCONV;
     }
-    mDecoder = EncodingUtils::DecoderForEncoding(charset);
+    mDecoder = encoding->NewDecoderWithBOMRemoval();
   }
 
   // Process the data into mBuffer
   uint32_t dummy;
   rv = WriteSegmentFun(nullptr, this,
                        mRawData.BeginReading(),
                        0, mRawData.Length(),
                        &dummy);
--- a/netwerk/mime/nsMIMEHeaderParamImpl.cpp
+++ b/netwerk/mime/nsMIMEHeaderParamImpl.cpp
@@ -16,19 +16,19 @@
 #include "nsEscape.h"
 #include "nsIUTF8ConverterService.h"
 #include "nsUConvCID.h"
 #include "nsIServiceManager.h"
 #include "nsMIMEHeaderParamImpl.h"
 #include "nsReadableUtils.h"
 #include "nsNativeCharsetUtils.h"
 #include "nsError.h"
-#include "mozilla/dom/EncodingUtils.h"
+#include "mozilla/Encoding.h"
 
-using mozilla::dom::EncodingUtils;
+using mozilla::Encoding;
 
 // static functions declared below are moved from mailnews/mime/src/comi18n.cpp
   
 static char *DecodeQ(const char *, uint32_t);
 static bool Is7bitNonAsciiString(const char *, uint32_t);
 static void CopyRawHeader(const char *, uint32_t, const char *, nsACString &);
 static nsresult DecodeRFC2047Str(const char *, const char *, bool, nsACString&);
 static nsresult internalDecodeParameter(const nsACString&, const char*,
@@ -95,25 +95,24 @@ nsMIMEHeaderParamImpl::DoGetParameter(co
                                  // was aDecoding == MIME_FIELD_ENCODING
                                  // see bug 875615
                                  true,
                                  str1);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (!aFallbackCharset.IsEmpty())
     {
-        nsAutoCString charset;
-        EncodingUtils::FindEncodingForLabel(aFallbackCharset, charset);
+        const Encoding* encoding = Encoding::ForLabel(aFallbackCharset);
         nsAutoCString str2;
         nsCOMPtr<nsIUTF8ConverterService> 
           cvtUTF8(do_GetService(NS_UTF8CONVERTERSERVICE_CONTRACTID));
         if (cvtUTF8 &&
             NS_SUCCEEDED(cvtUTF8->ConvertStringToUTF8(str1, 
                 PromiseFlatCString(aFallbackCharset).get(), false,
-                                   !charset.EqualsLiteral("UTF-8"),
+                                   encoding != UTF_8_ENCODING,
                                    1, str2))) {
           CopyUTF8toUTF16(str2, aResult);
           return NS_OK;
         }
     }
 
     if (IsUTF8(str1)) {
       CopyUTF8toUTF16(str1, aResult);
--- a/netwerk/streamconv/converters/nsIndexedToHTML.cpp
+++ b/netwerk/streamconv/converters/nsIndexedToHTML.cpp
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * 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 "nsIndexedToHTML.h"
+
 #include "DateTimeFormat.h"
-#include "nsIndexedToHTML.h"
-#include "mozilla/dom/EncodingUtils.h"
+#include "mozilla/Encoding.h"
 #include "mozilla/intl/LocaleService.h"
 #include "nsNetUtil.h"
 #include "netCore.h"
 #include "nsStringStream.h"
 #include "nsIFile.h"
 #include "nsIFileURL.h"
 #include "nsEscape.h"
 #include "nsIDirIndex.h"
--- a/parser/html/nsHtml5MetaScannerCppSupplement.h
+++ b/parser/html/nsHtml5MetaScannerCppSupplement.h
@@ -1,17 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * 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 "nsISupportsImpl.h"
 
-#include "mozilla/dom/EncodingUtils.h"
-
-using mozilla::dom::EncodingUtils;
+#include "mozilla/Encoding.h"
 
 void
 nsHtml5MetaScanner::sniff(nsHtml5ByteReadable* bytes, nsACString& charset)
 {
   readable = bytes;
   stateLoop(stateSave);
   readable = nullptr;
   charset.Assign(mCharset);
@@ -22,25 +20,25 @@ nsHtml5MetaScanner::tryCharset(nsHtml5St
 {
   // This code needs to stay in sync with
   // nsHtml5StreamParser::internalEncodingDeclaration. Unfortunately, the
   // trickery with member fields here leads to some copy-paste reuse. :-(
   nsAutoCString label;
   nsString charset16; // Not Auto, because using it to hold nsStringBuffer*
   charset.ToString(charset16);
   CopyUTF16toUTF8(charset16, label);
-  nsAutoCString encoding;
-  if (!EncodingUtils::FindEncodingForLabel(label, encoding)) {
+  const mozilla::Encoding* encoding = mozilla::Encoding::ForLabel(label);
+  if (!encoding) {
     return false;
   }
-  if (encoding.EqualsLiteral("UTF-16BE") ||
-      encoding.EqualsLiteral("UTF-16LE")) {
+  if (encoding == UTF_16BE_ENCODING ||
+      encoding == UTF_16LE_ENCODING) {
     mCharset.AssignLiteral("UTF-8");
     return true;
   }
-  if (encoding.EqualsLiteral("x-user-defined")) {
+  if (encoding == X_USER_DEFINED_ENCODING) {
     // WebKit/Blink hack for Indian and Armenian legacy sites
     mCharset.AssignLiteral("windows-1252");
     return true;
   }
-  mCharset.Assign(encoding);
+  encoding->Name(mCharset);
   return true;
 }
--- a/parser/html/nsHtml5StreamParser.cpp
+++ b/parser/html/nsHtml5StreamParser.cpp
@@ -1,17 +1,18 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set sw=2 ts=2 et tw=79: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * 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 "mozilla/DebugOnly.h"
+#include "nsHtml5StreamParser.h"
 
-#include "nsHtml5StreamParser.h"
+#include "mozilla/DebugOnly.h"
+#include "mozilla/Encoding.h"
 #include "nsContentUtils.h"
 #include "nsHtml5Tokenizer.h"
 #include "nsIHttpChannel.h"
 #include "nsHtml5Parser.h"
 #include "nsHtml5TreeBuilder.h"
 #include "nsHtml5AtomTable.h"
 #include "nsHtml5Module.h"
 #include "nsHtml5RefPtr.h"
@@ -24,20 +25,17 @@
 #include "nsINestedURI.h"
 #include "nsCharsetSource.h"
 #include "nsIWyciwygChannel.h"
 #include "nsIThreadRetargetableRequest.h"
 #include "nsPrintfCString.h"
 #include "nsNetUtil.h"
 #include "nsXULAppAPI.h"
 
-#include "mozilla/dom/EncodingUtils.h"
-
 using namespace mozilla;
-using mozilla::dom::EncodingUtils;
 
 int32_t nsHtml5StreamParser::sTimerInitialDelay = 120;
 int32_t nsHtml5StreamParser::sTimerSubsequentDelay = 120;
 
 // static
 void
 nsHtml5StreamParser::InitializeStatics()
 {
@@ -250,40 +248,42 @@ nsHtml5StreamParser::GetChannel(nsIChann
 }
 
 NS_IMETHODIMP
 nsHtml5StreamParser::Notify(const char* aCharset, nsDetectionConfident aConf)
 {
   NS_ASSERTION(IsParserThread(), "Wrong thread!");
   if (aConf == eBestAnswer || aConf == eSureAnswer) {
     mFeedChardet = false; // just in case
-    nsAutoCString encoding;
-    if (!EncodingUtils::FindEncodingForLabelNoReplacement(
-        nsDependentCString(aCharset), encoding)) {
+    const Encoding* encoding = Encoding::ForLabelNoReplacement(
+        nsDependentCString(aCharset));
+    if (!encoding) {
       return NS_OK;
     }
+    nsAutoCString charset;
+    encoding->Name(charset);
     if (HasDecoder()) {
-      if (mCharset.Equals(encoding)) {
+      if (mCharset.Equals(charset)) {
         NS_ASSERTION(mCharsetSource < kCharsetFromAutoDetection,
             "Why are we running chardet at all?");
         mCharsetSource = kCharsetFromAutoDetection;
         mTreeBuilder->SetDocumentCharset(mCharset, mCharsetSource);
       } else {
         // We've already committed to a decoder. Request a reload from the
         // docshell.
-        mTreeBuilder->NeedsCharsetSwitchTo(encoding,
+        mTreeBuilder->NeedsCharsetSwitchTo(charset,
                                            kCharsetFromAutoDetection,
                                            0);
         FlushTreeOpsAndDisarmTimer();
         Interrupt();
       }
     } else {
       // Got a confident answer from the sniffing buffer. That code will
       // take care of setting up the decoder.
-      mCharset.Assign(encoding);
+      mCharset.Assign(charset);
       mCharsetSource = kCharsetFromAutoDetection;
       mTreeBuilder->SetDocumentCharset(mCharset, mCharsetSource);
     }
   }
   return NS_OK;
 }
 
 void
@@ -316,17 +316,17 @@ nsHtml5StreamParser::SetViewSourceTitle(
 
 nsresult
 nsHtml5StreamParser::SetupDecodingAndWriteSniffingBufferAndCurrentSegment(const uint8_t* aFromSegment, // can be null
                                                                           uint32_t aCount,
                                                                           uint32_t* aWriteCount)
 {
   NS_ASSERTION(IsParserThread(), "Wrong thread!");
   nsresult rv = NS_OK;
-  mUnicodeDecoder = EncodingUtils::DecoderForEncoding(mCharset);
+  mUnicodeDecoder = Encoding::ForName(mCharset)->NewDecoderWithBOMRemoval();
   if (mSniffingBuffer) {
     uint32_t writeCount;
     rv = WriteStreamBytes(mSniffingBuffer.get(), mSniffingLength, &writeCount);
     NS_ENSURE_SUCCESS(rv, rv);
     mSniffingBuffer = nullptr;
   }
   mMetaScanner = nullptr;
   if (aFromSegment) {
@@ -335,17 +335,17 @@ nsHtml5StreamParser::SetupDecodingAndWri
   return rv;
 }
 
 nsresult
 nsHtml5StreamParser::SetupDecodingFromBom(const char* aDecoderCharsetName)
 {
   NS_ASSERTION(IsParserThread(), "Wrong thread!");
   mCharset.Assign(aDecoderCharsetName);
-  mUnicodeDecoder = EncodingUtils::DecoderForEncoding(mCharset);
+  mUnicodeDecoder = Encoding::ForName(mCharset)->NewDecoderWithBOMRemoval();
   mCharsetSource = kCharsetFromByteOrderMark;
   mFeedChardet = false;
   mTreeBuilder->SetDocumentCharset(mCharset, mCharsetSource);
   mSniffingBuffer = nullptr;
   mMetaScanner = nullptr;
   mBomState = BOM_SNIFFING_OVER;
   return NS_OK;
 }
@@ -737,34 +737,36 @@ nsHtml5StreamParser::SniffStreamBytes(co
 
   if (mSniffingLength + aCount >= NS_HTML5_STREAM_PARSER_SNIFFING_BUFFER_SIZE) {
     // this is the last buffer
     uint32_t countToSniffingLimit =
         NS_HTML5_STREAM_PARSER_SNIFFING_BUFFER_SIZE - mSniffingLength;
     if (mMode == NORMAL || mMode == VIEW_SOURCE_HTML || mMode == LOAD_AS_DATA) {
       nsHtml5ByteReadable readable(aFromSegment, aFromSegment +
           countToSniffingLimit);
-      nsAutoCString encoding;
-      mMetaScanner->sniff(&readable, encoding);
+      nsAutoCString charset;
+      mMetaScanner->sniff(&readable, charset);
       // Due to the way nsHtml5Portability reports OOM, ask the tree buider
       nsresult rv;
       if (NS_FAILED((rv = mTreeBuilder->IsBroken()))) {
         MarkAsBroken(rv);
         return rv;
       }
-      if (!encoding.IsEmpty()) {
+      if (!charset.IsEmpty()) {
+        const Encoding* encoding = Encoding::ForName(charset);
         // meta scan successful; honor overrides unless meta is XSS-dangerous
         if ((mCharsetSource == kCharsetFromParentForced ||
              mCharsetSource == kCharsetFromUserForced) &&
-            EncodingUtils::IsAsciiCompatible(encoding)) {
+            (encoding->IsAsciiCompatible() ||
+             encoding == ISO_2022_JP_ENCODING)) {
           // Honor override
           return SetupDecodingAndWriteSniffingBufferAndCurrentSegment(
             aFromSegment, aCount, aWriteCount);
         }
-        mCharset.Assign(encoding);
+        mCharset.Assign(charset);
         mCharsetSource = kCharsetFromMetaPrescan;
         mFeedChardet = false;
         mTreeBuilder->SetDocumentCharset(mCharset, mCharsetSource);
         return SetupDecodingAndWriteSniffingBufferAndCurrentSegment(
           aFromSegment, aCount, aWriteCount);
       }
     }
     if (mCharsetSource == kCharsetFromParentForced ||
@@ -775,34 +777,36 @@ nsHtml5StreamParser::SniffStreamBytes(co
     }
     return FinalizeSniffing(aFromSegment, aCount, aWriteCount,
         countToSniffingLimit);
   }
 
   // not the last buffer
   if (mMode == NORMAL || mMode == VIEW_SOURCE_HTML || mMode == LOAD_AS_DATA) {
     nsHtml5ByteReadable readable(aFromSegment, aFromSegment + aCount);
-    nsAutoCString encoding;
-    mMetaScanner->sniff(&readable, encoding);
+    nsAutoCString charset;
+    mMetaScanner->sniff(&readable, charset);
     // Due to the way nsHtml5Portability reports OOM, ask the tree buider
     nsresult rv;
     if (NS_FAILED((rv = mTreeBuilder->IsBroken()))) {
       MarkAsBroken(rv);
       return rv;
     }
-    if (!encoding.IsEmpty()) {
+    if (!charset.IsEmpty()) {
+      const Encoding* encoding = Encoding::ForName(charset);
       // meta scan successful; honor overrides unless meta is XSS-dangerous
       if ((mCharsetSource == kCharsetFromParentForced ||
            mCharsetSource == kCharsetFromUserForced) &&
-          EncodingUtils::IsAsciiCompatible(encoding)) {
+          (encoding->IsAsciiCompatible() ||
+           encoding == ISO_2022_JP_ENCODING)) {
         // Honor override
         return SetupDecodingAndWriteSniffingBufferAndCurrentSegment(aFromSegment,
             aCount, aWriteCount);
       }
-      mCharset.Assign(encoding);
+      mCharset.Assign(charset);
       mCharsetSource = kCharsetFromMetaPrescan;
       mFeedChardet = false;
       mTreeBuilder->SetDocumentCharset(mCharset, mCharsetSource);
       return SetupDecodingAndWriteSniffingBufferAndCurrentSegment(aFromSegment,
         aCount, aWriteCount);
     }
   }
 
@@ -998,17 +1002,17 @@ nsHtml5StreamParser::OnStartRequest(nsIR
 
   // We are reloading a document.open()ed doc or loading JSON/WebVTT/etc. into
   // a browsing context. In the latter case, there's no need to remove the
   // BOM manually here, because the UTF-8 decoder removes it.
   mReparseForbidden = true;
   mFeedChardet = false;
 
   // Instantiate the converter here to avoid BOM sniffing.
-  mUnicodeDecoder = EncodingUtils::DecoderForEncoding(mCharset);
+  mUnicodeDecoder = Encoding::ForName(mCharset)->NewDecoderWithBOMRemoval();
   return NS_OK;
 }
 
 nsresult
 nsHtml5StreamParser::CheckListenerChain()
 {
   NS_ASSERTION(NS_IsMainThread(), "Should be on the main thread!");
   if (!mObserver) {
@@ -1225,59 +1229,59 @@ nsHtml5StreamParser::CopySegmentsToParse
   // Assume DoDataAvailable consumed all available bytes.
   *aWriteCount = aCount;
   return NS_OK;
 }
 
 bool
 nsHtml5StreamParser::PreferredForInternalEncodingDecl(nsACString& aEncoding)
 {
-  nsAutoCString newEncoding;
-  if (!EncodingUtils::FindEncodingForLabel(aEncoding, newEncoding)) {
+  const Encoding* newEncoding = Encoding::ForLabel(aEncoding);
+  if (!newEncoding) {
     // the encoding name is bogus
     mTreeBuilder->MaybeComplainAboutCharset("EncMetaUnsupported",
                                             true,
                                             mTokenizer->getLineNumber());
     return false;
   }
 
-  if (newEncoding.EqualsLiteral("UTF-16BE") ||
-      newEncoding.EqualsLiteral("UTF-16LE")) {
+  if (newEncoding == UTF_16BE_ENCODING ||
+      newEncoding == UTF_16LE_ENCODING) {
     mTreeBuilder->MaybeComplainAboutCharset("EncMetaUtf16",
                                             true,
                                             mTokenizer->getLineNumber());
-    newEncoding.AssignLiteral("UTF-8");
+    newEncoding = UTF_8_ENCODING;
   }
 
-  if (newEncoding.EqualsLiteral("x-user-defined")) {
+  if (newEncoding == X_USER_DEFINED_ENCODING) {
     // WebKit/Blink hack for Indian and Armenian legacy sites
     mTreeBuilder->MaybeComplainAboutCharset("EncMetaUserDefined",
                                             true,
                                             mTokenizer->getLineNumber());
-    newEncoding.AssignLiteral("windows-1252");
+    newEncoding = WINDOWS_1252_ENCODING;
   }
 
-  if (newEncoding.Equals(mCharset)) {
+  if (newEncoding == Encoding::ForName(mCharset)) {
     if (mCharsetSource < kCharsetFromMetaPrescan) {
       if (mInitialEncodingWasFromParentFrame) {
         mTreeBuilder->MaybeComplainAboutCharset("EncLateMetaFrame",
                                                 false,
                                                 mTokenizer->getLineNumber());
       } else {
         mTreeBuilder->MaybeComplainAboutCharset("EncLateMeta",
                                                 false,
                                                 mTokenizer->getLineNumber());
       }
     }
     mCharsetSource = kCharsetFromMetaTag; // become confident
     mFeedChardet = false; // don't feed chardet when confident
     return false;
   }
 
-  aEncoding.Assign(newEncoding);
+  newEncoding->Name(aEncoding);
   return true;
 }
 
 bool
 nsHtml5StreamParser::internalEncodingDeclaration(nsHtml5String aEncoding)
 {
   // This code needs to stay in sync with
   // nsHtml5MetaScanner::tryCharset. Unfortunately, the
--- a/parser/htmlparser/nsScanner.cpp
+++ b/parser/htmlparser/nsScanner.cpp
@@ -1,33 +1,30 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=2 sw=2 et tw=78: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * 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/. */
 
 //#define __INCREMENTAL 1
 
+#include "nsScanner.h"
+
 #include "mozilla/Attributes.h"
 #include "mozilla/DebugOnly.h"
-
-#include "nsScanner.h"
+#include "mozilla/Encoding.h"
 #include "nsDebug.h"
 #include "nsReadableUtils.h"
 #include "nsIInputStream.h"
 #include "nsIFile.h"
 #include "nsUTF8Utils.h" // for LossyConvertEncoding
 #include "nsCRT.h"
 #include "nsParser.h"
 #include "nsCharsetSource.h"
 
-#include "mozilla/dom/EncodingUtils.h"
-
-using mozilla::dom::EncodingUtils;
-
 nsReadEndCondition::nsReadEndCondition(const char16_t* aTerminateChars) :
   mChars(aTerminateChars), mFilter(char16_t(~0)) // All bits set
 {
   // Build filter that will be used to filter out characters with
   // bits that none of the terminal chars have. This works very well
   // because terminal chars often have only the last 4-6 bits set and
   // normal ascii letters have bit 7 set. Other letters have even higher
   // bits set.
@@ -101,34 +98,35 @@ nsScanner::nsScanner(nsString& aFilename
 
 nsresult nsScanner::SetDocumentCharset(const nsACString& aCharset , int32_t aSource)
 {
   if (aSource < mCharsetSource) // priority is lower than the current one
     return NS_OK;
 
   mCharsetSource = aSource;
 
-  nsCString charsetName;
+  const Encoding* encoding;
   if (aCharset.EqualsLiteral("replacement")) {
-    charsetName.Assign(aCharset);
+    encoding = REPLACEMENT_ENCODING;
   } else {
-    mozilla::DebugOnly<bool> valid =
-        EncodingUtils::FindEncodingForLabel(aCharset, charsetName);
-    MOZ_ASSERT(valid, "Should never call with a bogus aCharset.");
+    encoding = Encoding::ForLabel(aCharset);
+    MOZ_ASSERT(encoding, "Should never call with a bogus aCharset.");
   }
 
+  nsCString charsetName;
+  encoding->Name(charsetName);
   if (!mCharset.IsEmpty() && charsetName.Equals(mCharset)) {
     return NS_OK; // no difference, don't change it
   }
 
   // different, need to change it
 
   mCharset.Assign(charsetName);
 
-  mUnicodeDecoder = EncodingUtils::DecoderForEncoding(mCharset);
+  mUnicodeDecoder = encoding->NewDecoderWithBOMRemoval();
 
   return NS_OK;
 }
 
 
 /**
  *  default destructor
  *  
--- a/parser/xml/nsSAXXMLReader.cpp
+++ b/parser/xml/nsSAXXMLReader.cpp
@@ -1,30 +1,30 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * 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 "nsSAXXMLReader.h"
+
+#include "mozilla/Encoding.h"
 #include "nsIInputStream.h"
 #include "nsNetCID.h"
 #include "nsNetUtil.h"
 #include "NullPrincipal.h"
 #include "nsIParser.h"
 #include "nsParserCIID.h"
 #include "nsStreamUtils.h"
 #include "nsStringStream.h"
 #include "nsIScriptError.h"
 #include "nsSAXAttributes.h"
 #include "nsSAXLocator.h"
-#include "nsSAXXMLReader.h"
 #include "nsCharsetSource.h"
 
-#include "mozilla/dom/EncodingUtils.h"
-
-using mozilla::dom::EncodingUtils;
+using mozilla::Encoding;
 
 #define XMLNS_URI "http://www.w3.org/2000/xmlns/"
 
 static NS_DEFINE_CID(kParserCID, NS_PARSER_CID);
 
 NS_IMPL_CYCLE_COLLECTION(nsSAXXMLReader,
                          mContentHandler,
                          mDTDHandler,
@@ -648,21 +648,21 @@ nsSAXXMLReader::TryChannelCharset(nsICha
 {
   if (aCharsetSource >= kCharsetFromChannel)
     return true;
   
   if (aChannel) {
     nsAutoCString charsetVal;
     nsresult rv = aChannel->GetContentCharset(charsetVal);
     if (NS_SUCCEEDED(rv)) {
-      nsAutoCString preferred;
-      if (!EncodingUtils::FindEncodingForLabel(charsetVal, preferred))
+      const Encoding* preferred = Encoding::ForLabel(charsetVal);
+      if (!preferred)
         return false;
 
-      aCharset = preferred;
+      preferred->Name(aCharset);
       aCharsetSource = kCharsetFromChannel;
       return true;
     }
   }
 
   return false;
 }
 
--- a/toolkit/components/osfile/NativeOSFileInternals.cpp
+++ b/toolkit/components/osfile/NativeOSFileInternals.cpp
@@ -1,32 +1,32 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * 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/. */
 
 /**
  * Native implementation of some OS.File operations.
  */
 
+#include "NativeOSFileInternals.h"
+
 #include "nsString.h"
 #include "nsNetCID.h"
 #include "nsThreadUtils.h"
 #include "nsXPCOMCID.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsServiceManagerUtils.h"
 #include "nsProxyRelease.h"
 
 #include "nsINativeOSFileInternals.h"
-#include "NativeOSFileInternals.h"
 #include "mozilla/dom/NativeOSFileInternalsBinding.h"
 
 #include "mozilla/Encoding.h"
 #include "nsIEventTarget.h"
 
-#include "mozilla/dom/EncodingUtils.h"
 #include "mozilla/DebugOnly.h"
 #include "mozilla/Scoped.h"
 #include "mozilla/HoldDropJSObjects.h"
 #include "mozilla/TimeStamp.h"
 
 #include "prio.h"
 #include "prerror.h"
 #include "private/pprio.h"
@@ -786,22 +786,22 @@ public:
     NS_ReleaseOnMainThread(mResult.forget());
   }
 
 protected:
   nsresult BeforeRead() override {
     // Obtain the decoder. We do this before reading to avoid doing
     // any unnecessary I/O in case the name of the encoding is incorrect.
     MOZ_ASSERT(!NS_IsMainThread());
-    nsAutoCString encodingName;
-    if (!dom::EncodingUtils::FindEncodingForLabel(mEncoding, encodingName)) {
+    const Encoding* encoding = Encoding::ForLabel(mEncoding);
+    if (!encoding) {
       Fail(NS_LITERAL_CSTRING("Decode"), mResult.forget(), OS_ERROR_INVAL);
       return NS_ERROR_FAILURE;
     }
-    mDecoder = dom::EncodingUtils::DecoderForEncoding(encodingName);
+    mDecoder = encoding->NewDecoderWithBOMRemoval();
     if (!mDecoder) {
       Fail(NS_LITERAL_CSTRING("DecoderForEncoding"), mResult.forget(), OS_ERROR_INVAL);
       return NS_ERROR_FAILURE;
     }
 
     return NS_OK;
   }