Imported Upstream version 1.7.0
[platform/core/ml/nnfw.git] / compiler / luci-interpreter / src / core / Tensor.cpp
1 /*
2  * Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *    http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "luci_interpreter/core/Tensor.h"
18
19 #include <cstring>
20 #include <stdexcept>
21
22 namespace luci_interpreter
23 {
24
25 Tensor::Tensor(DataType element_type, Shape shape, AffineQuantization quantization,
26                std::string name)
27     : _element_type(element_type), _shape(std::move(shape)), _quantization(std::move(quantization)),
28       _name(std::move(name))
29 {
30   const size_t element_size = getDataTypeSize(_element_type);
31   const int32_t num_elements = _shape.num_elements();
32   _data = std::make_unique<uint8_t[]>(num_elements * element_size);
33 }
34
35 void Tensor::readData(void *data_ptr, size_t data_size) const
36 {
37   const size_t element_size = getDataTypeSize(element_type());
38   const int32_t num_elements = shape().num_elements();
39   if (data_size != num_elements * element_size)
40   {
41     throw std::invalid_argument("Invalid data size.");
42   }
43   assert(data_ptr != nullptr);
44   std::memcpy(data_ptr, data<void>(), data_size);
45 }
46
47 void Tensor::writeData(const void *data_ptr, size_t data_size)
48 {
49   const size_t element_size = getDataTypeSize(element_type());
50   const int32_t num_elements = shape().num_elements();
51   if (data_size != num_elements * element_size)
52   {
53     throw std::invalid_argument("Invalid data size.");
54   }
55   assert(data_ptr != nullptr);
56   std::memcpy(data<void>(), data_ptr, data_size);
57 }
58
59 void Tensor::resize(const Shape &new_shape)
60 {
61   _shape = new_shape;
62   const size_t element_size = getDataTypeSize(_element_type);
63   const int32_t num_elements = _shape.num_elements();
64   // NOTE: _data can be nullptr for empty tensors
65   _data = std::make_unique<uint8_t[]>(num_elements * element_size);
66 }
67
68 } // namespace luci_interpreter