1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 #include "mozilla/dom/EncodingUtils.h"
7 #include "mozilla/ArrayUtils.h" // ArrayLength
8 #include "nsUConvPropertySearch.h"
9 #include "nsIUnicodeDecoder.h"
10 #include "nsIUnicodeEncoder.h"
11 #include "nsComponentManagerUtils.h"
16 static const char* labelsEncodings
[][3] = {
17 #include "labelsencodings.properties.h"
20 static const char* encodingsGroups
[][3] = {
21 #include "encodingsgroups.properties.h"
25 EncodingUtils::FindEncodingForLabel(const nsACString
& aLabel
,
26 nsACString
& aOutEncoding
)
28 // Save aLabel first because it may refer the same string as aOutEncoding.
29 nsCString
label(aLabel
);
31 EncodingUtils::TrimSpaceCharacters(label
);
32 if (label
.IsEmpty()) {
33 aOutEncoding
.Truncate();
38 return NS_SUCCEEDED(nsUConvPropertySearch::SearchPropertyValue(
39 labelsEncodings
, ArrayLength(labelsEncodings
), label
, aOutEncoding
));
43 EncodingUtils::FindEncodingForLabelNoReplacement(const nsACString
& aLabel
,
44 nsACString
& aOutEncoding
)
46 if(!FindEncodingForLabel(aLabel
, aOutEncoding
)) {
49 if (aOutEncoding
.EqualsLiteral("replacement")) {
50 aOutEncoding
.Truncate();
57 EncodingUtils::IsAsciiCompatible(const nsACString
& aPreferredName
)
59 return !(aPreferredName
.LowerCaseEqualsLiteral("utf-16") ||
60 aPreferredName
.LowerCaseEqualsLiteral("utf-16be") ||
61 aPreferredName
.LowerCaseEqualsLiteral("utf-16le") ||
62 aPreferredName
.LowerCaseEqualsLiteral("replacement") ||
63 aPreferredName
.LowerCaseEqualsLiteral("hz-gb-2312") ||
64 aPreferredName
.LowerCaseEqualsLiteral("utf-7") ||
65 aPreferredName
.LowerCaseEqualsLiteral("x-imap4-modified-utf7"));
68 already_AddRefed
<nsIUnicodeDecoder
>
69 EncodingUtils::DecoderForEncoding(const nsACString
& aEncoding
)
71 nsAutoCString
contractId(NS_UNICODEDECODER_CONTRACTID_BASE
);
72 contractId
.Append(aEncoding
);
74 nsCOMPtr
<nsIUnicodeDecoder
> decoder
= do_CreateInstance(contractId
.get());
75 MOZ_ASSERT(decoder
, "Tried to create decoder for unknown encoding.");
76 return decoder
.forget();
79 already_AddRefed
<nsIUnicodeEncoder
>
80 EncodingUtils::EncoderForEncoding(const nsACString
& aEncoding
)
82 nsAutoCString
contractId(NS_UNICODEENCODER_CONTRACTID_BASE
);
83 contractId
.Append(aEncoding
);
85 nsCOMPtr
<nsIUnicodeEncoder
> encoder
= do_CreateInstance(contractId
.get());
86 MOZ_ASSERT(encoder
, "Tried to create encoder for unknown encoding.");
87 return encoder
.forget();
91 EncodingUtils::LangGroupForEncoding(const nsACString
& aEncoding
,
92 nsACString
& aOutGroup
)
94 if (NS_FAILED(nsUConvPropertySearch::SearchPropertyValue(
95 encodingsGroups
, ArrayLength(encodingsGroups
), aEncoding
, aOutGroup
))) {
96 aOutGroup
.AssignLiteral("x-unicode");
101 } // namespace mozilla