MCPcopy Create free account
hub / github.com/cactus-compute/cactus / Index

Method Index

cactus/engine/engine_index.cpp:34–126  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

32 }
33
34 Index::Index(const std::string& index_path, const std::string& data_path, size_t embedding_dim):
35 index_path_(index_path), data_path_(data_path), embedding_dim_(embedding_dim),
36 index_entry_size_(IndexEntry::size(embedding_dim)), num_documents_(0),
37 index_fd_(-1), data_fd_(-1),
38 mapped_index_(nullptr), mapped_data_(nullptr) {
39
40 bool index_exists = (access(index_path.c_str(), F_OK) == 0);
41 bool data_exists = (access(data_path.c_str(), F_OK) == 0);
42
43 if (index_exists != data_exists) {
44 throw std::runtime_error("Index and data files must both exist or both not exist");
45 }
46
47 index_fd_ = open(index_path.c_str(), O_RDWR | O_CREAT, 0644);
48 if (index_fd_ < 0) {
49 throw std::runtime_error("Cannot open index file: " + index_path);
50 }
51
52 data_fd_ = open(data_path.c_str(), O_RDWR | O_CREAT, 0644);
53 if (data_fd_ < 0) {
54 close(index_fd_);
55 throw std::runtime_error("Cannot open data file: " + data_path);
56 }
57
58 auto cleanup_and_throw = [this](const std::string& msg) {
59 close(index_fd_);
60 close(data_fd_);
61 throw std::runtime_error(msg);
62 };
63
64 struct stat index_st, data_st;
65 if (fstat(index_fd_, &index_st)) {
66 cleanup_and_throw("Cannot get index file size: " + index_path);
67 }
68 index_file_size_ = index_st.st_size;
69
70 if (fstat(data_fd_, &data_st)) {
71 cleanup_and_throw("Cannot get data file size: " + data_path);
72 }
73 data_file_size_ = data_st.st_size;
74
75 if (!index_exists) {
76 index_file_size_ = sizeof(IndexHeader);
77 data_file_size_ = sizeof(DataHeader);
78
79 if (ftruncate(index_fd_, index_file_size_) != 0) {
80 cleanup_and_throw("Failed to resize index file");
81 }
82
83 if (ftruncate(data_fd_, data_file_size_) != 0) {
84 cleanup_and_throw("Failed to resize data file");
85 }
86 }
87
88 mapped_index_ = mmap(nullptr, index_file_size_, PROT_READ | PROT_WRITE, MAP_SHARED, index_fd_, 0);
89 if (mapped_index_ == MAP_FAILED) {
90 cleanup_and_throw("Cannot map file: " + index_path);
91 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected