Vince's CSV Parser
Loading...
Searching...
No Matches
key_storage.hpp
1#pragma once
2
3#include <memory>
4#include <stdexcept>
5#include <string>
6#include <utility>
7#include <vector>
8
9#include "../csv_exceptions.hpp"
10
11namespace csv {
12 namespace internals {
13 namespace data_frame {
14 // Owning key types need no additional lifetime handling or runtime work.
15 template<typename KeyType>
16 class KeyStorage {
17 public:
18 template<typename InvalidateIndex>
19 inline bool preserve(std::vector<KeyType>&, const InvalidateIndex&, CSVError& error) const {
20 error.clear();
21 return true;
22 }
23 };
24
28 template<>
30 public:
31 template<typename InvalidateIndex>
32 inline bool preserve(std::vector<csv::string_view>& keys, const InvalidateIndex& invalidate_index, CSVError& error) {
33 error.clear();
34 if (keys.empty()) {
36 this->storage_.reset();
37 return true;
38 }
39
40 std::unique_ptr<std::string> storage(new std::string());
41 size_t bytes = 0;
42 for (const auto& key : keys) {
43 if (key.size() > storage->max_size() - bytes) {
44 return fail_static(error, CSVErrorCode::SizeLimitExceeded, "DataFrame key storage is too large");
45 }
46 bytes += key.size();
47 }
48 storage->reserve(bytes);
49 for (const auto& key : keys) {
50 if (!key.empty()) {
51 storage->append(key.data(), key.size());
52 }
53 }
54
55 // Form views only after the last append. Heap-own the string object
56 // so even its small-string buffer stays stable across frame moves.
57 std::vector<csv::string_view> preserved;
58 preserved.reserve(keys.size());
59 size_t offset = 0;
60 for (const auto& key : keys) {
61 preserved.emplace_back(storage->data() + offset, key.size());
62 offset += key.size();
63 }
64 // Drop index views while both old backing stores are still alive.
66 keys.swap(preserved);
67 this->storage_ = std::move(storage);
68 return true;
69 }
70
71 private:
72 std::unique_ptr<std::string> storage_;
73 };
74 }
75 }
76}
Borrow a row and error state for synchronous, single-pass field access.
The all encompassing namespace.
@ SizeLimitExceeded
Combined preserved string-view key bytes exceed std::string::max_size().
std::string_view string_view
The string_view class used by this library.
Definition common.hpp:182
A diagnostic whose text remains valid for the lifetime of the error.
Definition csv_error.hpp:94