smollerGraph 0.20.2
A small graph database, from scratch
Loading...
Searching...
No Matches
token_store.cc
Go to the documentation of this file.
2
3#include <algorithm>
4#include <cstring>
5#include <optional>
6#include <string>
7
8#include "absl/status/status.h"
9
10namespace smollergraph {
11
12absl::Status TokenStore::Open(const std::string& path) {
13 absl::Status status = file_.Open(path);
14 if (status.ok()) Load();
15 return status;
16}
17
19 absl::Status status = file_.OpenTemporary();
20 if (status.ok()) Load();
21 return status;
22}
23
24void TokenStore::Load() {
25 names_.clear();
26 tokens_.clear();
27 for (TokenId token = 0; token < file_.count(); ++token) {
28 names_.emplace_back(file_.Read(token).name);
29 tokens_.emplace(names_.back(), token);
30 }
31}
32
33TokenId TokenStore::Add(std::string_view name) {
34 if (std::optional<TokenId> found = Find(name)) return *found;
35 TokenRecord record;
36 std::memset(record.name, 0, sizeof(record.name));
37 std::memcpy(record.name, name.data(), std::min(name.size(), kMaxName));
38 TokenId token = file_.Append(record);
39 names_.emplace_back(record.name);
40 tokens_.emplace(names_.back(), token);
41 return token;
42}
43
44std::optional<TokenId> TokenStore::Find(std::string_view name) const {
45 auto found = tokens_.find(name);
46 if (found == tokens_.end()) return std::nullopt;
47 return found->second;
48}
49
50} // namespace smollergraph
TokenId Add(std::string_view name)
Returns the token for name, adding it the first time.
static constexpr size_t kMaxName
The longest name a token can stand for.
Definition token_store.h:36
absl::Status OpenTemporary()
std::optional< TokenId > Find(std::string_view name) const
Returns the token for name, if the store has one.
absl::Status Open(const std::string &path)
Opens the store in the file at path, creating it when it isn't there.
uint32_t TokenId
A number that stands for a name many records share, such as the label Species, so a record keeps four...
Definition token_store.h:20
Path path
Definition plan.cc:115
A token's name on disk. Its id in the file is the token.
Definition token_store.h:26