xref: /aosp_15_r20/external/federated-compute/fcp/aggregation/core/agg_vector.h (revision 14675a029014e728ec732f129a32e299b2da0601)
1 /*
2  * Copyright 2022 Google LLC
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 #ifndef FCP_AGGREGATION_CORE_AGG_VECTOR_H_
18 #define FCP_AGGREGATION_CORE_AGG_VECTOR_H_
19 
20 #include <cstddef>
21 #include <memory>
22 #include <utility>
23 
24 #include "fcp/aggregation/core/agg_vector_iterator.h"
25 #include "fcp/aggregation/core/tensor_data.h"
26 
27 namespace fcp {
28 namespace aggregation {
29 
30 // AggVector is flattened one-dimensional strongly typed view of tensor that
31 // provides immutable access to the values.
32 //
33 // AggVector hides the actual data organization of the tensor. The only
34 // way to access the tensor values is through the iterator that returns
35 // {index, value} pairs where each index is the dense index corresponding to
36 // the value.
37 //
38 // Example:
39 //
40 // template <typename T>
41 // void Iterate(const AggVector<T>& agg_vector) {
42 //   for (const auto& [index, value] : agg_vector) {
43 //     // Aggregate the `value` at the given `index`.
44 //   }
45 // }
46 //
47 template <typename T>
48 class AggVector final {
49  public:
50   using value_type = typename AggVectorIterator<T>::value_type;
51   using const_iterator = AggVectorIterator<T>;
52 
53   // Iterator begin() function.
begin()54   const_iterator begin() const { return AggVectorIterator<T>(data_); }
55 
56   // Iterator end() function.
end()57   const_iterator end() const { return AggVectorIterator<T>::end(); }
58 
59   // Entire AggVector length.
size()60   size_t size() const { return size_; }
61 
62  private:
63   // AggVector can be created only by Tensor::AsAggVector() method.
64   friend class Tensor;
AggVector(const TensorData * data)65   explicit AggVector(const TensorData* data)
66       : size_(data->byte_size() / sizeof(T)), data_(data) {}
67 
68   // The total length of the vector (in elements).
69   size_t size_;
70   // Tensor data, owned by the tensor object.
71   const TensorData* data_;
72 };
73 
74 }  // namespace aggregation
75 }  // namespace fcp
76 
77 #endif  // FCP_AGGREGATION_CORE_AGG_VECTOR_H_
78