added iOS source code
[wl-app.git] / iOS / Pods / Realm / include / core / realm / owned_data.hpp
1 /*************************************************************************
2  *
3  * Copyright 2016 Realm Inc.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  **************************************************************************/
18
19 #ifndef REALM_OWNED_DATA_HPP
20 #define REALM_OWNED_DATA_HPP
21
22 #include <realm/util/assert.hpp>
23
24 #include <cstring>
25 #include <memory>
26
27 namespace realm {
28
29 /// A chunk of owned data.
30 class OwnedData {
31 public:
32     /// Construct a null reference.
33     OwnedData() noexcept
34     {
35     }
36
37     /// If \a data_to_copy is 'null', \a data_size must be zero.
38     OwnedData(const char* data_to_copy, size_t data_size)
39         : m_size(data_size)
40     {
41         REALM_ASSERT_DEBUG(data_to_copy || data_size == 0);
42         if (data_to_copy) {
43             m_data = std::unique_ptr<char[]>(new char[data_size]);
44             memcpy(m_data.get(), data_to_copy, data_size);
45         }
46     }
47
48     /// If \a unique_data is 'null', \a data_size must be zero.
49     OwnedData(std::unique_ptr<char[]> unique_data, size_t data_size) noexcept
50         : m_data(std::move(unique_data))
51         , m_size(data_size)
52     {
53         REALM_ASSERT_DEBUG(m_data || m_size == 0);
54     }
55
56     OwnedData(const OwnedData& other)
57         : OwnedData(other.m_data.get(), other.m_size)
58     {
59     }
60     OwnedData& operator=(const OwnedData& other);
61
62     OwnedData(OwnedData&&) = default;
63     OwnedData& operator=(OwnedData&&) = default;
64
65     const char* data() const
66     {
67         return m_data.get();
68     }
69     size_t size() const
70     {
71         return m_size;
72     }
73
74 private:
75     std::unique_ptr<char[]> m_data;
76     size_t m_size = 0;
77 };
78
79 inline OwnedData& OwnedData::operator=(const OwnedData& other)
80 {
81     if (this != &other) {
82         if (other.m_data) {
83             m_data = std::unique_ptr<char[]>(new char[other.m_size]);
84             memcpy(m_data.get(), other.m_data.get(), other.m_size);
85         }
86         else {
87             m_data = nullptr;
88         }
89         m_size = other.m_size;
90     }
91     return *this;
92 }
93
94 } // namespace realm
95
96 #endif // REALM_OWNED_DATA_HPP