1 /*
2  * Copyright (c) 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 #include "values_buckets.h"
16 #include "rdb_errno.h"
17 
18 namespace OHOS {
19 namespace NativeRdb {
ValuesBuckets()20 ValuesBuckets::ValuesBuckets()
21 {
22     fields_ = std::make_shared<std::set<std::string>>();
23     values_ = std::make_shared<std::set<ValueObject>>();
24 }
25 
RowSize() const26 size_t ValuesBuckets::RowSize() const
27 {
28     return buckets_.size();
29 }
30 
GetFieldsAndValues() const31 std::pair<ValuesBuckets::FieldsType, ValuesBuckets::ValuesType> ValuesBuckets::GetFieldsAndValues() const
32 {
33     return { fields_, values_ };
34 }
35 
Put(const ValuesBucket & bucket)36 void ValuesBuckets::Put(const ValuesBucket &bucket)
37 {
38     BucketType row;
39     for (const auto &[field, value] : bucket.values_) {
40         auto fieldResult = fields_->insert(field);
41         auto valueResult = values_->insert(value);
42         row.insert(std::make_pair(std::ref(const_cast<std::string &>(*fieldResult.first)),
43                                   std::ref(const_cast<ValueObject &>(*valueResult.first))));
44     }
45     buckets_.push_back(std::move(row));
46 }
47 
Get(size_t row,const FieldType & field) const48 std::pair<int, ValuesBuckets::ValueType> ValuesBuckets::Get(size_t row, const FieldType &field) const
49 {
50     ValueObject empty;
51     std::reference_wrapper<ValueObject> emptyRef(empty);
52     if (row >= buckets_.size()) {
53         return { E_INVALID_ARGS, emptyRef };
54     }
55 
56     auto &bucket = buckets_[row];
57     auto it = bucket.find(field);
58     if (it == bucket.end()) {
59         return { E_INVALID_ARGS, emptyRef };
60     }
61 
62     return { E_OK, it->second };
63 }
64 }
65 }
66