Skip to content

Store Message as a Shared Constant Char Array #108

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Dec 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions include/errors/error.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ namespace errors {
*/
class Error {
private:
const std::shared_ptr<const std::string> message_ptr;
const std::shared_ptr<const char[]> msg_ptr;

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

public:
/**
Expand Down Expand Up @@ -47,7 +47,7 @@ class Error {
*/
explicit operator bool() const;

friend Error make(const std::string& msg);
friend Error make(std::string_view msg);
friend const Error& nil();

/**
Expand Down Expand Up @@ -76,7 +76,7 @@ class Error {
* @param msg The error message.
* @return A new error object.
*/
Error make(const std::string& msg);
Error make(std::string_view msg);


/**
Expand Down
16 changes: 10 additions & 6 deletions src/error.cpp
Original file line number Diff line number Diff line change
@@ -1,24 +1,28 @@
#include <algorithm>
#include <errors/error.hpp>

namespace errors {

Error::Error(const std::shared_ptr<const std::string>& message_ptr) : message_ptr(message_ptr) {}
Error::Error(const std::shared_ptr<const char[]>& msg_ptr) : msg_ptr(msg_ptr) {}

std::string_view Error::message() const {
if (!message_ptr) return "no error";
return *message_ptr;
if (!msg_ptr) return "no error";
return msg_ptr.get();
}

Error::operator bool() const {
return (bool)message_ptr;
return (bool)msg_ptr;
}

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

Error make(const std::string& msg) {
return Error(std::make_shared<const std::string>(msg));
Error make(std::string_view msg) {
auto c_msg = new char[msg.size() + 1];
msg.copy(c_msg, msg.size());
c_msg[msg.size()] = 0;
return Error(std::shared_ptr<const char[]>(c_msg));
}

const Error& nil() {
Expand Down