Commit 4326b92e authored by Gerald Squelart's avatar Gerald Squelart
Browse files

Bug 1784812 - Use common JSONWriteFuncs when writing to a string -...

Bug 1784812 - Use common JSONWriteFuncs when writing to a string - r=canaltinova,media-playback-reviewers,alwu

Most users of JSONWriter want to fill a string, so instead of having all these
similar implementations, we now have central reusable implementations:
- JSONStringWriteFunc contains a string and writes to it.
- JSONStringRefWriteFunc references a string and writes to it. This is most
  useful when the string already exists somewhere, or needs to be returned from
  a function (so we avoid another conversion when returning).

Differential Revision: https://phabricator.services.mozilla.com/D154618
parent eb90b3b1
Loading
Loading
Loading
Loading
+6 −11
Original line number Diff line number Diff line
@@ -9,7 +9,7 @@
#include "DDLogUtils.h"
#include "nsIThread.h"
#include "nsIThreadManager.h"
#include "mozilla/JSONWriter.h"
#include "mozilla/JSONStringWriteFuncs.h"

namespace mozilla {

@@ -375,12 +375,6 @@ void DDMediaLogs::ProcessBuffer() {
  });
}

struct StringWriteFunc : public JSONWriteFunc {
  nsCString& mCString;
  explicit StringWriteFunc(nsCString& aCString) : mCString(aCString) {}
  void Write(const Span<const char>& aStr) override { mCString.Append(aStr); }
};

void DDMediaLogs::FulfillPromises() {
  MOZ_ASSERT(!mThread || mThread.get() == NS_GetCurrentThread());

@@ -415,8 +409,8 @@ void DDMediaLogs::FulfillPromises() {
      continue;
    }

    nsCString json;
    JSONWriter jw{MakeUnique<StringWriteFunc>(json)};
    JSONStringWriteFunc<nsCString> json;
    JSONWriter jw{json};
    jw.Start();
    jw.StartArrayProperty("messages");
    for (const DDLogMessage& message : log->mMessages) {
@@ -485,7 +479,8 @@ void DDMediaLogs::FulfillPromises() {
        log->mMessages.IsEmpty());
    jw.EndObject();
    jw.End();
    DDL_DEBUG("RetrieveMessages(%p) ->\n%s", mediaElement, json.get());
    DDL_DEBUG("RetrieveMessages(%p) ->\n%s", mediaElement,
              json.StringCRef().get());

    // This log exists (new messages or not) -> Resolve this promise.
    DDL_INFO("Resolving promise for HTMLMediaElement[%p] with messages %" PRImi
@@ -495,7 +490,7 @@ void DDMediaLogs::FulfillPromises() {
             log->mMessages.IsEmpty()
                 ? 0
                 : log->mMessages[log->mMessages.Length() - 1].mIndex.Value());
    promiseHolder.Resolve(std::move(json), __func__);
    promiseHolder.Resolve(std::move(json).StringRRef(), __func__);

    // Remove exported messages.
    log->mMessages.Clear();
+4 −10
Original line number Diff line number Diff line
@@ -9,7 +9,7 @@
#include "ChromiumCDMProxy.h"
#include "GMPCrashHelper.h"
#include "mozilla/EMEUtils.h"
#include "mozilla/JSONWriter.h"
#include "mozilla/JSONStringWriteFuncs.h"
#include "mozilla/Telemetry.h"
#include "mozilla/dom/DOMException.h"
#include "mozilla/dom/Document.h"
@@ -716,14 +716,6 @@ void MediaKeys::Unbind() {
  mElement = nullptr;
}

struct StringWriteFunc : public JSONWriteFunc {
  nsString& mString;
  explicit StringWriteFunc(nsString& aString) : mString(aString) {}
  void Write(const Span<const char>& aStr) override {
    mString.Append(NS_ConvertUTF8toUTF16(aStr.data(), aStr.size()));
  }
};

void MediaKeys::CheckIsElementCapturePossible() {
  MOZ_ASSERT(NS_IsMainThread());
  EME_LOG("MediaKeys[%p]::IsElementCapturePossible()", this);
@@ -761,11 +753,13 @@ void MediaKeys::CheckIsElementCapturePossible() {

  if (mCaptureCheckRequestJson.IsEmpty()) {
    // Lazily populate the JSON the first time we need it.
    JSONWriter jw{MakeUnique<StringWriteFunc>(mCaptureCheckRequestJson)};
    JSONStringWriteFunc<nsAutoCString> json;
    JSONWriter jw{json};
    jw.Start();
    jw.StringProperty("status", "is-capture-possible");
    jw.StringProperty("keySystem", NS_ConvertUTF16toUTF8(mKeySystem));
    jw.End();
    mCaptureCheckRequestJson = NS_ConvertUTF8toUTF16(json.StringCRef());
  }

  MOZ_DIAGNOSTIC_ASSERT(!mCaptureCheckRequestJson.IsEmpty());
+6 −17
Original line number Diff line number Diff line
@@ -13,7 +13,7 @@
#include "mozilla/Encoding.h"
#include "mozilla/EventStateManager.h"
#include "mozilla/HoldDropJSObjects.h"
#include "mozilla/JSONWriter.h"
#include "mozilla/JSONStringWriteFuncs.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/Preferences.h"
#include "mozilla/StaticPrefs_dom.h"
@@ -1315,17 +1315,6 @@ bool Notification::IsInPrivateBrowsing() {
  return false;
}

namespace {
struct StringWriteFunc : public JSONWriteFunc {
  nsAString& mBuffer;  // This struct must not outlive this buffer
  explicit StringWriteFunc(nsAString& buffer) : mBuffer(buffer) {}

  void Write(const Span<const char>& aStr) override {
    mBuffer.Append(NS_ConvertUTF8toUTF16(aStr.data(), aStr.size()));
  }
};
}  // namespace

void Notification::ShowInternal() {
  AssertIsOnMainThread();
  MOZ_ASSERT(mTempRef,
@@ -1431,9 +1420,8 @@ void Notification::ShowInternal() {
  NS_ENSURE_SUCCESS_VOID(rv);

  if (isPersistent) {
    nsAutoString persistentData;

    JSONWriter w(MakeUnique<StringWriteFunc>(persistentData));
    JSONStringWriteFunc<nsAutoCString> persistentData;
    JSONWriter w(persistentData);
    w.Start();

    nsAutoString origin;
@@ -1448,7 +1436,8 @@ void Notification::ShowInternal() {

    w.End();

    alertService->ShowPersistentNotification(persistentData, alert,
    alertService->ShowPersistentNotification(
        NS_ConvertUTF8toUTF16(persistentData.StringCRef()), alert,
        alertObserver);
  } else {
    alertService->ShowAlert(alert, alertObserver);
+4 −10
Original line number Diff line number Diff line
@@ -9,19 +9,13 @@
#include "mozilla/dom/Navigator.h"
#include "mozilla/dom/ReportingHeader.h"
#include "mozilla/dom/ReportDeliver.h"
#include "mozilla/JSONWriter.h"
#include "mozilla/JSONStringWriteFuncs.h"
#include "nsIPrincipal.h"
#include "nsIURIMutator.h"
#include "nsString.h"

namespace mozilla::dom {

struct StringWriteFunc : public JSONWriteFunc {
  nsCString& mCString;
  explicit StringWriteFunc(nsCString& aCString) : mCString(aCString) {}
  void Write(const Span<const char>& aStr) override { mCString.Append(aStr); }
};

/* static */
bool CrashReport::Deliver(nsIPrincipal* aPrincipal, bool aIsOOM) {
  MOZ_ASSERT(aPrincipal);
@@ -47,8 +41,8 @@ bool CrashReport::Deliver(nsIPrincipal* aPrincipal, bool aIsOOM) {
  data.mFailures = 0;
  data.mEndpointURL = endpoint_url;

  nsCString body;
  JSONWriter writer{MakeUnique<StringWriteFunc>(body)};
  JSONStringWriteFunc<nsCString> body;
  JSONWriter writer{body};

  writer.Start();
  if (aIsOOM) {
@@ -56,7 +50,7 @@ bool CrashReport::Deliver(nsIPrincipal* aPrincipal, bool aIsOOM) {
  }
  writer.End();

  data.mReportBodyJSON = body;
  data.mReportBodyJSON = std::move(body).StringRRef();

  ReportDeliver::Fetch(data);
  return true;
+9 −16
Original line number Diff line number Diff line
@@ -4,7 +4,7 @@
 * 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/JSONWriter.h"
#include "mozilla/JSONStringWriteFuncs.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/dom/EndpointForReportChild.h"
#include "mozilla/dom/Fetch.h"
@@ -94,18 +94,10 @@ class ReportFetchHandler final : public PromiseNativeHandler {

NS_IMPL_ISUPPORTS0(ReportFetchHandler)

struct StringWriteFunc final : public JSONWriteFunc {
  nsACString&
      mBuffer;  // The lifetime of the struct must be bound to the buffer
  explicit StringWriteFunc(nsACString& aBuffer) : mBuffer(aBuffer) {}

  void Write(const Span<const char>& aStr) override { mBuffer.Append(aStr); }
};

class ReportJSONWriter final : public JSONWriter {
 public:
  explicit ReportJSONWriter(nsACString& aOutput)
      : JSONWriter(MakeUnique<StringWriteFunc>(aOutput)) {}
  explicit ReportJSONWriter(JSONStringWriteFunc<nsAutoCString>& aOutput)
      : JSONWriter(aOutput) {}

  void JSONProperty(const Span<const char>& aProperty,
                    const Span<const char>& aJSON) {
@@ -148,7 +140,7 @@ void SendReports(nsTArray<ReportDeliver::ReportData>& aReports,
  }

  // The body
  nsAutoCString body;
  JSONStringWriteFunc<nsAutoCString> body;
  ReportJSONWriter w(body);

  w.StartArrayElement();
@@ -170,7 +162,8 @@ void SendReports(nsTArray<ReportDeliver::ReportData>& aReports,

  // The body as stream
  nsCOMPtr<nsIInputStream> streamBody;
  nsresult rv = NS_NewCStringInputStream(getter_AddRefs(streamBody), body);
  nsresult rv =
      NS_NewCStringInputStream(getter_AddRefs(streamBody), body.StringCRef());

  // Headers
  IgnoredErrorResult error;
@@ -209,7 +202,7 @@ void SendReports(nsTArray<ReportDeliver::ReportData>& aReports,
  auto internalRequest = MakeSafeRefPtr<InternalRequest>(uriSpec, uriFragment);

  internalRequest->SetMethod("POST"_ns);
  internalRequest->SetBody(streamBody, body.Length());
  internalRequest->SetBody(streamBody, body.StringCRef().Length());
  internalRequest->SetHeaders(internalHeaders);
  internalRequest->SetSkipServiceWorker();
  // TODO: internalRequest->SetContentPolicyType(TYPE_REPORT);
@@ -249,7 +242,7 @@ void ReportDeliver::Record(nsPIDOMWindowInner* aWindow, const nsAString& aType,
  MOZ_ASSERT(aWindow);
  MOZ_ASSERT(aBody);

  nsAutoCString reportBodyJSON;
  JSONStringWriteFunc<nsAutoCString> reportBodyJSON;
  ReportJSONWriter w(reportBodyJSON);

  w.Start();
@@ -283,7 +276,7 @@ void ReportDeliver::Record(nsPIDOMWindowInner* aWindow, const nsAString& aType,
  data.mGroupName = aGroupName;
  data.mURL = aURL;
  data.mCreationTime = TimeStamp::Now();
  data.mReportBodyJSON = reportBodyJSON;
  data.mReportBodyJSON = std::move(reportBodyJSON).StringRRef();
  data.mPrincipal = principal;
  data.mFailures = 0;

Loading