unilink  0.4.3
A simple C++ library for unified async communication
safe_data_buffer.hpp
Go to the documentation of this file.
1 /*
2  * Copyright 2025 Jinwoo Sung
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 #pragma once
18 
19 #include <cstdint>
20 #include <functional>
21 #include <memory>
22 #include <stdexcept>
23 #include <string>
24 #include <string_view>
25 #include <type_traits>
26 #include <vector>
27 
30 
31 namespace unilink {
32 namespace memory {
33 
41  public:
42  // Constructors
43  explicit SafeDataBuffer(const std::string& data);
44  explicit SafeDataBuffer(std::string_view data);
45  explicit SafeDataBuffer(std::vector<uint8_t> data);
46  explicit SafeDataBuffer(const uint8_t* data, size_t size);
47  explicit SafeDataBuffer(const char* data, size_t size);
48  explicit SafeDataBuffer(ConstByteSpan span);
49 
50  // Copy and move constructors
51  SafeDataBuffer(const SafeDataBuffer&) = default;
55 
56  // Destructor
57  ~SafeDataBuffer() = default;
58 
59  // Access methods
60  std::string as_string() const;
61  ConstByteSpan as_span() const noexcept;
62  const uint8_t* data() const noexcept;
63  size_t size() const noexcept;
64  bool empty() const noexcept;
65 
66  // Safe element access
67  const uint8_t& operator[](size_t index) const;
68  const uint8_t& at(size_t index) const;
69 
70  // Comparison operators
71  bool operator==(const SafeDataBuffer& other) const noexcept;
72  bool operator!=(const SafeDataBuffer& other) const noexcept;
73 
74  // Utility methods
75  void clear() noexcept;
76  void reserve(size_t capacity);
77  void resize(size_t new_size);
78 
79  // Validation
80  bool is_valid() const noexcept;
81  void validate() const;
82 
83  private:
84  std::vector<uint8_t> data_;
85 
86  // Helper methods
87  void validate_index(size_t index) const;
88  void validate_construction(const void* ptr, size_t size) const;
89 };
90 
94 using SafeDataHandler = std::function<void(const SafeDataBuffer&)>;
95 
99 namespace safe_buffer_factory {
100 SafeDataBuffer from_string(const std::string& str);
101 SafeDataBuffer from_c_string(const char* str);
102 SafeDataBuffer from_vector(const std::vector<uint8_t>& vec);
103 SafeDataBuffer from_raw_data(const uint8_t* data, size_t size);
105 } // namespace safe_buffer_factory
106 
107 } // namespace memory
108 } // namespace unilink
#define UNILINK_API
Definition: visibility.hpp:37