xref: /aosp_15_r20/external/icing/icing/index/embed/embedding-hit.h (revision 8b6cd535a057e39b3b86660c4aa06c99747c2136)
1 // Copyright (C) 2024 Google LLC
2 //
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 #ifndef ICING_INDEX_EMBED_EMBEDDING_HIT_H_
16 #define ICING_INDEX_EMBED_EMBEDDING_HIT_H_
17 
18 #include <cstdint>
19 
20 #include "icing/index/hit/hit.h"
21 
22 namespace icing {
23 namespace lib {
24 
25 class EmbeddingHit {
26  public:
27   // Order: basic_hit, location
28   // Value bits layout: 32 basic_hit + 32 location
29   using Value = uint64_t;
30 
31   // WARNING: Changing this value will invalidate any pre-existing posting lists
32   // on user devices.
33   //
34   // kInvalidValue contains:
35   // - BasicHit of value 0, which is invalid.
36   // - location of 0 (valid), which is ok because BasicHit is already invalid.
37   static_assert(BasicHit::kInvalidValue == 0);
38   static constexpr Value kInvalidValue = 0;
39 
EmbeddingHit(BasicHit basic_hit,uint32_t location)40   explicit EmbeddingHit(BasicHit basic_hit, uint32_t location) {
41     value_ = (static_cast<uint64_t>(basic_hit.value()) << 32) | location;
42   }
43 
EmbeddingHit(Value value)44   explicit EmbeddingHit(Value value) : value_(value) {}
45 
46   // BasicHit contains the document id and the section id.
basic_hit()47   BasicHit basic_hit() const { return BasicHit(value_ >> 32); }
48   // The location of the referred embedding vector in the vector storage.
location()49   uint32_t location() const { return value_ & 0xFFFFFFFF; };
50 
is_valid()51   bool is_valid() const { return basic_hit().is_valid(); }
value()52   Value value() const { return value_; }
53 
54   bool operator<(const EmbeddingHit& h2) const { return value_ < h2.value_; }
55   bool operator==(const EmbeddingHit& h2) const { return value_ == h2.value_; }
56 
57  private:
58   Value value_;
59 };
60 
61 static_assert(sizeof(BasicHit) == 4);
62 static_assert(sizeof(EmbeddingHit) == 8);
63 
64 }  // namespace lib
65 }  // namespace icing
66 
67 #endif  // ICING_INDEX_EMBED_EMBEDDING_HIT_H_
68