template<typename Definition>
struct SC::UniqueHandle< Definition >
Move only handle that has a special tag value flagging its invalid state.
Typically used to wrap Operating System specific handles.
- Template Parameters
-
| Definition | A struct declaring handle type, release function and invalid handle value. |
Example:
... definition in header
struct SC_FILE_EXPORT FileDescriptorDefinition
{
using Handle = int;
static Result releaseHandle(Handle& handle);
static constexpr Handle Invalid = -1;
};
... derive from it
struct SC_FILE_EXPORT FileDescriptor : public UniqueHandle<detail::FileDescriptorDefinition>
{
using UniqueHandle::UniqueHandle;
...declaration in .cpp file
#include <errno.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <unistd.h>
namespace
{
static SC::TimeMs fileDescriptorPosixTimespecToTimeMs(
const timespec& timespecValue)
{
static_cast<SC::int64_t>(timespecValue.tv_nsec / (1000 * 1000))};
}
{
if (S_ISREG(mode))
return SC::FileDescriptorEntryType::File;
if (S_ISDIR(mode))
return SC::FileDescriptorEntryType::Directory;
if (S_ISLNK(mode))
return SC::FileDescriptorEntryType::SymbolicLink;
return SC::FileDescriptorEntryType::Other;
}
{
fileStat = {};
fileStat.
entryType = fileDescriptorPosixEntryTypeFromMode(pathStat.st_mode);
fileStat.
accessedTime = fileDescriptorPosixTimespecToTimeMs(
#if __APPLE__
pathStat.st_atimespec
#else
pathStat.st_atim
#endif
);
fileStat.
modifiedTime = fileDescriptorPosixTimespecToTimeMs(
#if __APPLE__
pathStat.st_mtimespec
#else
pathStat.st_mtim
#endif
);
#if __APPLE__
fileStat.
creationTime = fileDescriptorPosixTimespecToTimeMs(pathStat.st_birthtimespec);
#endif
}
}
SC::Result SC::detail::FileDescriptorDefinition::releaseHandle(Handle& handle)
{
if (::close(handle) != 0)
{
return Result::Error(
"FileDescriptorDefinition::releaseHandle - close failed");
}
return Result(true);
}
...usage
#include <fcntl.h>
{
SC_TRY(filePath.assign(
"someFile.txt"));
const int flags = O_RDWR | O_CREAT | O_TRUNC;
const int access = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
SC_TRY(myDescriptor.assign(nativeFd));
SC_TRY(otherDescriptor.close());
otherDescriptor.detach();
if (otherDescriptor.isValid())
{
}
}