Turi Create  4.0
auto_close_sarray.hpp
1 /* Copyright © 2017 Apple Inc. All rights reserved.
2  *
3  * Use of this source code is governed by a BSD-3-clause license that can
4  * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
5  */
6 #ifndef TURI_UNITY_AUTO_CLOSE_SARRAY
7 #define TURI_UNITY_AUTO_CLOSE_SARRAY
8 
9 namespace turi {
10 /**
11 * helper class to auto open SArray for write in constructor and and then close
12 * the sarray as it is out of scope
13 **/
15 public:
16  auto_close_sarrays(std::vector<flex_type_enum> column_types) {
17  m_columns.resize(column_types.size());
18  for (size_t col_idx = 0; col_idx < column_types.size(); col_idx++) {
19  m_columns[col_idx] = std::make_shared<sarray<flexible_type>>();
20  m_columns[col_idx]->open_for_write();
21  m_columns[col_idx]->set_type(column_types[col_idx]);
22  }
23  }
24 
26  close();
27  }
28 
29  void close() {
30  if (!m_closed) {
31  for(auto column: m_columns) {
32  column->close();
33  }
34  m_closed = true;
35  }
36  }
37 
38  std::vector<std::shared_ptr<sarray<flexible_type>>> get_sarrays() {
39  return m_columns;
40  }
41 
42 private:
43  std::vector<std::shared_ptr<sarray<flexible_type>>> m_columns;
44  bool m_closed = false;
45 };
46 
47 }
48 #endif