Added typed arrays

This commit is contained in:
Mikhail Lobotskiy
2023-11-13 18:33:14 +04:00
parent 62f5b03bb4
commit 85f86c2de6
4 changed files with 58 additions and 1 deletions

View File

@ -201,6 +201,30 @@ namespace NSJSON
return m_values[index];
}
CTypedArray::CTypedArray(BYTE* data, int len) : IBaseValue(vtTypedArray), m_data(data), m_len(len)
{
}
CTypedArray::~CTypedArray()
{
delete[] m_data;
}
BYTE* CTypedArray::getData()
{
return m_data;
}
const BYTE* CTypedArray::getData() const
{
return m_data;
}
int CTypedArray::getCount() const
{
return m_len;
}
void CObject::addMember(const IBaseValue* pValue, const std::string& name)
{
if (m_type != vtObject)

View File

@ -26,6 +26,7 @@ namespace NSJSON
vtStringA,
vtStringW,
vtArray,
vtTypedArray,
vtObject
};
@ -111,6 +112,25 @@ namespace NSJSON
std::vector<IBaseValue*> m_values;
};
class JS_DECL CTypedArray : public IBaseValue
{
public:
CTypedArray(BYTE* data = nullptr, int len = 0);
// elements get deleted on typed array destruction
virtual ~CTypedArray();
public:
BYTE* getData();
const BYTE* getData() const;
int getCount() const;
friend JSSmart<NSJSBase::CJSValue> toJS(const IBaseValue* pValue);
private:
BYTE* m_data;
int m_len;
};
// extend this class to make custom objects serializable to JS
class JS_DECL CObject : public IBaseValue
{

View File

@ -35,6 +35,12 @@ namespace NSJSON
}
ret = jsArr->toValue();
}
else if (type == IBaseValue::vtTypedArray)
{
const CTypedArray* pTypedArray = static_cast<const CTypedArray*>(pValue);
JSSmart<NSJSBase::CJSTypedArray> jsTypedArr = NSJSBase::CJSContext::createUint8Array(pTypedArray->m_data, pTypedArray->m_len);
ret = jsTypedArr->toValue();
}
else
{
// primitive type

View File

@ -128,8 +128,15 @@ int main()
oTextPr.m_arrNumbers.add(new NSJSON::CValue(0));
NSJSON::CArray* pArray = new NSJSON::CArray();
pArray->add(new NSJSON::CValue(std::string("test!")));
pArray->addNull();
pArray->add(new NSJSON::CValue(3.14));
oTextPr.m_arrNumbers.add(pArray);
BYTE* pData = new BYTE[4];
pData[0] = 0x22;
pData[1] = 0x33;
pData[2] = 0xaa;
pData[3] = 0x45;
NSJSON::CTypedArray* pTypedArray = new NSJSON::CTypedArray(pData, 4);
oTextPr.m_arrNumbers.add(pTypedArray);
JSSmart<CJSObject> jsObj = toJS(&oTextPr)->toObject();
JSSmart<CJSObject> global = pContext->GetGlobal();