/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-*/ /* vim: set ts=2 sw=2 et tw=79: */ /* 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/. */ #ifndef mozilla_dom_TypedArray_h #define mozilla_dom_TypedArray_h #include "jsfriendapi.h" #include "js/RootingAPI.h" namespace mozilla { namespace dom { /* * Various typed array classes for argument conversion. We have a base class * that has a way of initializing a TypedArray from an existing typed array, and * a subclass of the base class that supports creation of a relevant typed array * or array buffer object. */ template struct TypedArray_base { TypedArray_base(JSObject* obj) : mObj(NULL), mData(NULL), mLength(0), mComputed(false) { Init(obj); } private: JSObject* mObj; mutable T* mData; mutable uint32_t mLength; mutable bool mComputed; public: inline bool Init(JSObject* obj) { MOZ_ASSERT(!inited()); DoInit(obj); return inited(); } inline bool inited() const { return !!mObj; } inline T *Data() const { MOZ_ASSERT(mComputed); return mData; } inline uint32_t Length() const { MOZ_ASSERT(mComputed); return mLength; } inline JSObject *Obj() const { MOZ_ASSERT(inited()); return mObj; } inline void ComputeLengthAndData() const { MOZ_ASSERT(inited()); MOZ_ASSERT(!mComputed); GetLengthAndData(mObj, &mLength, &mData); mComputed = true; } protected: inline void DoInit(JSObject* obj) { mObj = UnwrapArray(obj); } }; template struct TypedArray : public TypedArray_base { TypedArray(JSObject* obj) : TypedArray_base(obj) {} static inline JSObject* Create(JSContext* cx, nsWrapperCache* creator, uint32_t length, const T* data = NULL) { JS::Rooted creatorWrapper(cx); Maybe ac; if (creator && (creatorWrapper = creator->GetWrapperPreserveColor())) { ac.construct(cx, creatorWrapper); } JSObject* obj = CreateNew(cx, length); if (!obj) { return NULL; } if (data) { T* buf = static_cast(GetData(obj)); memcpy(buf, data, length*sizeof(T)); } return obj; } }; typedef TypedArray Int8Array; typedef TypedArray Uint8Array; typedef TypedArray Uint8ClampedArray; typedef TypedArray Int16Array; typedef TypedArray Uint16Array; typedef TypedArray Int32Array; typedef TypedArray Uint32Array; typedef TypedArray Float32Array; typedef TypedArray Float64Array; typedef TypedArray_base ArrayBufferView; typedef TypedArray ArrayBuffer; } // namespace dom } // namespace mozilla #endif /* mozilla_dom_TypedArray_h */