tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

TextEncoder.cpp (1772B)


      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/. */
      6 
      7 #include "mozilla/dom/TextEncoder.h"
      8 
      9 #include "mozilla/ErrorResult.h"
     10 #include "nsReadableUtils.h"
     11 
     12 namespace mozilla::dom {
     13 
     14 void TextEncoder::Encode(JSContext* aCx, JS::Handle<JSObject*> aObj,
     15                         const nsACString& aUtf8String,
     16                         JS::MutableHandle<JSObject*> aRetval,
     17                         ErrorResult& aRv) {
     18  JSAutoRealm ar(aCx, aObj);
     19  JSObject* outView = Uint8Array::Create(aCx, aUtf8String, aRv);
     20  if (aRv.Failed()) {
     21    return;
     22  }
     23 
     24  aRetval.set(outView);
     25 }
     26 
     27 void TextEncoder::EncodeInto(JSContext* aCx, JS::Handle<JSString*> aSrc,
     28                             const Uint8Array& aDst,
     29                             TextEncoderEncodeIntoResult& aResult,
     30                             OOMReporter& aError) {
     31  DebugOnly<size_t> dstLength = 0;
     32  auto maybe = aDst.ProcessData(
     33      [&](const Span<uint8_t>& aData, JS::AutoCheckCannotGC&&) {
     34        dstLength = aData.Length();
     35        return JS_EncodeStringToUTF8BufferPartial(aCx, aSrc,
     36                                                  AsWritableChars(aData));
     37      });
     38  if (!maybe) {
     39    aError.ReportOOM();
     40    return;
     41  }
     42  size_t read;
     43  size_t written;
     44  std::tie(read, written) = *maybe;
     45  MOZ_ASSERT(written <= dstLength);
     46  aResult.mRead.Construct() = read;
     47  aResult.mWritten.Construct() = written;
     48 }
     49 
     50 void TextEncoder::GetEncoding(nsACString& aEncoding) {
     51  aEncoding.AssignLiteral("utf-8");
     52 }
     53 
     54 }  // namespace mozilla::dom