1/*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#ifndef ECMASCRIPT_BYTE_ARRAY_H
17#define ECMASCRIPT_BYTE_ARRAY_H
18
19#include "ecmascript/js_hclass.h"
20#include "ecmascript/js_tagged_value.h"
21#include "ecmascript/js_dataview.h"
22
23namespace panda::ecmascript {
24class ObjectFactory;
25class JSThread;
26
27class ByteArray : public TaggedObject {
28public:
29    CAST_CHECK(ByteArray, IsByteArray);
30
31    static inline size_t ComputeSize(size_t elemSize, uint32_t length)
32    {
33        ASSERT(elemSize != 0);
34        size_t size = DATA_OFFSET + elemSize * length;
35        return size;
36    }
37
38    static inline size_t ComputeDataSize(size_t elemSize, uint32_t length)
39    {
40        ASSERT(elemSize != 0);
41        return elemSize * length;
42    }
43
44    size_t GetPointerLength()
45    {
46        size_t byteSize = ComputeDataSize(GetArrayLength(), GetByteLength());
47        return AlignUp(byteSize, static_cast<size_t>(MemAlignment::MEM_ALIGN_OBJECT)) / sizeof(JSTaggedType);
48    }
49
50    inline void *GetData(uint32_t index = 0) const
51    {
52        return reinterpret_cast<void *>(ToUintPtr(this) + DATA_OFFSET + index * GetByteLength());
53    }
54
55    void Set(JSThread* thread, uint32_t idx, DataViewType type, JSTaggedType val, uint32_t offset = 0);
56    JSTaggedValue Get(JSThread *thread, uint32_t idx, DataViewType type, uint32_t offset = 0);
57
58    static constexpr size_t ARRAY_LENGTH_OFFSET = TaggedObjectSize();
59    ACCESSORS_PRIMITIVE_FIELD(ArrayLength, uint32_t, ARRAY_LENGTH_OFFSET, BYTE_LENGTH_OFFSET)
60    ACCESSORS_PRIMITIVE_FIELD(ByteLength, uint32_t, BYTE_LENGTH_OFFSET, LAST_OFFSET)
61    DEFINE_ALIGN_SIZE(LAST_OFFSET);
62    static constexpr size_t DATA_OFFSET = SIZE;  // DATA_OFFSET equal to Empty ByteArray size
63
64    DECL_VISIT_ARRAY(DATA_OFFSET, 0, GetPointerLength());
65    DECL_DUMP()
66
67private:
68    friend class ObjectFactory;
69};
70
71static_assert(ByteArray::ARRAY_LENGTH_OFFSET == sizeof(TaggedObject));
72static_assert((ByteArray::DATA_OFFSET % static_cast<uint8_t>(MemAlignment::MEM_ALIGN_OBJECT)) == 0);
73}  // namespace panda::ecmascript
74#endif  // ECMASCRIPT_BYTE_ARRAY_H
75