summaryrefslogtreecommitdiffstats
path: root/intl/uconv/nsScriptableUConv.cpp
blob: 8a9638f2ce5f428ccebfc593f13d632f0dcd2016 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/* -*- 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 "nsString.h"
#include "nsIScriptableUConv.h"
#include "nsScriptableUConv.h"
#include "nsIStringStream.h"
#include "nsComponentManagerUtils.h"

#include <tuple>

using namespace mozilla;

/* Implementation file */
NS_IMPL_ISUPPORTS(nsScriptableUnicodeConverter, nsIScriptableUnicodeConverter)

nsScriptableUnicodeConverter::nsScriptableUnicodeConverter()
    : mIsInternal(false) {}

nsScriptableUnicodeConverter::~nsScriptableUnicodeConverter() = default;

NS_IMETHODIMP
nsScriptableUnicodeConverter::ConvertFromUnicode(const nsAString& aSrc,
                                                 nsACString& _retval) {
  if (!mEncoder) return NS_ERROR_FAILURE;

  // We can compute the length without replacement, because the
  // the replacement is only one byte long and a mappable character
  // would always output something, i.e. at least one byte.
  // When encoding to ISO-2022-JP, unmappables shouldn't be able
  // to cause more escape sequences to be emitted than the mappable
  // worst case where every input character causes an escape into
  // a different state.
  CheckedInt<size_t> needed =
      mEncoder->MaxBufferLengthFromUTF16WithoutReplacement(aSrc.Length());
  if (!needed.isValid() || needed.value() > UINT32_MAX) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  auto dstChars = _retval.GetMutableData(needed.value(), fallible);
  if (!dstChars) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  auto src = Span(aSrc);
  auto dst = AsWritableBytes(*dstChars);
  size_t totalWritten = 0;
  for (;;) {
    auto [result, read, written] =
        mEncoder->EncodeFromUTF16WithoutReplacement(src, dst, false);
    if (result != kInputEmpty && result != kOutputFull) {
      MOZ_RELEASE_ASSERT(written < dst.Length(),
                         "Unmappables with one-byte replacement should not "
                         "exceed mappable worst case.");
      dst[written++] = '?';
    }
    totalWritten += written;
    if (result == kInputEmpty) {
      MOZ_ASSERT(totalWritten <= UINT32_MAX);
      if (!_retval.SetLength(totalWritten, fallible)) {
        return NS_ERROR_OUT_OF_MEMORY;
      }
      return NS_OK;
    }
    src = src.From(read);
    dst = dst.From(written);
  }
}

NS_IMETHODIMP
nsScriptableUnicodeConverter::Finish(nsACString& _retval) {
  // The documentation for this method says it should be called after
  // ConvertFromUnicode(). However, our own tests called it after
  // convertFromByteArray(), i.e. when *decoding*.
  // Assuming that there exists extensions that similarly call
  // this at the wrong time, let's deal. In general, it is a design
  // error for this class to handle conversions in both directions.
  if (!mEncoder) {
    _retval.Truncate();
    mDecoder->Encoding()->NewDecoderWithBOMRemovalInto(*mDecoder);
    return NS_OK;
  }
  // If we are encoding to ISO-2022-JP, potentially
  // transition back to the ASCII state. The buffer
  // needs to be large enough for an additional NCR,
  // though.
  _retval.SetLength(13);
  auto dst = AsWritableBytes(_retval.GetMutableData(13));
  Span<char16_t> src(nullptr);
  uint32_t result;
  size_t read;
  size_t written;
  std::tie(result, read, written, std::ignore) =
      mEncoder->EncodeFromUTF16(src, dst, true);
  MOZ_ASSERT(!read);
  MOZ_ASSERT(result == kInputEmpty);
  _retval.SetLength(written);

  mDecoder->Encoding()->NewDecoderWithBOMRemovalInto(*mDecoder);
  mEncoder->Encoding()->NewEncoderInto(*mEncoder);
  return NS_OK;
}

NS_IMETHODIMP
nsScriptableUnicodeConverter::ConvertToUnicode(const nsACString& aSrc,
                                               nsAString& _retval) {
  if (!mDecoder) return NS_ERROR_FAILURE;

  uint32_t length = aSrc.Length();

  CheckedInt<size_t> needed = mDecoder->MaxUTF16BufferLength(length);
  if (!needed.isValid() || needed.value() > UINT32_MAX) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  auto dst = _retval.GetMutableData(needed.value(), fallible);
  if (!dst) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  auto src =
      Span(reinterpret_cast<const uint8_t*>(aSrc.BeginReading()), length);
  uint32_t result;
  size_t read;
  size_t written;
  // The UTF-8 decoder used to throw regardless of the error behavior.
  // Simulating the old behavior for compatibility with legacy callers.
  // If callers want control over the behavior, they should switch to
  // TextDecoder.
  if (mDecoder->Encoding() == UTF_8_ENCODING) {
    std::tie(result, read, written) =
        mDecoder->DecodeToUTF16WithoutReplacement(src, *dst, false);
    if (result != kInputEmpty) {
      return NS_ERROR_UDEC_ILLEGALINPUT;
    }
  } else {
    std::tie(result, read, written, std::ignore) =
        mDecoder->DecodeToUTF16(src, *dst, false);
  }
  MOZ_ASSERT(result == kInputEmpty);
  MOZ_ASSERT(read == length);
  MOZ_ASSERT(written <= needed.value());
  if (!_retval.SetLength(written, fallible)) {
    return NS_ERROR_OUT_OF_MEMORY;
  }
  return NS_OK;
}

NS_IMETHODIMP
nsScriptableUnicodeConverter::ConvertToByteArray(const nsAString& aString,
                                                 uint32_t* aLen,
                                                 uint8_t** _aData) {
  if (!mEncoder) return NS_ERROR_FAILURE;

  CheckedInt<size_t> needed =
      mEncoder->MaxBufferLengthFromUTF16WithoutReplacement(aString.Length());
  if (!needed.isValid() || needed.value() > UINT32_MAX) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  uint8_t* data = (uint8_t*)malloc(needed.value());
  if (!data) {
    return NS_ERROR_OUT_OF_MEMORY;
  }
  auto src = Span(aString);
  auto dst = Span(data, needed.value());
  size_t totalWritten = 0;
  for (;;) {
    auto [result, read, written] =
        mEncoder->EncodeFromUTF16WithoutReplacement(src, dst, true);
    if (result != kInputEmpty && result != kOutputFull) {
      // There's always room for one byte in the case of
      // an unmappable character, because otherwise
      // we'd have gotten `kOutputFull`.
      dst[written++] = '?';
    }
    totalWritten += written;
    if (result == kInputEmpty) {
      *_aData = data;
      MOZ_ASSERT(totalWritten <= UINT32_MAX);
      *aLen = totalWritten;
      return NS_OK;
    }
    src = src.From(read);
    dst = dst.From(written);
  }
}

NS_IMETHODIMP
nsScriptableUnicodeConverter::ConvertToInputStream(const nsAString& aString,
                                                   nsIInputStream** _retval) {
  nsresult rv;
  nsCOMPtr<nsIStringInputStream> inputStream =
      do_CreateInstance("@mozilla.org/io/string-input-stream;1", &rv);
  if (NS_FAILED(rv)) return rv;

  uint8_t* data;
  uint32_t dataLen;
  rv = ConvertToByteArray(aString, &dataLen, &data);
  if (NS_FAILED(rv)) return rv;

  rv = inputStream->AdoptData(reinterpret_cast<char*>(data), dataLen);
  if (NS_FAILED(rv)) {
    free(data);
    return rv;
  }

  NS_ADDREF(*_retval = inputStream);
  return rv;
}

NS_IMETHODIMP
nsScriptableUnicodeConverter::GetCharset(nsACString& aCharset) {
  if (!mDecoder) {
    aCharset.Truncate();
  } else {
    mDecoder->Encoding()->Name(aCharset);
  }
  return NS_OK;
}

NS_IMETHODIMP
nsScriptableUnicodeConverter::SetCharset(const nsACString& aCharset) {
  return InitConverter(aCharset);
}

NS_IMETHODIMP
nsScriptableUnicodeConverter::GetIsInternal(bool* aIsInternal) {
  *aIsInternal = mIsInternal;
  return NS_OK;
}

NS_IMETHODIMP
nsScriptableUnicodeConverter::SetIsInternal(const bool aIsInternal) {
  mIsInternal = aIsInternal;
  return NS_OK;
}

nsresult nsScriptableUnicodeConverter::InitConverter(
    const nsACString& aCharset) {
  mEncoder = nullptr;
  mDecoder = nullptr;

  auto encoding = Encoding::ForLabelNoReplacement(aCharset);
  if (!encoding) {
    return NS_ERROR_UCONV_NOCONV;
  }
  if (!(encoding == UTF_16LE_ENCODING || encoding == UTF_16BE_ENCODING)) {
    mEncoder = encoding->NewEncoder();
  }
  mDecoder = encoding->NewDecoderWithBOMRemoval();
  return NS_OK;
}