summaryrefslogtreecommitdiff
path: root/cabinet/magic.cpp
diff options
context:
space:
mode:
authorFelix Morgner <felix.morgner@gmail.com>2026-06-04 19:42:02 +0200
committerFelix Morgner <felix.morgner@gmail.com>2026-06-04 19:42:02 +0200
commit11df846b1ec951dd35feb9b0bad42486c7b94dca (patch)
tree3e94acde315473011793cad482f23f1adf02fc98 /cabinet/magic.cpp
parent240e7804156c5c374d4cf1216161f4feefd3fcb1 (diff)
downloadcabinet-11df846b1ec951dd35feb9b0bad42486c7b94dca.tar.xz
cabinet-11df846b1ec951dd35feb9b0bad42486c7b94dca.zip
magic: refactor construction
Diffstat (limited to 'cabinet/magic.cpp')
-rw-r--r--cabinet/magic.cpp48
1 files changed, 45 insertions, 3 deletions
diff --git a/cabinet/magic.cpp b/cabinet/magic.cpp
index f8d7337..96e212f 100644
--- a/cabinet/magic.cpp
+++ b/cabinet/magic.cpp
@@ -2,18 +2,60 @@
#include <magic.h>
+#include <cerrno>
+#include <expected>
+#include <string_view>
+#include <system_error>
#include <utility>
namespace cab
{
- magic::magic(magic::flags flags)
- : m_cookie{magic_open(std::to_underlying(flags))}
+ auto magic::open(magic::flags flags, std::string_view database) noexcept -> std::expected<magic, std::error_code>
+ {
+ auto cookie = magic_open(std::to_underlying(flags));
+ if (!cookie)
+ {
+ return std::unexpected{
+ std::error_code{errno, std::system_category()}
+ };
+ }
+
+ if (auto success = magic_load(cookie, database.data()); success < 0)
+ {
+ return std::unexpected{std::make_error_code(std::errc::invalid_argument)};
+ }
+
+ return magic{cookie};
+ }
+
+ magic::magic(::magic_t cookie) noexcept
+ : m_cookie{cookie}
+ {}
+
+ magic::magic(magic && other) noexcept
+ : m_cookie{std::exchange(other.m_cookie, nullptr)}
{}
magic::~magic()
{
- magic_close(m_cookie);
+ if (m_cookie)
+ {
+ magic_close(m_cookie);
+ }
+ }
+
+ auto magic::operator=(magic && other) noexcept -> magic &
+ {
+ std::swap(m_cookie, other.m_cookie);
+ return *this;
+ }
+
+ auto swap(magic & lhs, magic & rhs) noexcept -> void
+ {
+ auto temp = std::move(lhs);
+ lhs = std::move(rhs);
+ rhs = std::move(lhs);
}
} // namespace cab