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/PushUtil.h"
8 
9 namespace mozilla {
10 namespace dom {
11 
CopyArrayBufferToArray(const ArrayBuffer & aBuffer,nsTArray<uint8_t> & aArray)12 /* static */ bool PushUtil::CopyArrayBufferToArray(const ArrayBuffer& aBuffer,
13                                                    nsTArray<uint8_t>& aArray) {
14   MOZ_ASSERT(aArray.IsEmpty());
15   aBuffer.ComputeLengthAndData();
16   return aArray.SetCapacity(aBuffer.Length(), fallible) &&
17          aArray.InsertElementsAt(0, aBuffer.Data(), aBuffer.Length(), fallible);
18 }
19 
CopyArrayBufferViewToArray(const ArrayBufferView & aView,nsTArray<uint8_t> & aArray)20 /* static */ bool PushUtil::CopyArrayBufferViewToArray(
21     const ArrayBufferView& aView, nsTArray<uint8_t>& aArray) {
22   MOZ_ASSERT(aArray.IsEmpty());
23   aView.ComputeLengthAndData();
24   return aArray.SetCapacity(aView.Length(), fallible) &&
25          aArray.InsertElementsAt(0, aView.Data(), aView.Length(), fallible);
26 }
27 
CopyBufferSourceToArray(const OwningArrayBufferViewOrArrayBuffer & aSource,nsTArray<uint8_t> & aArray)28 /* static */ bool PushUtil::CopyBufferSourceToArray(
29     const OwningArrayBufferViewOrArrayBuffer& aSource,
30     nsTArray<uint8_t>& aArray) {
31   if (aSource.IsArrayBuffer()) {
32     return CopyArrayBufferToArray(aSource.GetAsArrayBuffer(), aArray);
33   }
34   if (aSource.IsArrayBufferView()) {
35     return CopyArrayBufferViewToArray(aSource.GetAsArrayBufferView(), aArray);
36   }
37   MOZ_CRASH("Uninitialized union: expected buffer or view");
38 }
39 
CopyArrayToArrayBuffer(JSContext * aCx,const nsTArray<uint8_t> & aArray,JS::MutableHandle<JSObject * > aValue,ErrorResult & aRv)40 /* static */ void PushUtil::CopyArrayToArrayBuffer(
41     JSContext* aCx, const nsTArray<uint8_t>& aArray,
42     JS::MutableHandle<JSObject*> aValue, ErrorResult& aRv) {
43   if (aArray.IsEmpty()) {
44     aValue.set(nullptr);
45     return;
46   }
47   JS::Rooted<JSObject*> buffer(
48       aCx, ArrayBuffer::Create(aCx, aArray.Length(), aArray.Elements()));
49   if (NS_WARN_IF(!buffer)) {
50     aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
51     return;
52   }
53   aValue.set(buffer);
54 }
55 
56 }  // namespace dom
57 }  // namespace mozilla
58