• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2023-2024 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 #include "intrinsics.h"
17 #include "plugins/ets/runtime/ets_coroutine.h"
18 #include "plugins/ets/runtime/ets_vm.h"
19 #include "plugins/ets/runtime/types/ets_array.h"
20 #include "plugins/ets/runtime/types/ets_arraybuffer.h"
21 #include "plugins/ets/runtime/ets_handle_scope.h"
22 #include "plugins/ets/runtime/ets_handle.h"
23 
24 namespace ark::ets::intrinsics {
EtsArrayBufferFrom(EtsObject * obj)25 extern "C" ObjectHeader *EtsArrayBufferFrom(EtsObject *obj)
26 {
27     EtsCoroutine *coro = EtsCoroutine::GetCurrent();
28     if (obj == nullptr) {
29         LanguageContext ctx = Runtime::GetCurrent()->GetLanguageContext(panda_file::SourceLang::ETS);
30         ThrowNullPointerException(ctx, coro);
31         return nullptr;
32     }
33     if (!obj->GetClass()->IsArrayClass() || !obj->GetClass()->GetComponentType()->IsPrimitive()) {
34         LanguageContext ctx = Runtime::GetCurrent()->GetLanguageContext(panda_file::SourceLang::ETS);
35         ThrowException(ctx, coro, ctx.GetClassCastExceptionClassDescriptor(),
36                        utf::CStringAsMutf8("Object is not an array of primitives"));
37         return nullptr;
38     }
39     [[maybe_unused]] EtsHandleScope s(coro);
40     EtsHandle<EtsArray> array(coro, reinterpret_cast<EtsArray *>(obj));
41     EtsClass *arraybufClass = coro->GetPandaVM()->GetClassLinker()->GetArrayBufferClass();
42     EtsHandle<EtsArrayBuffer> buf(coro, reinterpret_cast<EtsArrayBuffer *>(EtsObject::Create(coro, arraybufClass)));
43     if (UNLIKELY(buf.GetPtr() == nullptr)) {
44         return nullptr;
45     }
46     auto byteLength = static_cast<EtsInt>(array->GetLength() * array->GetElementSize());
47     buf->SetByteLength(byteLength);
48     auto *data = EtsByteArray::Create(byteLength);
49     buf->SetData(coro, data);
50     if (UNLIKELY(buf->GetData() == nullptr)) {
51         return nullptr;
52     }
53     std::copy_n(array->GetData<EtsByte>(), byteLength, buf->GetData()->GetData<EtsByte>());
54     return buf.GetPtr();
55 }
56 }  // namespace ark::ets::intrinsics
57