Libmagicxx v10.0.3
A modern C++23 wrapper for libmagic — the library that powers the Unix file command.
Loading...
Searching...
No Matches
Recognition::Magic::MagicPrivate Class Reference

PIMPL implementation class for Magic. More...

Classes

struct  FlagsConverter
 Converter between C++ flag types and libmagic flag values. More...
struct  LibmagicPairConverter
 Extracts values from libmagic constant pairs. More...

Public Types

enum  IdentifyFileOptions : unsigned long long {
  CheckNothing = 0ULL , CheckIsValid = 1ULL << 0 , CheckPathEmpty = 1ULL << 1 , CheckPathExists = 1ULL << 2 ,
  CheckPath = CheckPathEmpty | CheckPathExists , CheckEverything = CheckIsValid | CheckPath
}
 Options controlling file identification precondition checks. More...
using IdentifyFileOptionsMaskT = std::bitset<3uz>
 Bitmask type for file identification validation options.

Public Member Functions

 MagicPrivate () noexcept=default
 Default constructor creates a closed instance.
 MagicPrivate (FlagsMaskT flags_mask, const std::filesystem::path &database_file)
 Construct and initialize with flags (throwing version).
 MagicPrivate (FlagsMaskT flags_mask, const std::nothrow_t &tag, const std::filesystem::path &database_file) noexcept
 Construct and initialize with flags (noexcept version).
 MagicPrivate (const FlagsContainerT &flags_container, const std::filesystem::path &database_file)
 Construct with flags container (throwing version).
 MagicPrivate (const FlagsContainerT &flags_container, const std::nothrow_t &tag, const std::filesystem::path &database_file) noexcept
 Construct with flags container (noexcept version).
 MagicPrivate (MagicPrivate &&) noexcept=default
 Move constructor.
 MagicPrivate (const MagicPrivate &)=delete
 Deleted copy constructor.
MagicPrivateoperator= (MagicPrivate &&) noexcept=default
 Move assignment operator.
MagicPrivateoperator= (const MagicPrivate &)=delete
 Deleted copy assignment operator.
 ~MagicPrivate ()=default
 Destructor.
bool Check (const std::filesystem::path &database_file) const noexcept
 Check if a magic database file is valid.
bool Compile (const std::filesystem::path &database_file) const noexcept
 Compile a magic database from source.
FlagsContainerT GetFlags () const
 Get current flags (throwing version).
std::optional< FlagsContainerTGetFlags (const std::nothrow_t &tag) const noexcept
 Get current flags (noexcept version).
std::size_t GetParameter (Parameters parameter) const
 Get a single parameter value (throwing version).
std::optional< std::size_t > GetParameter (Parameters parameter, const std::nothrow_t &tag) const noexcept
 Get a single parameter value (noexcept version).
ParameterValueMapT GetParameters () const
 Get all parameter values (throwing version).
std::optional< ParameterValueMapTGetParameters (const std::nothrow_t &tag) const noexcept
 Get all parameter values (noexcept version).
FileTypeT IdentifyFile (const std::filesystem::path &path, IdentifyFileOptionsMaskT options) const
 Identify a single file's type (throwing version).
ExpectedFileTypeT IdentifyFile (const std::filesystem::path &path, IdentifyFileOptionsMaskT options, const std::nothrow_t &tag) const noexcept
 Identify a single file's type (noexcept version).
DefaultFileContainerT IdentifyDirectoryPreliminaryChecks (const std::filesystem::path &directory, std::filesystem::directory_options option, ProgressTrackerT progress_tracker) const
 Validate preconditions for directory identification (throwing).
std::optional< DefaultFileContainerTIdentifyDirectoryPreliminaryChecks (const std::filesystem::path &directory, const std::nothrow_t &tag, std::filesystem::directory_options option, ProgressTrackerT progress_tracker) const noexcept
 Validate preconditions for directory identification (noexcept).
void IdentifyContainerPreliminaryChecks (ProgressTrackerT progress_tracker) const
 Validate preconditions for container identification (throwing).
bool IdentifyContainerPreliminaryChecks (const std::nothrow_t &tag, ProgressTrackerT progress_tracker) const noexcept
 Validate preconditions for container identification (noexcept).
FileTypeMapT IdentifyFiles (const DefaultFileContainerT &files, IdentifyFileOptionsMaskT option, ProgressTrackerT progress_tracker) const
 Identify multiple files with progress tracking (throwing).
ExpectedFileTypeMapT IdentifyFiles (const DefaultFileContainerT &files, const std::nothrow_t &tag, IdentifyFileOptionsMaskT option, ProgressTrackerT progress_tracker) const noexcept
 Identify multiple files with progress tracking (noexcept).
bool IsDatabaseLoaded () const noexcept
 Check if a database is loaded.
bool IsOpen () const noexcept
 Check if instance is open.
bool IsValid () const noexcept
 Check if instance is valid for file identification.
void LoadDatabaseFile (const std::filesystem::path &database_file)
 Load a magic database file (throwing version).
bool LoadDatabaseFile (const std::nothrow_t &tag, const std::filesystem::path &database_file) noexcept
 Load a magic database file (noexcept version).
void Open (FlagsMaskT flags_mask)
 Open the magic instance with flags (throwing version).
bool Open (FlagsMaskT flags_mask, const std::nothrow_t &tag) noexcept
 Open the magic instance with flags (noexcept version).
void Open (const FlagsContainerT &flags_container)
 Open with flags container (throwing version).
bool Open (const FlagsContainerT &flags_container, const std::nothrow_t &tag) noexcept
 Open with flags container (noexcept version).
void SetFlags (FlagsMaskT flags_mask)
 Set new flags for the instance (throwing version).
bool SetFlags (FlagsMaskT flags_mask, const std::nothrow_t &tag) noexcept
 Set new flags for the instance (noexcept version).
void SetFlags (const FlagsContainerT &flags_container)
 Set new flags from container (throwing version).
bool SetFlags (const FlagsContainerT &flags_container, const std::nothrow_t &tag) noexcept
 Set new flags from container (noexcept version).
void SetParameter (Parameters parameter, std::size_t value)
 Set a single parameter value (throwing version).
bool SetParameter (Parameters parameter, std::size_t value, const std::nothrow_t &tag) noexcept
 Set a single parameter value (noexcept version).
void SetParameters (const ParameterValueMapT &parameters)
 Set multiple parameter values (throwing version).
bool SetParameters (const ParameterValueMapT &parameters, const std::nothrow_t &tag) noexcept
 Set multiple parameter values (noexcept version).

Static Public Member Functions

template<std::derived_from< MagicException > ExceptionT, typename ResultT, typename... ExceptionArgsT>
requires std::same_as<ResultT, int> || std::same_as<ResultT, bool>
static void ThrowExceptionOnFailure (ResultT result, ExceptionArgsT &&... args)
 Centralized error handling template.

Private Types

using CookieT
 RAII cookie type wrapping libmagic handle.
using LibmagicValueT = int
using LibmagicValueNameT = std::string
using LibmagicPairT
using LibmagicFlagsT = std::array<LibmagicPairT, LIBMAGIC_FLAGS_COUNT>
using LibmagicParametersT

Private Member Functions

std::string GetErrorMessage () const noexcept
 Retrieve the last error message from libmagic.

Private Attributes

CookieT m_cookie {nullptr}
FlagsMaskT m_flags_mask {0}
bool m_is_database_loaded

Static Private Attributes

static constexpr IdentifyFileOptionsMaskT CHECK_IS_VALID_OPTION
static constexpr IdentifyFileOptionsMaskT CHECK_PATH_EMPTY_OPTION
static constexpr IdentifyFileOptionsMaskT CHECK_PATH_EXISTS_OPTION
static constexpr auto LIBMAGIC_ERROR
static constexpr auto LIBMAGIC_FLAGS_COUNT
static constexpr auto LIBMAGIC_PARAMETER_COUNT
static constexpr LibmagicPairT LIBMAGIC_FLAG_NONE
 The MAGIC_NONE flag pair for default output.
static constexpr LibmagicFlagsT LIBMAGIC_FLAGS
 Mapping from Magic::Flags bit positions to libmagic constants.
static constexpr LibmagicParametersT LIBMAGIC_PARAMETERS
 Mapping from Magic::Parameters enum to libmagic constants.

Friends

std::string ToString (Magic::Flags flag)
 Convert a Magic flag to its string name.
std::string ToString (Magic::Parameters parameter)
 Convert a Magic parameter to its string name.

Detailed Description

PIMPL implementation class for Magic.

MagicPrivate encapsulates all libmagic interactions and maintains the internal state of a Magic instance. This class is the heart of the implementation, providing:

  • Cookie Management: RAII wrapper for magic_t handle
  • Flag Conversion: Bidirectional conversion between C++ and C flags
  • Error Handling: Template-based exception throwing
  • State Tracking: m_cookie and m_is_database_loaded flags

Design Patterns

PIMPL Pattern

MagicPrivate implements the Pointer to IMPLementation (PIMPL) idiom:

// In magic.hpp (public header)
class Magic {
class MagicPrivate; // Forward declaration only
std::unique_ptr<MagicPrivate> m_impl; // Pointer to implementation
};
// In magic.cpp (implementation file)
class Magic::MagicPrivate { ... }; // Full definition here
PIMPL implementation class for Magic.
Definition magic.cpp:222
std::unique_ptr< MagicPrivate > m_impl
Pointer to the implementation (Pimpl idiom).
Definition magic.hpp:1653
Magic() noexcept
Default constructor. Creates an unopened Magic instance.
Definition magic.cpp:2421
MagicPrivate() noexcept=default
Default constructor creates a closed instance.

This provides:

  • Compilation Firewall: Changes to MagicPrivate don't recompile clients
  • ABI Stability: Internal changes don't break binary compatibility
  • Header Isolation: libmagic headers stay internal

RAII Cookie Management

The libmagic handle (magic_t) is wrapped in a std::unique_ptr with a custom deleter that calls magic_close():

using CookieT = std::unique_ptr<
Detail::magic_set,
decltype([](Detail::magic_t cookie) noexcept {
Detail::magic_close(cookie);
})
>;
std::unique_ptr< Detail::magic_set, decltype([](Detail::magic_t cookie) noexcept { Detail::magic_close(cookie); }) > CookieT
RAII cookie type wrapping libmagic handle.
Definition magic.cpp:1903

Member Variables

Member Type Purpose
m_cookie CookieT RAII-managed libmagic handle (nullptr = Closed)
m_flags_mask FlagsMaskT Current configuration flags bitmask
m_is_database_loaded bool True only after successful LoadDatabaseFile()

Converter Classes

Converter Purpose
FlagsConverter Converts between FlagsContainerT, FlagsMaskT, and libmagic int
LibmagicPairConverter Extracts int or string from libmagic constant pairs

Constants

Constant Value Purpose
LIBMAGIC_ERROR -1 libmagic error return value
LIBMAGIC_FLAGS_COUNT 30 Number of supported flags
LIBMAGIC_PARAMETER_COUNT 10 Number of tunable parameters
LIBMAGIC_FLAGS array Maps Flags enum bit positions to libmagic constants
LIBMAGIC_PARAMETERS array Maps Parameters enum to libmagic constants

Error Handling

The ThrowExceptionOnFailure template provides centralized error handling:

// Throws MagicIsClosed if IsOpen() returns false
// Throws MagicOpenError with error message if result is -1
std::string GetErrorMessage() const noexcept
Retrieve the last error message from libmagic.
Definition magic.cpp:2065
static void ThrowExceptionOnFailure(ResultT result, ExceptionArgsT &&... args)
Centralized error handling template.
Definition magic.cpp:1866
bool IsOpen() const noexcept
Check if instance is open.
Definition magic.cpp:1285

Lifecycle Management

The three-state lifecycle is tracked by member variables:

State m_cookie m_is_database_loaded IsValid()
Closed nullptr false false
Opened valid ptr false false
Valid valid ptr true true
Note
MagicPrivate is move-only (copy operations deleted).
The destructor automatically releases resources via CookieT.
See also
Magic for the public interface
magic.hpp for public API documentation
Since
10.0.0

Member Typedef Documentation

◆ CookieT

Initial value:
std::unique_ptr<
Detail::magic_set,
decltype([](Detail::magic_t cookie) noexcept {
Detail::magic_close(cookie);
})
>

RAII cookie type wrapping libmagic handle.

A std::unique_ptr specialized with a custom deleter lambda that calls magic_close() on destruction. This ensures the libmagic cookie is always properly released, even on exceptions.

Custom Deleter
[](Detail::magic_t cookie) noexcept {
Detail::magic_close(cookie);
}
See also
m_cookie
Open()

◆ IdentifyFileOptionsMaskT

Bitmask type for file identification validation options.

A 3-bit bitset used to control which precondition checks are performed before file identification operations.

See also
IdentifyFileOptions
IdentifyFile()

Member Enumeration Documentation

◆ IdentifyFileOptions

Options controlling file identification precondition checks.

These options determine which validation checks are performed before attempting to identify a file. They can be combined using bitwise OR to enable multiple checks.

Validation Flow

// Example validation sequence with CheckEverything:
// 1. CheckIsValid -> Verify Magic instance is valid
// 2. CheckPathEmpty -> Verify path string is non-empty
// 3. CheckPathExists -> Verify file exists on disk
auto type = IdentifyFile(path, CheckEverything);
@ CheckEverything
Definition magic.cpp:273
FileTypeT IdentifyFile(const std::filesystem::path &path, IdentifyFileOptionsMaskT options) const
Identify a single file's type (throwing version).
Definition magic.cpp:872

Option Combinations

| Option | Checks | |-----—|-----—|| | CheckNothing | None - skip all validation | | CheckIsValid | Magic instance validity | | CheckPathEmpty | Path string non-empty | | CheckPathExists | File exists on disk | | CheckPath | CheckPathEmpty + CheckPathExists | | CheckEverything | CheckIsValid + CheckPath |

See also
IdentifyFile()
IdentifyFiles()
Enumerator
CheckNothing 0ULL 

Skip all checks

CheckIsValid 1ULL << 0 

Verify instance is valid

CheckPathEmpty 1ULL << 1 

Verify path is non-empty

CheckPathExists 1ULL << 2 

Verify path exists on disk

CheckPath CheckPathEmpty | CheckPathExists 

Check both path conditions

CheckEverything CheckIsValid | CheckPath 

Perform all validations

Member Function Documentation

◆ GetErrorMessage()

std::string Recognition::Magic::MagicPrivate::GetErrorMessage ( ) const
inlinenodiscardprivatenoexcept

Retrieve the last error message from libmagic.

Calls magic_error() to get the most recent error message from the libmagic library. Returns an empty string if no error message is available.

Returns
Error message string, or empty string if none.
libmagic Call
Detail::magic_error(m_cookie.get());
CookieT m_cookie
Definition magic.cpp:1920
Note
Used internally to populate exception messages.

Member Data Documentation

◆ LIBMAGIC_FLAG_NONE

LibmagicPairT Recognition::Magic::MagicPrivate::LIBMAGIC_FLAG_NONE
staticconstexprprivate
Initial value:
{
std::make_pair(MAGIC_NONE, "None")
}

The MAGIC_NONE flag pair for default output.

◆ LIBMAGIC_FLAGS

LibmagicFlagsT Recognition::Magic::MagicPrivate::LIBMAGIC_FLAGS
staticconstexprprivate

Mapping from Magic::Flags bit positions to libmagic constants.

◆ LIBMAGIC_PARAMETERS

LibmagicParametersT Recognition::Magic::MagicPrivate::LIBMAGIC_PARAMETERS
staticconstexprprivate
Initial value:
{
std::make_pair(MAGIC_PARAM_INDIR_MAX, "IndirMax"),
std::make_pair(MAGIC_PARAM_NAME_MAX, "NameMax"),
std::make_pair(MAGIC_PARAM_ELF_PHNUM_MAX, "ElfPhnumMax"),
std::make_pair(MAGIC_PARAM_ELF_SHNUM_MAX, "ElfShnumMax"),
std::make_pair(MAGIC_PARAM_ELF_NOTES_MAX, "ElfNotesMax"),
std::make_pair(MAGIC_PARAM_REGEX_MAX, "RegexMax"),
std::make_pair(MAGIC_PARAM_BYTES_MAX, "BytesMax"),
std::make_pair(MAGIC_PARAM_ENCODING_MAX, "EncodingMax"),
std::make_pair(MAGIC_PARAM_ELF_SHSIZE_MAX, "ElfShsizeMax"),
std::make_pair(MAGIC_PARAM_MAGWARN_MAX, "MagWarnMax")
}

Mapping from Magic::Parameters enum to libmagic constants.

Static lookup table mapping Parameters enum ordinal values to the corresponding libmagic MAGIC_PARAM_* constants and their human-readable names.

See also
Parameters
GetParameter()
SetParameter()

The documentation for this class was generated from the following file: