Skip to content

Instantly share code, notes, and snippets.

@satoruhiga
Created March 24, 2015 18:09
Show Gist options
  • Save satoruhiga/e292b96c62182786cd12 to your computer and use it in GitHub Desktop.
Save satoruhiga/e292b96c62182786cd12 to your computer and use it in GitHub Desktop.
TypedArray.h
#include <vector>
#include <cmath>
#include <assert.h>
class ArrayBuffer
{
public:
ArrayBuffer(size_t size)
: data_(size, 0)
{}
size_t byteLength() const { return data_.size(); }
uint8_t* data() { return data_.data(); }
const uint8_t* data() const { return data_.data(); }
uint8_t* data(size_t byte_offset) { return data_.data() + byte_offset; }
const uint8_t* data(size_t byte_offset) const { return data_.data() + byte_offset; }
public:
template <typename T>
T* data() { return (T*)data(); }
template <typename T>
const T* data() const { return (T*)data(); }
template <typename T>
T* data(size_t byte_offset) { return (T*)data(byte_offset); }
template <typename T>
const T* data(size_t byte_offset) const { return (T*)data(byte_offset); }
template <typename T>
size_t length() const { return byteLength() / sizeof(T); }
protected:
std::vector<uint8_t> data_;
};
template <typename T>
class TypedArray
{
public:
static const size_t BYTES_PER_ELEMENT = sizeof(T);
TypedArray(ArrayBuffer* buffer, size_t byte_offset = 0, size_t stride = 0, size_t length = 0)
: buffer_(buffer)
, byte_offset_(byte_offset)
, stride_(stride == 0 ? BYTES_PER_ELEMENT : stride)
, length_(std::ceil((float)(buffer_->byteLength() - byte_offset_) / this->stride_))
, data_((uint8_t*)buffer_->data() + byte_offset_)
{
if (length)
length_ = std::min<size_t>(length_, length);
}
TypedArray(ArrayBuffer& buffer, size_t byte_offset = 0, size_t stride = 0, size_t length = 0)
: TypedArray(&buffer, byte_offset, stride, length)
{}
size_t byteOffset() const { return byte_offset_; }
size_t stride() const { return stride_; }
size_t length() const { return length_; }
T& operator[](size_t index)
{
assert(index >= 0 && index < length_);
return *(T*)(data_ + (index * stride_));
}
const T& operator[](size_t index) const
{
assert(index >= 0 && index < length_);
return *(const T*)(data_ + (index * stride_));
}
protected:
ArrayBuffer* buffer_;
size_t byte_offset_;
size_t stride_;
size_t length_;
uint8_t* data_;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment