1// Copyright 2015 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include <stdlib.h>
6
7#include "src/v8.h"
8#include "test/cctest/cctest.h"
9
10#include "src/api.h"
11#include "src/heap/heap.h"
12#include "src/objects.h"
13
14using namespace v8::internal;
15
16void TestArrayBufferViewContents(LocalContext& env, bool should_use_buffer) {
17  v8::Local<v8::Object> obj_a = v8::Local<v8::Object>::Cast(
18      env->Global()
19          ->Get(v8::Isolate::GetCurrent()->GetCurrentContext(), v8_str("a"))
20          .ToLocalChecked());
21  CHECK(obj_a->IsArrayBufferView());
22  v8::Local<v8::ArrayBufferView> array_buffer_view =
23      v8::Local<v8::ArrayBufferView>::Cast(obj_a);
24  CHECK_EQ(array_buffer_view->HasBuffer(), should_use_buffer);
25  unsigned char contents[4] = {23, 23, 23, 23};
26  CHECK_EQ(sizeof(contents),
27           array_buffer_view->CopyContents(contents, sizeof(contents)));
28  CHECK_EQ(array_buffer_view->HasBuffer(), should_use_buffer);
29  for (size_t i = 0; i < sizeof(contents); ++i) {
30    CHECK_EQ(i, contents[i]);
31  }
32}
33
34
35TEST(CopyContentsTypedArray) {
36  LocalContext env;
37  v8::HandleScope scope(env->GetIsolate());
38  CompileRun(
39      "var a = new Uint8Array(4);"
40      "a[0] = 0;"
41      "a[1] = 1;"
42      "a[2] = 2;"
43      "a[3] = 3;");
44  TestArrayBufferViewContents(env, false);
45}
46
47
48TEST(CopyContentsArray) {
49  LocalContext env;
50  v8::HandleScope scope(env->GetIsolate());
51  CompileRun("var a = new Uint8Array([0, 1, 2, 3]);");
52  TestArrayBufferViewContents(env, false);
53}
54
55
56TEST(CopyContentsView) {
57  LocalContext env;
58  v8::HandleScope scope(env->GetIsolate());
59  CompileRun(
60      "var b = new ArrayBuffer(6);"
61      "var c = new Uint8Array(b);"
62      "c[0] = -1;"
63      "c[1] = -1;"
64      "c[2] = 0;"
65      "c[3] = 1;"
66      "c[4] = 2;"
67      "c[5] = 3;"
68      "var a = new DataView(b, 2);");
69  TestArrayBufferViewContents(env, true);
70}
71
72
73TEST(AllocateNotExternal) {
74  LocalContext env;
75  v8::HandleScope scope(env->GetIsolate());
76  void* memory = reinterpret_cast<Isolate*>(env->GetIsolate())
77                     ->array_buffer_allocator()
78                     ->Allocate(1024);
79  v8::Local<v8::ArrayBuffer> buffer =
80      v8::ArrayBuffer::New(env->GetIsolate(), memory, 1024,
81                           v8::ArrayBufferCreationMode::kInternalized);
82  CHECK(!buffer->IsExternal());
83  CHECK_EQ(memory, buffer->GetContents().Data());
84}
85