Fixed up ArrayBuffer::slice() behaviour

This commit is contained in:
Atlante45 2014-07-07 18:58:53 -07:00
parent f9b739a0d1
commit 96a1390d8f
2 changed files with 27 additions and 3 deletions

View file

@ -9,8 +9,11 @@
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include <QDebug>
#include <QScriptEngine>
#include <glm/glm.hpp>
#include "ArrayBufferClass.h"
#include "ArrayBufferPrototype.h"
@ -21,7 +24,27 @@ ArrayBufferPrototype::ArrayBufferPrototype(QObject* parent) : QObject(parent) {
}
QByteArray ArrayBufferPrototype::slice(long begin, long end) const {
return thisArrayBuffer()->mid(begin, end);
QByteArray* ba = thisArrayBuffer();
// if indices < 0 then they start from the end of the array
begin = (begin < 0) ? ba->size() + begin : begin;
end = (end < 0) ? ba->size() + end : end;
// here we clamp the indices to fit the array
begin = glm::clamp(begin, 0l, (long)(ba->size() - 1));
end = glm::clamp(end, 0l, (long)(ba->size() - 1));
return (end - begin > 0) ? ba->mid(begin, end - begin) : QByteArray();
}
QByteArray ArrayBufferPrototype::slice(long begin) const {
QByteArray* ba = thisArrayBuffer();
// if indices < 0 then they start from the end of the array
begin = (begin < 0) ? ba->size() + begin : begin;
// here we clamp the indices to fit the array
begin = glm::clamp(begin, 0l, (long)(ba->size() - 1));
return ba->mid(begin, -1);
}
QByteArray* ArrayBufferPrototype::thisArrayBuffer() const {

View file

@ -22,8 +22,9 @@ class ArrayBufferPrototype : public QObject, public QScriptable {
public:
ArrayBufferPrototype(QObject* parent = NULL);
public slots:
QByteArray slice(long begin, long end = -1) const;
public slots:
QByteArray slice(long begin, long end) const;
QByteArray slice(long begin) const;
private:
QByteArray* thisArrayBuffer() const;