Bug 1787269 [wpt PR 35624] - Further refine STP download regexs, a=testonly
[gecko.git] / dom / encoding / TextEncoder.cpp
blob4f7b3767b47bf95e124b0fbd120455d65218ba70
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "mozilla/dom/TextEncoder.h"
8 #include "mozilla/CheckedInt.h"
9 #include "mozilla/ErrorResult.h"
10 #include "mozilla/UniquePtrExtensions.h"
11 #include "nsReadableUtils.h"
13 namespace mozilla::dom {
15 void TextEncoder::Encode(JSContext* aCx, JS::Handle<JSObject*> aObj,
16 const nsACString& aUtf8String,
17 JS::MutableHandle<JSObject*> aRetval,
18 OOMReporter& aRv) {
19 JSAutoRealm ar(aCx, aObj);
20 JSObject* outView = Uint8Array::Create(aCx, aUtf8String);
21 if (!outView) {
22 aRv.ReportOOM();
23 return;
26 aRetval.set(outView);
29 void TextEncoder::EncodeInto(JSContext* aCx, JS::Handle<JSString*> aSrc,
30 const Uint8Array& aDst,
31 TextEncoderEncodeIntoResult& aResult,
32 OOMReporter& aError) {
33 aDst.ComputeState();
34 size_t read;
35 size_t written;
36 auto maybe = JS_EncodeStringToUTF8BufferPartial(
37 aCx, aSrc, AsWritableChars(Span(aDst.Data(), aDst.Length())));
38 if (!maybe) {
39 aError.ReportOOM();
40 return;
42 Tie(read, written) = *maybe;
43 MOZ_ASSERT(written <= aDst.Length());
44 aResult.mRead.Construct() = read;
45 aResult.mWritten.Construct() = written;
48 void TextEncoder::GetEncoding(nsACString& aEncoding) {
49 aEncoding.AssignLiteral("utf-8");
52 } // namespace mozilla::dom