AFIO  v2.00 late alpha
afio_v2_xxx::async_file_handle Class Referenceabstract

An asynchronous handle to an open something. More...

#include "async_file_handle.hpp"

Inheritance diagram for afio_v2_xxx::async_file_handle:
afio_v2_xxx::file_handle afio_v2_xxx::io_handle afio_v2_xxx::fs_handle afio_v2_xxx::handle

Classes

class  awaitable
 Type sugar to tell co_await what to do. More...
 

Public Types

using dev_t = file_handle::dev_t
 
using ino_t = file_handle::ino_t
 
using path_view_type = file_handle::path_view_type
 
using path_type = io_handle::path_type
 
using extent_type = io_handle::extent_type
 
using size_type = io_handle::size_type
 
using mode = io_handle::mode
 
using creation = io_handle::creation
 
using caching = io_handle::caching
 
using flag = io_handle::flag
 
using buffer_type = io_handle::buffer_type
 
using const_buffer_type = io_handle::const_buffer_type
 
using buffers_type = io_handle::buffers_type
 
using const_buffers_type = io_handle::const_buffers_type
 
template<class T >
using io_request = io_handle::io_request< T >
 
template<class T >
using io_result = io_handle::io_result< T >
 
using io_state_ptr = std::unique_ptr< _erased_io_state_type, _io_state_deleter >
 
using unique_id_type = QUICKCPPLIB_NAMESPACE::integers128::uint128
 The unique identifier type used by this handle.
 

Public Member Functions

 async_file_handle ()=default
 Default constructor.
 
constexpr async_file_handle (io_service *service, native_handle_type h, dev_t devid, ino_t inode, caching caching=caching::none, flag flags=flag::none)
 Construct a handle from a supplied native handle.
 
 async_file_handle (async_file_handle &&o) noexcept=default
 Implicit move construction of async_file_handle permitted.
 
constexpr async_file_handle (file_handle &&o) noexcept
 Explicit conversion from file_handle permitted.
 
constexpr async_file_handle (handle &&o, io_service *service, dev_t devid, ino_t inode) noexcept
 Explicit conversion from handle and io_handle permitted.
 
async_file_handleoperator= (async_file_handle &&o) noexcept
 Move assignment of async_file_handle permitted.
 
void swap (async_file_handle &o) noexcept
 Swap with another instance.
 
AFIO_HEADERS_ONLY_VIRTUAL_SPEC io_result< const_buffers_type > barrier (io_request< const_buffers_type > reqs=io_request< const_buffers_type >(), bool wait_for_device=false, bool and_metadata=false, deadline d=deadline()) noexcept override
 
result< async_file_handleclone (io_service &service, mode mode_=mode::unchanged, caching caching_=caching::unchanged, deadline d=std::chrono::seconds(30)) const noexcept
 
AFIO_HEADERS_ONLY_VIRTUAL_SPEC result< file_handleclone (mode mode_=mode::unchanged, caching caching_=caching::unchanged, deadline d=std::chrono::seconds(30)) const noexcept override
 
template<class CompletionRoutine >
result< io_state_ptrasync_barrier (io_request< const_buffers_type > reqs, CompletionRoutine &&completion, bool wait_for_device=false, bool and_metadata=false, span< char > mem={}) noexcept
 Schedule a barrier to occur asynchronously. More...
 
template<class CompletionRoutine >
result< io_state_ptrasync_read (io_request< buffers_type > reqs, CompletionRoutine &&completion, span< char > mem={}) noexcept
 Schedule a read to occur asynchronously. More...
 
template<class CompletionRoutine >
result< io_state_ptrasync_write (io_request< const_buffers_type > reqs, CompletionRoutine &&completion, span< char > mem={}) noexcept
 Schedule a write to occur asynchronously. More...
 
AFIO_HEADERS_ONLY_VIRTUAL_SPEC io_result< buffers_type > read (io_request< buffers_type > reqs, deadline d=deadline()) noexcept override
 
AFIO_HEADERS_ONLY_VIRTUAL_SPEC io_result< const_buffers_type > write (io_request< const_buffers_type > reqs, deadline d=deadline()) noexcept override
 
result< awaitable< buffers_type > > co_read (io_request< buffers_type > reqs) noexcept
 Schedule a read to occur asynchronously. More...
 
result< awaitable< const_buffers_type > > co_write (io_request< const_buffers_type > reqs) noexcept
 Schedule a write to occur asynchronously. More...
 
void swap (file_handle &o) noexcept
 Swap with another instance.
 
void swap (handle &o) noexcept
 Swap with another instance.
 
virtual result< void > close () noexcept override
 Immediately close the native handle type managed by this handle.
 
virtual io_result< const_buffers_type > barrier (io_request< const_buffers_type > reqs=io_request< const_buffers_type >(), bool wait_for_device=false, bool and_metadata=false, deadline d=deadline()) noexcept=0
 Issue a write reordering barrier such that writes preceding the barrier will reach storage before writes after this barrier. More...
 
result< handleclone () const noexcept
 
io_serviceservice () const noexcept
 The i/o service this handle is attached to, if any.
 
virtual result< extent_type > length () const noexcept
 
virtual result< extent_type > truncate (extent_type newsize) noexcept
 
virtual result< std::vector< std::pair< extent_type, extent_type > > > extents () const noexcept
 Returns a list of currently valid extents for this open file. WARNING: racy!
 
virtual result< extent_type > zero (extent_type offset, extent_type bytes, deadline d=deadline()) noexcept
 Efficiently zero, and possibly deallocate, data on storage. More...
 
virtual size_t max_buffers () const noexcept
 The maximum number of buffers which a single read or write syscall can process at a time for this specific open handle. On POSIX, this is known as IOV_MAX. More...
 
virtual io_result< buffers_type > read (io_request< buffers_type > reqs, deadline d=deadline()) noexcept
 Read data from the open handle. More...
 
io_result< buffer_typeread (extent_type offset, char *data, size_type bytes, deadline d=deadline()) noexcept
 
virtual io_result< const_buffers_type > write (io_request< const_buffers_type > reqs, deadline d=deadline()) noexcept
 Write data to the open handle. More...
 
io_result< const_buffer_typewrite (extent_type offset, const char *data, size_type bytes, deadline d=deadline()) noexcept
 
virtual result< extent_guardlock (extent_type offset, extent_type bytes, bool exclusive=true, deadline d=deadline()) noexcept
 Tries to lock the range of bytes specified for shared or exclusive access. Be aware this passes through the same semantics as the underlying OS call, including any POSIX insanity present on your platform: More...
 
result< extent_guardlock (io_request< buffers_type > reqs, deadline d=deadline()) noexcept
 
result< extent_guardlock (io_request< const_buffers_type > reqs, deadline d=deadline()) noexcept
 
result< extent_guardtry_lock (extent_type offset, extent_type bytes, bool exclusive=true) noexcept
 
virtual void unlock (extent_type offset, extent_type bytes) noexcept
 Unlocks a byte range previously locked. More...
 
virtual result< path_type > current_path () const noexcept
 
virtual native_handle_type release () noexcept
 Release the native handle type managed by this handle.
 
bool is_valid () const noexcept
 True if the handle is valid (and usually open)
 
bool is_readable () const noexcept
 True if the handle is readable.
 
bool is_writable () const noexcept
 True if the handle is writable.
 
bool is_append_only () const noexcept
 True if the handle is append only.
 
virtual result< void > set_append_only (bool enable) noexcept
 
bool is_overlapped () const noexcept
 True if overlapped.
 
bool is_seekable () const noexcept
 True if seekable.
 
bool requires_aligned_io () const noexcept
 True if requires aligned i/o.
 
bool is_regular () const noexcept
 True if a regular file or device.
 
bool is_directory () const noexcept
 True if a directory.
 
bool is_symlink () const noexcept
 True if a symlink.
 
bool is_multiplexer () const noexcept
 True if a multiplexer like BSD kqueues, Linux epoll or Windows IOCP.
 
bool is_process () const noexcept
 True if a process.
 
bool is_section () const noexcept
 True if a memory section.
 
caching kernel_caching () const noexcept
 Kernel cache strategy used by this handle.
 
bool are_reads_from_cache () const noexcept
 True if the handle uses the kernel page cache for reads.
 
bool are_writes_durable () const noexcept
 True if writes are safely on storage on completion.
 
bool are_safety_fsyncs_issued () const noexcept
 True if issuing safety fsyncs is on.
 
flag flags () const noexcept
 The flags this handle was opened with.
 
native_handle_type native_handle () const noexcept
 The native handle used by this handle.
 
dev_t st_dev () const noexcept
 Unless flag::disable_safety_unlinks is set, the device id of the file when opened.
 
ino_t st_ino () const noexcept
 Unless flag::disable_safety_unlinks is set, the inode of the file when opened. When combined with st_dev(), forms a unique identifer on this system.
 
unique_id_type unique_id () const noexcept
 A unique identifier for this handle across the entire system. Can be used in hash tables etc.
 
virtual result< path_handleparent_path_handle (deadline d=std::chrono::seconds(30)) const noexcept
 
virtual result< void > relink (const path_handle &base, path_view_type path, bool atomic_replace=true, deadline d=std::chrono::seconds(30)) noexcept
 
virtual result< void > unlink (deadline d=std::chrono::seconds(30)) noexcept
 

Static Public Member Functions

static AFIO_HEADERS_ONLY_MEMFUNC_SPEC result< async_file_handleasync_file (io_service &service, const path_handle &base, path_view_type _path, mode _mode=mode::read, creation _creation=creation::open_existing, caching _caching=caching::only_metadata, flag flags=flag::none) noexcept
 
static result< async_file_handleasync_random_file (io_service &service, const path_handle &dirpath, mode _mode=mode::write, caching _caching=caching::only_metadata, flag flags=flag::none) noexcept
 
static result< async_file_handleasync_temp_file (io_service &service, path_view_type name=path_view_type(), mode _mode=mode::write, creation _creation=creation::if_needed, caching _caching=caching::only_metadata, flag flags=flag::unlink_on_close) noexcept
 
static AFIO_HEADERS_ONLY_MEMFUNC_SPEC result< async_file_handleasync_temp_inode (io_service &service, const path_handle &dir=path_discovery::storage_backed_temporary_files_directory(), mode _mode=mode::write, flag flags=flag::none) noexcept
 
static result< file_handlefile (const path_handle &base, path_view_type path, mode _mode=mode::read, creation _creation=creation::open_existing, caching _caching=caching::all, flag flags=flag::none) noexcept
 
static result< file_handlerandom_file (const path_handle &dirpath, mode _mode=mode::write, caching _caching=caching::temporary, flag flags=flag::none) noexcept
 
static result< file_handletemp_file (path_view_type name=path_view_type(), mode _mode=mode::write, creation _creation=creation::if_needed, caching _caching=caching::temporary, flag flags=flag::unlink_on_close) noexcept
 
static result< file_handletemp_inode (const path_handle &dirh=path_discovery::storage_backed_temporary_files_directory(), mode _mode=mode::write, flag flags=flag::none) noexcept
 

Protected Member Functions

result< void > _fetch_inode () noexcept
 Fill in _devid and _inode from the handle via fstat()
 

Protected Attributes

io_service_service {nullptr}
 
caching _caching {caching::none}
 
flag _flags {flag::none}
 
native_handle_type _v
 
dev_t _devid {0}
 
ino_t _inode {0}
 

Friends

class io_service
 

Detailed Description

An asynchronous handle to an open something.

Note
Unlike the others, async_file_handle defaults to only_metadata caching as that is the only use case where using async i/o makes sense given the other options below.
Cost of openingCost of i/oConcurrency and AtomicityOther remarks
file_handleLeastSyscallPOSIX guarantees (usually)Least gotcha
async_file_handleMoreMost (syscall + malloc/free + reactor)POSIX guarantees (usually)Makes no sense to use with cached i/o as it's a very expensive way to call memcpy()
mapped_file_handleMostLeastNoneCannot be used with uncached i/o
Warning
i/o initiated by this class MUST be on the same kernel thread as which created the owning io_service which MUST also be the same kernel thread as which runs the i/o service's run() function.
namespace afio = AFIO_V2_NAMESPACE;
// Create an i/o service for this thread
afio::io_service service;
// Create an async file i/o handle attached to the i/o service for this thread
afio::async_file_handle h = afio::async_file_handle::async_file(service, {}, "temp", afio::file_handle::mode::write, afio::file_handle::creation::if_needed, afio::file_handle::caching::only_metadata, afio::file_handle::flag::unlink_on_close).value();
// Truncate to 1Mb
h.truncate(1024 * 4096);
// Launch 8 coroutines, each writing 4Kb of chars 0-8 to every 32Kb block
auto coroutine = [&h](size_t no) -> std::future<void> {
std::vector<char, afio::utils::page_allocator<char>> buffer(4096);
memset(buffer.data(), (int) ('0' + no), 4096);
afio::async_file_handle::const_buffer_type bt{buffer.data(), buffer.size()};
for(size_t n = 0; n < 128; n++)
{
// This will initiate the i/o, and suspend the coroutine until completion.
// The caller will thus resume execution with a valid unsignaled future.
auto written = co_await h.co_write({bt, n * 32768 + no * 4096}).value();
written.value();
}
};
std::vector<std::future<void>> coroutines;
for(size_t n = 0; n < 8; n++)
{
// Construct each coroutine, initiating the i/o, then suspending.
coroutines.push_back(coroutine(n));
}
// Pump the i/o, multiplexing the coroutines, until no more work remains.
while(service.run().value())
;
// Make sure nothing went wrong by fetching the futures.
for(auto &i : coroutines)
{
i.get();
}

Member Typedef Documentation

◆ io_state_ptr

using afio_v2_xxx::async_file_handle::io_state_ptr = std::unique_ptr<_erased_io_state_type, _io_state_deleter>

Smart pointer to state of an i/o in progress. Destroying this before an i/o has completed is blocking because the i/o must be cancelled before the destructor can safely exit.

Member Function Documentation

◆ async_barrier()

template<class CompletionRoutine >
result<io_state_ptr> afio_v2_xxx::async_file_handle::async_barrier ( io_request< const_buffers_type >  reqs,
CompletionRoutine &&  completion,
bool  wait_for_device = false,
bool  and_metadata = false,
span< char >  mem = {} 
)
inlinenoexcept

Schedule a barrier to occur asynchronously.

Note
All the caveats and exclusions which apply to barrier() also apply here. Note that Microsoft Windows does not support asynchronously executed barriers, and this call will fail on that operating system.
Returns
Either an io_state_ptr to the i/o in progress, or an error code.
Parameters
reqsA scatter-gather and offset request for what range to barrier. May be ignored on some platforms which always write barrier the entire file. Supplying a default initialised reqs write barriers the entire file.
completionA callable to call upon i/o completion. Spec is void(async_file_handle *, io_result<const_buffers_type> &). Note that buffers returned may not be buffers input, see documentation for barrier().
wait_for_deviceTrue if you want the call to wait until data reaches storage and that storage has acknowledged the data is physically written. Slow.
and_metadataTrue if you want the call to sync the metadata for retrieving the writes before the barrier after a sudden power loss event. Slow.
memOptional span of memory to use to avoid using calloc(). Note span MUST be all bits zero on entry.
Errors returnable
As for barrier(), plus ENOMEM.
Memory Allocations
If mem is not set, one calloc, one free. The allocation is unavoidable due to the need to store a type erased completion handler of unknown type and state per buffers input.
363  {}) noexcept
364  {
365  AFIO_LOG_FUNCTION_CALL(this);
366  struct completion_handler : _erased_completion_handler
367  {
368  CompletionRoutine completion;
369  explicit completion_handler(CompletionRoutine c)
370  : completion(std::move(c))
371  {
372  }
373  size_t bytes() const noexcept final { return sizeof(*this); }
374  void move(_erased_completion_handler *_dest) final
375  {
376  auto *dest = (void *) _dest;
377  new(dest) completion_handler(std::move(*this));
378  }
379  void operator()(_erased_io_state_type *state) final { completion(state->parent, state->result.write); }
380  void *address() noexcept final { return &completion; }
381  } ch{std::forward<CompletionRoutine>(completion)};
382  operation_t operation = operation_t::fsync_sync;
383  if(!wait_for_device && and_metadata)
384  {
385  operation = operation_t::fsync_async;
386  }
387  else if(wait_for_device && !and_metadata)
388  {
389  operation = operation_t::dsync_sync;
390  }
391  else if(!wait_for_device && !and_metadata)
392  {
393  operation = operation_t::dsync_async;
394  }
395  return _begin_io(mem, operation, reinterpret_cast<io_request<const_buffers_type> &>(reqs), std::move(ch));
396  }
STL namespace.

◆ async_file()

static AFIO_HEADERS_ONLY_MEMFUNC_SPEC result<async_file_handle> afio_v2_xxx::async_file_handle::async_file ( io_service service,
const path_handle base,
path_view_type  _path,
mode  _mode = mode::read,
creation  _creation = creation::open_existing,
caching  _caching = caching::only_metadata,
flag  flags = flag::none 
)
inlinestaticnoexcept

Create an async file handle opening access to a file on path using the given io_service.

Parameters
serviceThe io_service to use.
baseHandle to a base location on the filing system. Pass {} to indicate that path will be absolute.
_pathThe path relative to base to open.
_modeHow to open the file.
_creationHow to create the file.
_cachingHow to ask the kernel to cache the file.
flagsAny additional custom behaviours.
Errors returnable
Any of the values POSIX open() or CreateFile() can return.
134  {
135  // Open it overlapped, otherwise no difference.
136  OUTCOME_TRY(v, file_handle::file(std::move(base), _path, _mode, _creation, _caching, flags | flag::overlapped));
137  async_file_handle ret(std::move(v));
138  ret._service = &service;
139  return std::move(ret);
140  }
static result< file_handle > file(const path_handle &base, path_view_type path, mode _mode=mode::read, creation _creation=creation::open_existing, caching _caching=caching::all, flag flags=flag::none) noexcept
flag flags() const noexcept
The flags this handle was opened with.
Definition: handle.hpp:314
io_service * service() const noexcept
The i/o service this handle is attached to, if any.
Definition: file_handle.hpp:229
async_file_handle()=default
Default constructor.

◆ async_random_file()

static result<async_file_handle> afio_v2_xxx::async_file_handle::async_random_file ( io_service service,
const path_handle dirpath,
mode  _mode = mode::write,
caching  _caching = caching::only_metadata,
flag  flags = flag::none 
)
inlinestaticnoexcept

Create an async file handle creating a randomly named file on a path. The file is opened exclusively with creation::only_if_not_exist so it will never collide with nor overwrite any existing file.

Errors returnable
Any of the values POSIX open() or CreateFile() can return.
150  {
151  try
152  {
153  for(;;)
154  {
155  auto randomname = utils::random_string(32);
156  randomname.append(".random");
157  result<async_file_handle> ret = async_file(service, dirpath, randomname, _mode, creation::only_if_not_exist, _caching, flags);
158  if(ret || (!ret && ret.error() != std::errc::file_exists))
159  {
160  return ret;
161  }
162  }
163  }
164  catch(...)
165  {
166  return error_from_exception();
167  }
168  }
std::string random_string(size_t randomlen)
Returns a cryptographically random string capable of being used as a filename. Essentially random_fil...
Definition: utils.hpp:134
flag flags() const noexcept
The flags this handle was opened with.
Definition: handle.hpp:314
io_service * service() const noexcept
The i/o service this handle is attached to, if any.
Definition: file_handle.hpp:229
static AFIO_HEADERS_ONLY_MEMFUNC_SPEC result< async_file_handle > async_file(io_service &service, const path_handle &base, path_view_type _path, mode _mode=mode::read, creation _creation=creation::open_existing, caching _caching=caching::only_metadata, flag flags=flag::none) noexcept
Definition: async_file_handle.hpp:133

◆ async_read()

template<class CompletionRoutine >
result<io_state_ptr> afio_v2_xxx::async_file_handle::async_read ( io_request< buffers_type >  reqs,
CompletionRoutine &&  completion,
span< char >  mem = {} 
)
inlinenoexcept

Schedule a read to occur asynchronously.

Returns
Either an io_state_ptr to the i/o in progress, or an error code.
Parameters
reqsA scatter-gather and offset request.
completionA callable to call upon i/o completion. Spec is void(async_file_handle *, io_result<buffers_type> &). Note that buffers returned may not be buffers input, see documentation for read().
memOptional span of memory to use to avoid using calloc(). Note span MUST be all bits zero on entry.
Errors returnable
As for read(), plus ENOMEM.
Memory Allocations
If mem is not set, one calloc, one free. The allocation is unavoidable due to the need to store a type erased completion handler of unknown type and state per buffers input.
412  {}) noexcept
413  {
414  AFIO_LOG_FUNCTION_CALL(this);
415  struct completion_handler : _erased_completion_handler
416  {
417  CompletionRoutine completion;
418  explicit completion_handler(CompletionRoutine c)
419  : completion(std::move(c))
420  {
421  }
422  size_t bytes() const noexcept final { return sizeof(*this); }
423  void move(_erased_completion_handler *_dest) final
424  {
425  auto *dest = (void *) _dest;
426  new(dest) completion_handler(std::move(*this));
427  }
428  void operator()(_erased_io_state_type *state) final { completion(state->parent, state->result.read); }
429  void *address() noexcept final { return &completion; }
430  } ch{std::forward<CompletionRoutine>(completion)};
431  return _begin_io(mem, operation_t::read, io_request<const_buffers_type>({reinterpret_cast<const_buffer_type *>(reqs.buffers.data()), reqs.buffers.size()}, reqs.offset), std::move(ch));
432  }
STL namespace.

◆ async_temp_file()

static result<async_file_handle> afio_v2_xxx::async_file_handle::async_temp_file ( io_service service,
path_view_type  name = path_view_type(),
mode  _mode = mode::write,
creation  _creation = creation::if_needed,
caching  _caching = caching::only_metadata,
flag  flags = flag::unlink_on_close 
)
inlinestaticnoexcept

Create an async file handle creating the named file on some path which the OS declares to be suitable for temporary files. Most OSs are very lazy about flushing changes made to these temporary files. Note the default flags are to have the newly created file deleted on first handle close. Note also that an empty name is equivalent to calling async_random_file(path_discovery::storage_backed_temporary_files_directory()) and the creation parameter is ignored.

Note
If the temporary file you are creating is not going to have its path sent to another process for usage, this is the WRONG function to use. Use temp_inode() instead, it is far more secure.
Errors returnable
Any of the values POSIX open() or CreateFile() can return.
186  {
188  return name.empty() ? async_random_file(service, tempdirh, _mode, _caching, flags) : async_file(service, tempdirh, name, _mode, _creation, _caching, flags);
189  }
static result< async_file_handle > async_random_file(io_service &service, const path_handle &dirpath, mode _mode=mode::write, caching _caching=caching::only_metadata, flag flags=flag::none) noexcept
Definition: async_file_handle.hpp:149
const path_handle & storage_backed_temporary_files_directory() noexcept
Returns a reference to an open handle to a verified temporary directory where files created are store...
flag flags() const noexcept
The flags this handle was opened with.
Definition: handle.hpp:314
io_service * service() const noexcept
The i/o service this handle is attached to, if any.
Definition: file_handle.hpp:229
static AFIO_HEADERS_ONLY_MEMFUNC_SPEC result< async_file_handle > async_file(io_service &service, const path_handle &base, path_view_type _path, mode _mode=mode::read, creation _creation=creation::open_existing, caching _caching=caching::only_metadata, flag flags=flag::none) noexcept
Definition: async_file_handle.hpp:133

◆ async_temp_inode()

static AFIO_HEADERS_ONLY_MEMFUNC_SPEC result<async_file_handle> afio_v2_xxx::async_file_handle::async_temp_inode ( io_service service,
const path_handle dir = path_discovery::storage_backed_temporary_files_directory(),
mode  _mode = mode::write,
flag  flags = flag::none 
)
inlinestaticnoexcept

Securely create an async file handle creating a temporary anonymous inode in the filesystem referred to by dirpath. The inode created has no name nor accessible path on the filing system and ceases to exist as soon as the last handle is closed, making it ideal for use as a temporary file where other processes do not need to have access to its contents via some path on the filing system (a classic use case is for backing shared memory maps).

Errors returnable
Any of the values POSIX open() or CreateFile() can return.
202  {
203  // Open it overlapped, otherwise no difference.
204  OUTCOME_TRY(v, file_handle::temp_inode(dir, _mode, flags | flag::overlapped));
205  async_file_handle ret(std::move(v));
206  ret._service = &service;
207  return std::move(ret);
208  }
static result< file_handle > temp_inode(const path_handle &dirh=path_discovery::storage_backed_temporary_files_directory(), mode _mode=mode::write, flag flags=flag::none) noexcept
flag flags() const noexcept
The flags this handle was opened with.
Definition: handle.hpp:314
io_service * service() const noexcept
The i/o service this handle is attached to, if any.
Definition: file_handle.hpp:229
async_file_handle()=default
Default constructor.

◆ async_write()

template<class CompletionRoutine >
result<io_state_ptr> afio_v2_xxx::async_file_handle::async_write ( io_request< const_buffers_type >  reqs,
CompletionRoutine &&  completion,
span< char >  mem = {} 
)
inlinenoexcept

Schedule a write to occur asynchronously.

Returns
Either an io_state_ptr to the i/o in progress, or an error code.
Parameters
reqsA scatter-gather and offset request.
completionA callable to call upon i/o completion. Spec is void(async_file_handle *, io_result<const_buffers_type> &). Note that buffers returned may not be buffers input, see documentation for write().
memOptional span of memory to use to avoid using calloc(). Note span MUST be all bits zero on entry.
Errors returnable
As for write(), plus ENOMEM.
Memory Allocations
If mem in not set, one calloc, one free. The allocation is unavoidable due to the need to store a type erased completion handler of unknown type and state per buffers input.
448  {}) noexcept
449  {
450  AFIO_LOG_FUNCTION_CALL(this);
451  struct completion_handler : _erased_completion_handler
452  {
453  CompletionRoutine completion;
454  explicit completion_handler(CompletionRoutine c)
455  : completion(std::move(c))
456  {
457  }
458  size_t bytes() const noexcept final { return sizeof(*this); }
459  void move(_erased_completion_handler *_dest) final
460  {
461  auto *dest = (void *) _dest;
462  new(dest) completion_handler(std::move(*this));
463  }
464  void operator()(_erased_io_state_type *state) final { completion(state->parent, state->result.write); }
465  void *address() noexcept final { return &completion; }
466  } ch{std::forward<CompletionRoutine>(completion)};
467  return _begin_io(mem, operation_t::write, reqs, std::move(ch));
468  }
STL namespace.

◆ barrier()

virtual io_result<const_buffers_type> afio_v2_xxx::io_handle::barrier ( io_request< const_buffers_type reqs = io_requestconst_buffers_type >(),
bool  wait_for_device = false,
bool  and_metadata = false,
deadline  d = deadline() 
)
pure virtualnoexceptinherited

Issue a write reordering barrier such that writes preceding the barrier will reach storage before writes after this barrier.

Warning
Assume that this call is a no-op. It is not reliably implemented in many common use cases, for example if your code is running inside a LXC container, or if the user has mounted the filing system with non-default options. Instead open the handle with caching::reads which means that all writes form a strict sequential order not completing until acknowledged by the storage device. Filing system can and do use different algorithms to give much better performance with caching::reads, some (e.g. ZFS) spectacularly better.
Let me repeat again: consider this call to be a hint to poke the kernel with a stick to go start to do some work sooner rather than later. It may be ignored entirely.
For portability, you can only assume that barriers write order for a single handle instance. You cannot assume that barriers write order across multiple handles to the same inode, or across processes.
Returns
The buffers barriered, which may not be the buffers input. The size of each scatter-gather buffer is updated with the number of bytes of that buffer barriered.
Parameters
reqsA scatter-gather and offset request for what range to barrier. May be ignored on some platforms which always write barrier the entire file. Supplying a default initialised reqs write barriers the entire file.
wait_for_deviceTrue if you want the call to wait until data reaches storage and that storage has acknowledged the data is physically written. Slow.
and_metadataTrue if you want the call to sync the metadata for retrieving the writes before the barrier after a sudden power loss event. Slow.
dAn optional deadline by which the i/o must complete, else it is cancelled. Note function may return significantly after this deadline if the i/o takes long to cancel.
Errors returnable
Any of the values POSIX fdatasync() or Windows NtFlushBuffersFileEx() can return.
Memory Allocations
None.

◆ clone() [1/3]

result<async_file_handle> afio_v2_xxx::async_file_handle::clone ( io_service service,
mode  mode_ = mode::unchanged,
caching  caching_ = caching::unchanged,
deadline  d = std::chrono::seconds(30) 
) const
inlinenoexcept

Clone this handle to a different io_service (copy constructor is disabled to avoid accidental copying)

Errors returnable
Any of the values POSIX dup() or DuplicateHandle() can return.
217  {
218  OUTCOME_TRY(v, file_handle::clone(mode_, caching_, d));
219  async_file_handle ret(std::move(v));
220  ret._service = &service;
221  return std::move(ret);
222  }
result< handle > clone() const noexcept
io_service * service() const noexcept
The i/o service this handle is attached to, if any.
Definition: file_handle.hpp:229
async_file_handle()=default
Default constructor.

◆ clone() [2/3]

AFIO_HEADERS_ONLY_VIRTUAL_SPEC result<file_handle> afio_v2_xxx::async_file_handle::clone ( mode  mode_ = mode::unchanged,
caching  caching_ = caching::unchanged,
deadline  d = std::chrono::seconds(30) 
) const
inlineoverridevirtualnoexcept

Clone this handle (copy constructor is disabled to avoid accidental copying), optionally race free reopening the handle with different access or caching.

Microsoft Windows provides a syscall for cloning an existing handle but with new access. On POSIX, if not changing the mode, we change caching via fcntl(), if changing the mode we must loop calling current_path(), trying to open the path returned and making sure it is the same inode.

Errors returnable
Any of the values POSIX dup() or DuplicateHandle() can return.
Memory Allocations
On POSIX if changing the mode, we must loop calling current_path() and trying to open the path returned. Thus many allocations may occur.

Reimplemented from afio_v2_xxx::file_handle.

224  {
225  OUTCOME_TRY(v, file_handle::clone(mode_, caching_, d));
226  async_file_handle ret(std::move(v));
227  ret._service = _service;
228  return static_cast<file_handle &&>(ret);
229  }
result< handle > clone() const noexcept
async_file_handle()=default
Default constructor.
constexpr file_handle()
Default constructor.
Definition: file_handle.hpp:82

◆ clone() [3/3]

result<handle> afio_v2_xxx::handle::clone ( ) const
inlinenoexceptinherited

Clone this handle (copy constructor is disabled to avoid accidental copying)

Errors returnable
Any of the values POSIX dup() or DuplicateHandle() can return.

◆ co_read()

result<awaitable<buffers_type> > afio_v2_xxx::async_file_handle::co_read ( io_request< buffers_type >  reqs)
inlinenoexcept

Schedule a read to occur asynchronously.

Returns
An awaitable, which when co_awaited upon, suspends execution of the coroutine until the operation has completed, resuming with the buffers read, which may not be the buffers input. The size of each scatter-gather buffer is updated with the number of bytes of that buffer transferred, and the pointer to the data may be completely different to what was submitted (e.g. it may point into a memory map).
Parameters
reqsA scatter-gather and offset request.
Errors returnable
As for read(), plus ENOMEM.
Memory Allocations
One calloc, one free.
532  {
533  OUTCOME_TRY(r, async_read(reqs, awaitable_state<buffers_type>()));
534  return awaitable<buffers_type>(std::move(r));
535  }
result< io_state_ptr > async_read(io_request< buffers_type > reqs, CompletionRoutine &&completion, span< char > mem={}) noexcept
Schedule a read to occur asynchronously.
Definition: async_file_handle.hpp:412

◆ co_write()

result<awaitable<const_buffers_type> > afio_v2_xxx::async_file_handle::co_write ( io_request< const_buffers_type >  reqs)
inlinenoexcept

Schedule a write to occur asynchronously.

Returns
An awaitable, which when co_awaited upon, suspends execution of the coroutine until the operation has completed, resuming with the buffers written, which may not be the buffers input. The size of each scatter-gather buffer is updated with the number of bytes of that buffer transferred.
Parameters
reqsA scatter-gather and offset request.
Errors returnable
As for write(), plus ENOMEM.
Memory Allocations
One calloc, one free.
549  {
550  OUTCOME_TRY(r, async_write(reqs, awaitable_state<const_buffers_type>()));
551  return awaitable<const_buffers_type>(std::move(r));
552  }
result< io_state_ptr > async_write(io_request< const_buffers_type > reqs, CompletionRoutine &&completion, span< char > mem={}) noexcept
Schedule a write to occur asynchronously.
Definition: async_file_handle.hpp:448

◆ current_path()

virtual result<path_type> afio_v2_xxx::handle::current_path ( ) const
inlinevirtualnoexceptinherited

Returns the current path of the open handle as said by the operating system. Note that you are NOT guaranteed that any path refreshed bears any resemblance to the original, some operating systems will return some different path which still reaches the same inode via some other route e.g. hardlinks, dereferenced symbolic links, etc. Windows and Linux correctly track changes to the specific path the handle was opened with, not getting confused by other hard links. MacOS nearly gets it right, but under some circumstances e.g. renaming may switch to a different hard link's path which is almost certainly a bug.

If AFIO was not able to determine the current path for this open handle e.g. the inode has been unlinked, it returns an empty path. Be aware that FreeBSD can return an empty (deleted) path for file inodes no longer cached by the kernel path cache, AFIO cannot detect the difference. FreeBSD will also return any path leading to the inode if it is hard linked. FreeBSD does implement path retrieval for directory inodes correctly however, and see algorithm::stablized_path<T> for a handle adapter which makes use of that.

On Linux if /proc is not mounted, this call fails with an error. All APIs in AFIO which require the use of current_path() can be told to not use it e.g. flag::disable_safety_unlinks. It is up to you to detect if current_path() is not working, and to change how you call AFIO appropriately.

Warning
This call is expensive, it always asks the kernel for the current path, and no checking is done to ensure what the kernel returns is accurate or even sensible. Be aware that despite these precautions, paths are unstable and can change randomly at any moment. Most code written to use absolute file systems paths is racy, so don't do it, use path_handle to fix a base location on the file system and work from that anchor instead!
Memory Allocations
At least one malloc for the path_type, likely several more.
See also
algorithm::cached_parent_handle_adapter<T> which overrides this with an implementation based on retrieving the current path of a cached handle to the parent directory. On platforms with instability or failure to retrieve the correct current path for regular files, the cached parent handle adapter works around the problem by taking advantage of directory inodes not having the same instability problems on any platform.

◆ file()

static result<file_handle> afio_v2_xxx::file_handle::file ( const path_handle base,
path_view_type  path,
mode  _mode = mode::read,
creation  _creation = creation::open_existing,
caching  _caching = caching::all,
flag  flags = flag::none 
)
inlinestaticnoexceptinherited

Create a file handle opening access to a file on path

Parameters
baseHandle to a base location on the filing system. Pass {} to indicate that path will be absolute.
_pathThe path relative to base to open.
_modeHow to open the file.
_creationHow to create the file.
_cachingHow to ask the kernel to cache the file.
flagsAny additional custom behaviours.
Errors returnable
Any of the values POSIX open() or CreateFile() can return.

◆ length()

virtual result<extent_type> afio_v2_xxx::file_handle::length ( ) const
inlinevirtualnoexceptinherited

Return the current maximum permitted extent of the file.

Errors returnable
Any of the values POSIX fstat() or GetFileInformationByHandleEx() can return.

Reimplemented in afio_v2_xxx::mapped_file_handle.

◆ lock() [1/3]

virtual result<extent_guard> afio_v2_xxx::io_handle::lock ( extent_type  offset,
extent_type  bytes,
bool  exclusive = true,
deadline  d = deadline() 
)
inlinevirtualnoexceptinherited

Tries to lock the range of bytes specified for shared or exclusive access. Be aware this passes through the same semantics as the underlying OS call, including any POSIX insanity present on your platform:

  • Any fd closed on an inode must release all byte range locks on that inode for all other fds. If your OS isn't new enough to support the non-insane lock API, flag::byte_lock_insanity will be set in flags() after the first call to this function.
  • Threads replace each other's locks, indeed locks replace each other's locks.

You almost cetainly should use your choice of an algorithm::shared_fs_mutex::* instead of this as those are more portable and performant.

Warning
This is a low-level API which you should not use directly in portable code. Another issue is that atomic lock upgrade/downgrade, if your platform implements that (you should assume it does not in portable code), means that on POSIX you need to release the old extent_guard after creating a new one over the same byte range, otherwise the old extent_guard's destructor will simply unlock the range entirely. On Windows however upgrade/downgrade locks overlay, so on that platform you must not release the old extent_guard. Look into algorithm::shared_fs_mutex::safe_byte_ranges for a portable solution.
Returns
An extent guard, the destruction of which will call unlock().
Parameters
offsetThe offset to lock. Note that on POSIX the top bit is always cleared before use as POSIX uses signed transport for offsets. If you want an advisory rather than mandatory lock on Windows, one technique is to force top bit set so the region you lock is not the one you will i/o - obviously this reduces maximum file size to (2^63)-1.
bytesThe number of bytes to lock. Zero means lock the entire file using any more efficient alternative algorithm where available on your platform (specifically, on BSD and OS X use flock() for non-insane semantics).
exclusiveWhether the lock is to be exclusive.
dAn optional deadline by which the lock must complete, else it is cancelled.
Errors returnable
Any of the values POSIX fcntl() can return, errc::timed_out, errc::not_supported may be returned if deadline i/o is not possible with this particular handle configuration (e.g. non-overlapped HANDLE on Windows).
Memory Allocations
The default synchronous implementation in file_handle performs no memory allocation. The asynchronous implementation in async_file_handle performs one calloc and one free.

◆ lock() [2/3]

result<extent_guard> afio_v2_xxx::io_handle::lock ( io_request< buffers_type reqs,
deadline  d = deadline() 
)
inlinenoexceptinherited

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

408  {
409  size_t bytes = 0;
410  for(auto &i : reqs.buffers)
411  {
412  if(bytes + i.len < bytes)
413  {
414  return std::errc::value_too_large;
415  }
416  bytes += i.len;
417  }
418  return lock(reqs.offset, bytes, false, d);
419  }
virtual result< extent_guard > lock(extent_type offset, extent_type bytes, bool exclusive=true, deadline d=deadline()) noexcept
Tries to lock the range of bytes specified for shared or exclusive access. Be aware this passes throu...

◆ lock() [3/3]

result<extent_guard> afio_v2_xxx::io_handle::lock ( io_request< const_buffers_type reqs,
deadline  d = deadline() 
)
inlinenoexceptinherited

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

422  {
423  size_t bytes = 0;
424  for(auto &i : reqs.buffers)
425  {
426  if(bytes + i.len < bytes)
427  {
428  return std::errc::value_too_large;
429  }
430  bytes += i.len;
431  }
432  return lock(reqs.offset, bytes, true, d);
433  }
virtual result< extent_guard > lock(extent_type offset, extent_type bytes, bool exclusive=true, deadline d=deadline()) noexcept
Tries to lock the range of bytes specified for shared or exclusive access. Be aware this passes throu...

◆ max_buffers()

virtual size_t afio_v2_xxx::io_handle::max_buffers ( ) const
inlinevirtualnoexceptinherited

The maximum number of buffers which a single read or write syscall can process at a time for this specific open handle. On POSIX, this is known as IOV_MAX.

Note that the actual number of buffers accepted for a read or a write may be significantly lower than this system-defined limit, depending on available resources. The read() or write() call will return the buffers accepted.

Note also that some OSs will error out if you supply more than this limit to read() or write(), but other OSs do not. Some OSs guarantee that each i/o syscall has effects atomically visible or not to other i/o, other OSs do not.

Microsoft Windows does not implement scatter-gather file i/o syscalls except for unbuffered i/o. Thus this function will always return 1 in that situation.

◆ parent_path_handle()

virtual result<path_handle> afio_v2_xxx::fs_handle::parent_path_handle ( deadline  d = std::chrono::seconds(30)) const
inlinevirtualnoexceptinherited

Obtain a handle to the path currently containing this handle's file entry.

Warning
This call is racy and can result in the wrong path handle being returned. Note that unless flag::disable_safety_unlinks is set, this implementation opens a path_handle to the source containing directory, then checks if the file entry within has the same inode as the open file handle. It will retry this matching until success until the deadline given.
Memory Allocations
Calls current_path() and thus is both expensive and calls malloc many times.
See also
algorithm::cached_parent_handle_adapter<T> which overrides this with a zero cost implementation, thus making unlinking and relinking very considerably quicker.

◆ random_file()

static result<file_handle> afio_v2_xxx::file_handle::random_file ( const path_handle dirpath,
mode  _mode = mode::write,
caching  _caching = caching::temporary,
flag  flags = flag::none 
)
inlinestaticnoexceptinherited

Create a file handle creating a randomly named file on a path. The file is opened exclusively with creation::only_if_not_exist so it will never collide with nor overwrite any existing file. Note also that caching defaults to temporary which hints to the OS to only flush changes to physical storage as lately as possible.

Errors returnable
Any of the values POSIX open() or CreateFile() can return.
134  {
135  try
136  {
137  for(;;)
138  {
139  auto randomname = utils::random_string(32);
140  randomname.append(".random");
141  result<file_handle> ret = file(dirpath, randomname, _mode, creation::only_if_not_exist, _caching, flags);
142  if(ret || (!ret && ret.error() != std::errc::file_exists))
143  {
144  return ret;
145  }
146  }
147  }
148  catch(...)
149  {
150  return error_from_exception();
151  }
152  }
static result< file_handle > file(const path_handle &base, path_view_type path, mode _mode=mode::read, creation _creation=creation::open_existing, caching _caching=caching::all, flag flags=flag::none) noexcept
std::string random_string(size_t randomlen)
Returns a cryptographically random string capable of being used as a filename. Essentially random_fil...
Definition: utils.hpp:134
flag flags() const noexcept
The flags this handle was opened with.
Definition: handle.hpp:314

◆ read() [1/2]

virtual io_result<buffers_type> afio_v2_xxx::io_handle::read ( io_request< buffers_type reqs,
deadline  d = deadline() 
)
inlinevirtualnoexceptinherited

Read data from the open handle.

Warning
Depending on the implementation backend, very different buffers may be returned than you supplied. You should always use the buffers returned and assume that they point to different memory and that each buffer's size will have changed.
Returns
The buffers read, which may not be the buffers input. The size of each scatter-gather buffer is updated with the number of bytes of that buffer transferred, and the pointer to the data may be completely different to what was submitted (e.g. it may point into a memory map).
Parameters
reqsA scatter-gather and offset request.
dAn optional deadline by which the i/o must complete, else it is cancelled. Note function may return significantly after this deadline if the i/o takes long to cancel.
Errors returnable
Any of the values POSIX read() can return, errc::timed_out, errc::operation_canceled. errc::not_supported may be returned if deadline i/o is not possible with this particular handle configuration (e.g. reading from regular files on POSIX or reading from a non-overlapped HANDLE on Windows).
Memory Allocations
The default synchronous implementation in file_handle performs no memory allocation. The asynchronous implementation in async_file_handle performs one calloc and one free.

◆ read() [2/2]

io_result<buffer_type> afio_v2_xxx::io_handle::read ( extent_type  offset,
char *  data,
size_type  bytes,
deadline  d = deadline() 
)
inlinenoexceptinherited

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

221  {
222  buffer_type _reqs[1] = {{data, bytes}};
223  io_request<buffers_type> reqs(buffers_type(_reqs), offset);
224  OUTCOME_TRY(v, read(reqs, d));
225  return *v.data();
226  }
span< buffer_type > buffers_type
The scatter buffers type used by this handle. Guaranteed to be TrivialType apart from construction...
Definition: io_handle.hpp:76
virtual io_result< buffers_type > read(io_request< buffers_type > reqs, deadline d=deadline()) noexcept
Read data from the open handle.

◆ relink()

virtual result<void> afio_v2_xxx::fs_handle::relink ( const path_handle base,
path_view_type  path,
bool  atomic_replace = true,
deadline  d = std::chrono::seconds(30) 
)
inlinevirtualnoexceptinherited

Relinks the current path of this open handle to the new path specified. If atomic_replace is true, the relink atomically and silently replaces any item at the new path specified. This operation is both atomic and silent matching POSIX behaviour even on Microsoft Windows where no Win32 API can match POSIX semantics.

Warning
Some operating systems provide a race free syscall for renaming an open handle (Windows). On all other operating systems this call is racy and can result in the wrong file entry being relinked. Note that unless flag::disable_safety_unlinks is set, this implementation opens a path_handle to the source containing directory first, then checks before relinking that the item about to be relinked has the same inode as the open file handle. It will retry this matching until success until the deadline given. This should prevent most unmalicious accidental loss of data.
Parameters
baseBase for any relative path.
pathThe relative or absolute new path to relink to.
atomic_replaceAtomically replace the destination if a file entry already is present there. Choosing false for this will fail if a file entry is already present at the destination, and may not be an atomic operation on some platforms (i.e. both the old and new names may be linked to the same inode for a very short period of time). Windows and recent Linuxes are always atomic.
dThe deadline by which the matching of the containing directory to the open handle's inode must succeed, else std::errc::timed_out will be returned.
Memory Allocations
Except on platforms with race free syscalls for renaming open handles (Windows), calls current_path() via parent_path_handle() and thus is both expensive and calls malloc many times.

◆ set_append_only()

virtual result<void> afio_v2_xxx::handle::set_append_only ( bool  enable)
inlinevirtualnoexceptinherited

Changes whether this handle is append only or not.

Warning
On Windows this is implemented as a bit of a hack to make it fast like on POSIX, so make sure you open the handle for read/write originally. Note unlike on POSIX the append_only disposition will be the only one toggled, seekable and readable will remain turned on.
Errors returnable
Whatever POSIX fcntl() returns. On Windows nothing is changed on the handle.
Memory Allocations
No memory allocation.

◆ temp_file()

static result<file_handle> afio_v2_xxx::file_handle::temp_file ( path_view_type  name = path_view_type(),
mode  _mode = mode::write,
creation  _creation = creation::if_needed,
caching  _caching = caching::temporary,
flag  flags = flag::unlink_on_close 
)
inlinestaticnoexceptinherited

Create a file handle creating the named file on some path which the OS declares to be suitable for temporary files. Most OSs are very lazy about flushing changes made to these temporary files. Note the default flags are to have the newly created file deleted on first handle close. Note also that an empty name is equivalent to calling random_file(path_discovery::storage_backed_temporary_files_directory()) and the creation parameter is ignored.

Note
If the temporary file you are creating is not going to have its path sent to another process for usage, this is the WRONG function to use. Use temp_inode() instead, it is far more secure.
Errors returnable
Any of the values POSIX open() or CreateFile() can return.
170  {
172  return name.empty() ? random_file(tempdirh, _mode, _caching, flags) : file(tempdirh, name, _mode, _creation, _caching, flags);
173  }
const path_handle & storage_backed_temporary_files_directory() noexcept
Returns a reference to an open handle to a verified temporary directory where files created are store...
static result< file_handle > file(const path_handle &base, path_view_type path, mode _mode=mode::read, creation _creation=creation::open_existing, caching _caching=caching::all, flag flags=flag::none) noexcept
static result< file_handle > random_file(const path_handle &dirpath, mode _mode=mode::write, caching _caching=caching::temporary, flag flags=flag::none) noexcept
Definition: file_handle.hpp:133
flag flags() const noexcept
The flags this handle was opened with.
Definition: handle.hpp:314

◆ temp_inode()

static result<file_handle> afio_v2_xxx::file_handle::temp_inode ( const path_handle dirh = path_discovery::storage_backed_temporary_files_directory(),
mode  _mode = mode::write,
flag  flags = flag::none 
)
inlinestaticnoexceptinherited

Securely create a file handle creating a temporary anonymous inode in the filesystem referred to by dirpath. The inode created has no name nor accessible path on the filing system and ceases to exist as soon as the last handle is closed, making it ideal for use as a temporary file where other processes do not need to have access to its contents via some path on the filing system (a classic use case is for backing shared memory maps).

Errors returnable
Any of the values POSIX open() or CreateFile() can return.

◆ truncate()

virtual result<extent_type> afio_v2_xxx::file_handle::truncate ( extent_type  newsize)
inlinevirtualnoexceptinherited

Resize the current maximum permitted extent of the file to the given extent, avoiding any new allocation of physical storage where supported. Note that on extents based filing systems this will succeed even if there is insufficient free space on the storage medium.

Returns
The bytes actually truncated to.
Parameters
newsizeThe bytes to truncate the file to.
Errors returnable
Any of the values POSIX ftruncate() or SetFileInformationByHandle() can return.

Reimplemented in afio_v2_xxx::mapped_file_handle.

◆ try_lock()

result<extent_guard> afio_v2_xxx::io_handle::try_lock ( extent_type  offset,
extent_type  bytes,
bool  exclusive = true 
)
inlinenoexceptinherited

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

405 { return lock(offset, bytes, exclusive, deadline(std::chrono::seconds(0))); }
virtual result< extent_guard > lock(extent_type offset, extent_type bytes, bool exclusive=true, deadline d=deadline()) noexcept
Tries to lock the range of bytes specified for shared or exclusive access. Be aware this passes throu...

◆ unlink()

virtual result<void> afio_v2_xxx::fs_handle::unlink ( deadline  d = std::chrono::seconds(30))
inlinevirtualnoexceptinherited

Unlinks the current path of this open handle, causing its entry to immediately disappear from the filing system. On Windows unless flag::win_disable_unlink_emulation is set, this behaviour is simulated by renaming the file to something random and setting its delete-on-last-close flag. Note that Windows may prevent the renaming of a file in use by another process, if so it will NOT be renamed. After the next handle to that file closes, it will become permanently unopenable by anyone else until the last handle is closed, whereupon the entry will be eventually removed by the operating system.

Warning
Some operating systems provide a race free syscall for unlinking an open handle (Windows). On all other operating systems this call is racy and can result in the wrong file entry being unlinked. Note that unless flag::disable_safety_unlinks is set, this implementation opens a path_handle to the containing directory first, then checks that the item about to be unlinked has the same inode as the open file handle. It will retry this matching until success until the deadline given. This should prevent most unmalicious accidental loss of data.
Parameters
dThe deadline by which the matching of the containing directory to the open handle's inode must succeed, else std::errc::timed_out will be returned.
Memory Allocations
Except on platforms with race free syscalls for unlinking open handles (Windows), calls current_path() and thus is both expensive and calls malloc many times. On Windows, also calls current_path() if flag::disable_safety_unlinks is not set.

◆ unlock()

virtual void afio_v2_xxx::io_handle::unlock ( extent_type  offset,
extent_type  bytes 
)
inlinevirtualnoexceptinherited

Unlocks a byte range previously locked.

Parameters
offsetThe offset to unlock. This should be an offset previously locked.
bytesThe number of bytes to unlock. This should be a byte extent previously locked.
Errors returnable
Any of the values POSIX fcntl() can return.
Memory Allocations
None.

◆ write() [1/2]

virtual io_result<const_buffers_type> afio_v2_xxx::io_handle::write ( io_request< const_buffers_type reqs,
deadline  d = deadline() 
)
inlinevirtualnoexceptinherited

Write data to the open handle.

Warning
Depending on the implementation backend, not all of the buffers input may be written and the some buffers at the end of the returned buffers may return with zero bytes written. For example, with a zeroed deadline, some backends may only consume as many buffers as the system has available write slots for, thus for those backends this call is "non-blocking" in the sense that it will return immediately even if it could not schedule a single buffer write. Another example is that some implementations will not auto-extend the length of a file when a write exceeds the maximum extent, you will need to issue a truncate(newsize) first.
Returns
The buffers written, which may not be the buffers input. The size of each scatter-gather buffer is updated with the number of bytes of that buffer transferred.
Parameters
reqsA scatter-gather and offset request.
dAn optional deadline by which the i/o must complete, else it is cancelled. Note function may return significantly after this deadline if the i/o takes long to cancel.
Errors returnable
Any of the values POSIX write() can return, errc::timed_out, errc::operation_canceled. errc::not_supported may be returned if deadline i/o is not possible with this particular handle configuration (e.g. writing to regular files on POSIX or writing to a non-overlapped HANDLE on Windows).
Memory Allocations
The default synchronous implementation in file_handle performs no memory allocation. The asynchronous implementation in async_file_handle performs one calloc and one free.

◆ write() [2/2]

io_result<const_buffer_type> afio_v2_xxx::io_handle::write ( extent_type  offset,
const char *  data,
size_type  bytes,
deadline  d = deadline() 
)
inlinenoexceptinherited

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

253  {
254  const_buffer_type _reqs[1] = {{data, bytes}};
255  io_request<const_buffers_type> reqs(const_buffers_type(_reqs), offset);
256  OUTCOME_TRY(v, write(reqs, d));
257  return *v.data();
258  }
span< const_buffer_type > const_buffers_type
The gather buffers type used by this handle. Guaranteed to be TrivialType apart from construction...
Definition: io_handle.hpp:78
virtual io_result< const_buffers_type > write(io_request< const_buffers_type > reqs, deadline d=deadline()) noexcept
Write data to the open handle.

◆ zero()

virtual result<extent_type> afio_v2_xxx::file_handle::zero ( extent_type  offset,
extent_type  bytes,
deadline  d = deadline() 
)
inlinevirtualnoexceptinherited

Efficiently zero, and possibly deallocate, data on storage.

On most major operating systems and with recent filing systems which are "extents based", one can deallocate the physical storage of a file, causing the space deallocated to appear all bits zero. This call attempts to deallocate whole pages (usually 4Kb) entirely, and memset's any excess to all bits zero. This call works on most Linux filing systems with a recent kernel, Microsoft Windows with NTFS, and FreeBSD with ZFS. On other systems it simply writes zeros.

Returns
The bytes zeroed.
Parameters
offsetThe offset to start zeroing from.
bytesThe number of bytes to zero.
dAn optional deadline by which the i/o must complete, else it is cancelled. Note function may return significantly after this deadline if the i/o takes long to cancel.
Errors returnable
Any of the values POSIX write() can return, errc::timed_out, errc::operation_canceled. errc::not_supported may be returned if deadline i/o is not possible with this particular handle configuration (e.g. writing to regular files on POSIX or writing to a non-overlapped HANDLE on Windows).
Memory Allocations
The default synchronous implementation in file_handle performs no memory allocation. The asynchronous implementation in async_file_handle may perform one calloc and one free.

Reimplemented in afio_v2_xxx::mapped_file_handle.


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