Skip to content

Commit 09b61b7

Browse files
authored
feat: store message as a shared constant char array (#108)
* feat: use `const char*` for the `msg` parameter in the `make` function * feat: store `Error::message` as `std::shared_ptr<const char[]>` * feat: use `std::string_view` for the `msg` parameter in the `make` function * style: rename `Error::message_ptr` to `Error::msg_ptr`
1 parent 190dfc3 commit 09b61b7

File tree

2 files changed

+14
-10
lines changed

2 files changed

+14
-10
lines changed

include/errors/error.hpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@ namespace errors {
1313
*/
1414
class [[nodiscard]] Error {
1515
private:
16-
const std::shared_ptr<const std::string> message_ptr;
16+
const std::shared_ptr<const char[]> msg_ptr;
1717

18-
Error(const std::shared_ptr<const std::string>& message_ptr);
18+
Error(const std::shared_ptr<const char[]>& msg_ptr);
1919

2020
public:
2121
/**
@@ -47,7 +47,7 @@ class [[nodiscard]] Error {
4747
*/
4848
explicit operator bool() const;
4949

50-
friend Error make(const std::string& msg);
50+
friend Error make(std::string_view msg);
5151
friend const Error& nil();
5252

5353
/**
@@ -76,7 +76,7 @@ class [[nodiscard]] Error {
7676
* @param msg The error message.
7777
* @return A new error object.
7878
*/
79-
Error make(const std::string& msg);
79+
Error make(std::string_view msg);
8080

8181

8282
/**

src/error.cpp

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,28 @@
1+
#include <algorithm>
12
#include <errors/error.hpp>
23

34
namespace errors {
45

5-
Error::Error(const std::shared_ptr<const std::string>& message_ptr) : message_ptr(message_ptr) {}
6+
Error::Error(const std::shared_ptr<const char[]>& msg_ptr) : msg_ptr(msg_ptr) {}
67

78
std::string_view Error::message() const {
8-
if (!message_ptr) return "no error";
9-
return *message_ptr;
9+
if (!msg_ptr) return "no error";
10+
return msg_ptr.get();
1011
}
1112

1213
Error::operator bool() const {
13-
return (bool)message_ptr;
14+
return (bool)msg_ptr;
1415
}
1516

1617
std::ostream& operator<<(std::ostream& os, const errors::Error& err) {
1718
return os << "error: " << err.message();
1819
}
1920

20-
Error make(const std::string& msg) {
21-
return Error(std::make_shared<const std::string>(msg));
21+
Error make(std::string_view msg) {
22+
auto c_msg = new char[msg.size() + 1];
23+
msg.copy(c_msg, msg.size());
24+
c_msg[msg.size()] = 0;
25+
return Error(std::shared_ptr<const char[]>(c_msg));
2226
}
2327

2428
const Error& nil() {

0 commit comments

Comments
 (0)