nlib
nlib Platform APIs

The most basic nlib API that has C linkage. More...

Files

file  Platform.h
 Basic APIs are declared with a C linkage.
 

Classes

struct  nlib_timerspec
 Specifies the time to elapse before the timer initially starts up and the interval between the subsequent startups. If 0 is specified for the both values, the timer stops. More...
 
struct  nlib_mq_attr
 Structure to store the settings and current status of a message queue. More...
 

Macros

#define RSIZE_MAX   0x7FFFFFFFFFFFFFFFLL
 Defines a value somewhat smaller than the maximum value of size_t. More...
 

Typedefs

typedef unsigned char nlib_byte_t
 This type will be defined as std::byte in a typedef of C++17 or later.
 
typedef int32_t nlib_long_compatible_t
 Defines an integer type that is compatible with long using typedef.
 
typedef uint32_t nlib_ulong_compatible_t
 Defines an integer type that is compatible with unsigned long using typedef.
 

Version

Macros and functions for getting the nlib version information.

#define NLIB_VERSION   20170926
 Defines the version number. Defines numerical values that correspond to the year, month, and day of the release.
 
#define NLIB_VERSION_YEAR   2017
 Defines an integer that corresponds to the year portion of the version number.
 
#define NLIB_VERSION_YEAR_SHORT   17
 Defines an integer that corresponds to the lower two digits of the year portion of the version number.
 
#define NLIB_VERSION_DATE   0926
 Defines an integer that corresponds to the month portion of the version number.
 
#define nlib_getversion   NLIB_CAPI(nlib_getversion)
 Dynamically gets the nlib version. More...
 
#define nlib_compiler_version   NLIB_CAPI(nlib_compiler_version)
 Dynamically obtains the compiler version used to compile nlib. More...
 

CRC-32, CRC-32C

Calculates quickly using dedicated instructions if SSE or NEON is available.

uint32_t nlib_crc32 (uint32_t crc32, const void *p, size_t n)
 This function calculates the CRC-32 checksum value for data. More...
 
uint32_t nlib_crc32c (uint32_t crc32c, const void *p, size_t n)
 This function calculates the CRC-32C checksum value for data. More...
 

Memory Fences

Low-level primitives for synchronizing memory access when programming for multicore processors.

#define NLIB_MEMORY_ORDER_RELEASE   __atomic_thread_fence(__ATOMIC_RELEASE)
 A memory fence. Corresponds to atomic_thread_fence(memory_order_release) in C++11.
 
#define NLIB_MEMORY_ORDER_ACQUIRE   __atomic_thread_fence(__ATOMIC_ACQUIRE)
 A memory fence. Corresponds to atomic_thread_fence(memory_order_acquire) in C++11.
 
#define NLIB_MEMORY_ORDER_ACQ_REL   __atomic_thread_fence(__ATOMIC_ACQ_REL)
 A memory fence. Corresponds to atomic_thread_fence(memory_order_acq_rel) in C++11.
 
#define NLIB_MEMORY_ORDER_SEQ_CST   __atomic_thread_fence(__ATOMIC_SEQ_CST)
 A memory fence. Corresponds to atomic_thread_fence(memory_order_seq_cst) in C++11.
 

Attributes

A macro for handling differences in attributes in every compiler.

#define NLIB_WARN(exp)   ("WARNING: " exp)
 Outputs a warning. More...
 
#define NLIB_ALWAYS_INLINE   inline __attribute__((always_inline))
 Indicates that the compiler is forced to perform inline expansion of functions. More...
 
#define NLIB_NEVER_INLINE   __attribute__((__noinline__))
 Indicates that the compiler does not perform inline expansion of functions. More...
 
#define NLIB_LIKELY(x)   __builtin_expect(!!(x), 1)
 Indicates to the compiler that condition x is likely to be true. More...
 
#define NLIB_UNLIKELY(x)   __builtin_expect(!!(x), 0)
 Indicates to the compiler that condition x is likely to be false. More...
 
#define NLIB_CHECK_RESULT   __attribute__((warn_unused_result))
 Indicates that the caller of the function must check the returned value. More...
 
#define NLIB_NORETURN   __attribute__((noreturn))
 Indicates that the process will not return from functions. More...
 
#define NLIB_NONNULL   __attribute__((nonnull))
 Indicates that you cannot specify NULL for all arguments. More...
 
#define NLIB_NONNULL_1   __attribute__((nonnull (1)))
 Indicates that you cannot specify NULL for the first argument. More...
 
#define NLIB_NONNULL_2   __attribute__((nonnull (2)))
 Indicates that you cannot specify NULL for the second argument. More...
 
#define NLIB_NONNULL_3   __attribute__((nonnull (3)))
 Indicates that you cannot specify NULL for the third argument. More...
 
#define NLIB_NONNULL_4   __attribute__((nonnull (4)))
 Indicates that you cannot specify NULL for the fourth argument. More...
 
#define NLIB_NONNULL_5   __attribute__((nonnull (5)))
 Indicates that you cannot specify NULL for the fifth argument. More...
 
#define NLIB_ATTRIBUTE_MALLOC   __attribute__((malloc))
 Defines __attribute__((malloc)) if it is available for use. More...
 
#define NLIB_ATTRIBUTE_PURE   __attribute__((pure))
 Defines __attribute__((pure)) if it is available for use. More...
 
#define NLIB_ATTRIBUTE_CONST   __attribute__((const))
 Defines __attribute__((const)) if it is available for use. More...
 
#define NLIB_DEPRECATED   [[deprecated]]
 Indicates that a function or something has been deprecated. More...
 
#define NLIB_WEAKSYMBOL   __attribute__((weak))
 Used for defining weak symbols. More...
 
#define NLIB_VIS_HIDDEN   __attribute__((visibility("hidden")))
 Symbols for functions and classes are not made available outside of the library. More...
 
#define NLIB_VIS_PUBLIC   __attribute__((visibility("default")))
 Symbols for functions and classes are made available outside of the library. More...
 
#define NLIB_ASSUME(cond)   switch (0) case 0: default: if (cond) ; else __builtin_unreachable() /* NOLINT */
 Indicates that cond is true and provides tips for optimizing the compiler. More...
 

Macros for evaluating the environment

#define NLIB_LITTLE_ENDIAN
 Defined if the environment is little endian-based.
 
#define NLIB_64BIT
 Defined if the environment is 64-bit architecture-based.
 

Errors

Utilities related to error values.

#define nlib_get_native_last_error   NLIB_CAPI(nlib_get_native_last_error)
 Returns the last generated native error code. More...
 
const char * nlib_error_string (errno_t e)
 Returns a string literal corresponding to the error value of nlib. More...
 
template<class T >
bool nlib_is_error (const T &obj) noexcept
 Returns true when the process result or object status is in an erroneous condition. More...
 
typedef int errno_t
 Indicates with an int-type typedef that a POSIX error value is returned as the return value.
 

Time and Duration

Functions for getting times and durations, and sleeping based on times and durations.

errno_t nlib_epochtime (nlib_time *t)
 Gets the current time. More...
 
errno_t nlib_ticktime (nlib_duration *t)
 Gets the elapsed time since the system was last started. More...
 
errno_t nlib_sleep (nlib_duration t)
 Sleeps for the duration of t. More...
 
static errno_t nlib_epochtime_timespec (struct timespec *tm)
 A version taking the timespec structure as the argument of nlib_epochtime().
 
static errno_t nlib_ticktime_timespec (struct timespec *tm)
 A version taking the timespec structure as the argument of nlib_ticktime().
 
static errno_t nlib_sleep_timespec (const struct timespec *tm)
 A version taking the timespec structure as the argument of nlib_sleep().
 
typedef int64_t nlib_time
 The type expressing the time in increments of 100 ns from the zero starting point of 1970-01-01. A 64-bit signed integer.
 
typedef int64_t nlib_duration
 The type expressing the time in increments of 100 ns. A 64-bit signed integer.
 

A timer

It allows a task to be regularly run.

errno_t nlib_timer_create (nlib_timer *timer, nlib_timer_callback callback, void *param, uint32_t flags)
 Creates a timer. More...
 
errno_t nlib_timer_settime (nlib_timer timer, const nlib_timerspec *new_value, nlib_timerspec *old_value)
 Starts or suspends the timer. More...
 
errno_t nlib_timer_gettime (nlib_timer timer, nlib_timerspec *curr_value)
 Obtains the current timer settings. More...
 
errno_t nlib_timer_delete (nlib_timer timer, int wait_completion, nlib_timer_callback completion_callback)
 Deletes a timer. More...
 
typedef uint32_t nlib_timer
 The ID of the timer used with nlib_timer_create() and nlib_timer_delete().
 
typedef void(* nlib_timer_callback) (nlib_timer timer, void *param)
 The type of callback functions set with nlib_timer_create().
 
nlib_duration nlib_timerspec::due_time
 Specifies the time to elapse before the timer initially starts up.
 
nlib_duration nlib_timerspec::interval
 Specifies the interval between the startups of the timer following its initial startup. If 0 is specified, the time works as a one-shot timer.
 

Random Value Generation

errno_t nlib_gen_random (void *buf, size_t size)
 Generates a random value of size bytes and stores it in buf. More...
 

Allocation of Memory From the Operating System

Allows OS to allocate and free virtual memory spaces and to allocate and free physical memory.

errno_t nlib_mempagesize (size_t *size)
 Gets the page size. More...
 
errno_t nlib_virtual_alloc (void **ptr, size_t size)
 Allocates virtual memory address space. More...
 
errno_t nlib_virtual_free (void *ptr, size_t size)
 Frees the allocated virtual memory address space. More...
 
errno_t nlib_physical_alloc (void *ptr, size_t size, int prot)
 Allocates physical memory. More...
 
errno_t nlib_physical_free (void *ptr, size_t size)
 Frees the allocated physical memory. More...
 
errno_t nlib_mlock (void *addr, size_t len)
 The specified memory region is not swapped out. More...
 
errno_t nlib_munlock (void *addr, size_t len)
 The specified memory region can be swapped out. More...
 

TLS

Thread local storage (TLS) is a mechanism for accessing different memory for each thread.

#define NLIB_TLS_INVALID   (nlib_tls)(-1)
 Value indicating the ID of an invalid TLS slot.
 
errno_t nlib_tls_alloc (nlib_tls *tls, nlib_tls_destructor destr)
 Allocates a new ID for the specified TLS slot. More...
 
errno_t nlib_tls_free (nlib_tls tls)
 Frees the ID corresponding to the TLS slot. More...
 
errno_t nlib_tls_setvalue (nlib_tls tls, const void *value)
 Stores a value in a TLS slot. More...
 
errno_t nlib_tls_getvalue (nlib_tls tls, void **value)
 Gets the value from a TLS slot. More...
 
typedef pthread_key_t nlib_tls
 The type for TLS slot IDs.
 
typedef void(* nlib_tls_destructor) (void *tls_value)
 The type for the TLS destructor function called when the thread is ended. More...
 

Spinlock

Performs spinlock. Spin lock can be statically initialized.

#define NLIB_SPINLOCK_INITIALIZER   (0)
 Macro for statically initializing nlib_spinlock.
 
static void nlib_spinlock_init (nlib_spinlock *lock)
 Initializes the spinlock. More...
 
static void nlib_spinlock_lock (nlib_spinlock *lock)
 Locks the spinlock. Behavior is undefined if a recursive lock is performed. More...
 
static errno_t nlib_spinlock_trylock (nlib_spinlock *lock)
 Locks the spinlock. Returns 0 if successful or EBUSY if fails. More...
 
static void nlib_spinlock_unlock (nlib_spinlock *lock)
 Unlocks the spinlock. More...
 
typedef int32_t nlib_spinlock
 Spinlock variable type. Used by statically initializing with NLIB_SPINLOCK_INITIALIZER. More...
 

Mutex

Provides an interface that is based on the pthread mutex.

#define NLIB_MUTEX_INITIALIZER   PTHREAD_MUTEX_INITIALIZER
 A macro for statically initializing nlib_mutex.
 
#define NLIB_RECURSIVE_MUTEX_INITIALIZER   PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
 A macro for statically initializing nlib_mutex. Makes it a recursive mutex.
 
#define NLIB_RECURSIVE_TIMED_MUTEX_INITIALIZER   PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
 A macro for statically initializing nlib_mutex. Makes it a recursive mutex that can time out.
 
errno_t nlib_mutex_init (nlib_mutex *mutex) NLIB_EXCLUDES(*mutex)
 Initializes a mutex. More...
 
errno_t nlib_mutex_recursive_init (nlib_mutex *mutex) NLIB_EXCLUDES(*mutex)
 Initializes a recursive mutex. More...
 
errno_t nlib_mutex_recursive_timed_init (nlib_mutex *mutex) NLIB_EXCLUDES(*mutex)
 Initializes a mutex that is recursive and can time out. More...
 
errno_t nlib_mutex_lock (nlib_mutex *mutex) NLIB_ACQUIRE(*mutex)
 Locks the specified mutex. More...
 
errno_t nlib_mutex_trylock (nlib_mutex *mutex) NLIB_TRY_ACQUIRE(0
 Locks mutex, but only if it is not locked. More...
 
errno_t nlib_mutex_trylock_for (nlib_mutex *mutex, nlib_duration delta) NLIB_TRY_ACQUIRE(0
 Locks the specified mutex. Times out. More...
 
static errno_t nlib_mutex_trylock_for_timespec (nlib_mutex *mutex, const struct timespec *tm) NLIB_TRY_ACQUIRE(0
 A version taking the timespec structure as the argument of nlib_mutex_trylock_for().
 
errno_t nlib_mutex_unlock (nlib_mutex *mutex) NLIB_RELEASE(*mutex)
 Unlocks the specified mutex. More...
 
errno_t nlib_mutex_destroy (nlib_mutex *mutex) NLIB_EXCLUDES(*mutex)
 Destroys the specified mutex object and frees any associated resources. More...
 
typedef pthread_mutex_t nlib_mutex
 The type for mutex variables. More...
 

Semaphores

errno_t nlib_semaphore_init (nlib_semaphore *sem, int initial_count)
 Initializes the semaphore object specified by sem. More...
 
errno_t nlib_semaphore_wait (nlib_semaphore *sem)
 Waits until the semaphore count is no longer 0 and decrements the semaphore count by 1. More...
 
errno_t nlib_semaphore_trywait (nlib_semaphore *sem)
 Decrements the semaphore count by 1 if the count is not 0. More...
 
errno_t nlib_semaphore_trywait_for (nlib_semaphore *sem, nlib_duration duration)
 Decrements the semaphore count by 1 if the count is not 0. If 0, waits for the period specified by duration. More...
 
static errno_t nlib_semaphore_trywait_for_timespec (nlib_semaphore *sem, const struct timespec *tm)
 A version taking the timespec structure as the argument of nlib_semaphore_trywait_for().
 
errno_t nlib_semaphore_post (nlib_semaphore *sem, int *previous_count)
 Increments the semaphore count by 1. More...
 
errno_t nlib_semaphore_post_ex (nlib_semaphore *sem, int release_count, int *previous_count)
 Increments the semaphore count by the amount specified by releaseCount. More...
 
errno_t nlib_semaphore_destroy (nlib_semaphore *sem)
 Destroys the semaphore count. More...
 
typedef sem_t nlib_semaphore
 The type for a semaphore object. More...
 

Condition Variables

Provides an interface that is based on the pthread condition variables.

#define NLIB_COND_INITIALIZER   PTHREAD_COND_INITIALIZER
 Constant for statically initializing nlib_cond.
 
errno_t nlib_cond_init (nlib_cond *cond)
 Initializes a condition variable. More...
 
errno_t nlib_cond_signal (nlib_cond *cond)
 Resumes the execution of one thread that is waiting for condition variable cond. More...
 
errno_t nlib_cond_broadcast (nlib_cond *cond)
 Resumes the execution of all threads that are waiting for the conditional variable cond. More...
 
errno_t nlib_cond_wait (nlib_cond *cond, nlib_mutex *mutex) NLIB_REQUIRES(*mutex)
 Unlocks mutex and waits for a condition variable. It then relocks mutex after execution resumes. More...
 
errno_t nlib_cond_wait_for (nlib_cond *cond, nlib_mutex *mutex, nlib_duration duration) NLIB_REQUIRES(*mutex)
 Unlocks mutex and waits for just the duration amount of time for a condition variable. It then relocks mutex after execution resumes. More...
 
static errno_t nlib_cond_wait_for_timespec (nlib_cond *cond, nlib_mutex *mutex, const struct timespec *tm) NLIB_REQUIRES(*mutex)
 A version taking the timespec structure as the argument of nlib_cond_wait_for().
 
errno_t nlib_cond_wait_until (nlib_cond *cond, nlib_mutex *mutex, nlib_time abstime) NLIB_REQUIRES(*mutex)
 Unlocks mutex and waits until abstime for a condition variable. It then relocks mutex after execution resumes. More...
 
static errno_t nlib_cond_wait_until_timespec (nlib_cond *cond, nlib_mutex *mutex, const struct timespec *tm) NLIB_REQUIRES(*mutex)
 A version taking the timespec structure as the argument of nlib_cond_wait_until().
 
errno_t nlib_cond_destroy (nlib_cond *cond)
 Destroys a condition variable object. More...
 
typedef pthread_cond_t nlib_cond
 The type for a condition variable object. More...
 

Read-Write Locks

A mechanism for allowing multiple readers to access a read-write lock at the same time, and for allowing only exclusive access by the writer when updating.

#define NLIB_RWLOCK_INITIALIZER
 Constant for statically initializing nlib_rwlock.
 
errno_t nlib_rwlock_init (nlib_rwlock *rwlock) NLIB_EXCLUDES(*rwlock)
 Initializes a read-write lock object. More...
 
errno_t nlib_rwlock_destroy (nlib_rwlock *rwlock) NLIB_EXCLUDES(*rwlock)
 Destroys a read-write lock object. More...
 
errno_t nlib_rwlock_rdlock (nlib_rwlock *rwlock) NLIB_ACQUIRE_SHARED(*rwlock)
 Gets the read lock, and enters the critical section. Blocks until it can get a lock. More...
 
errno_t nlib_rwlock_tryrdlock (nlib_rwlock *rwlock) NLIB_TRY_ACQUIRE_SHARED(0
 Gets the read lock, and attempts to enter the critical section. More...
 
errno_t nlib_rwlock_tryrdlock_for (nlib_rwlock *rwlock, nlib_duration duration) NLIB_TRY_ACQUIRE_SHARED(0
 Gets the read lock, and attempts to enter the critical section. Times out. More...
 
static errno_t nlib_rwlock_tryrdlock_for_timespec (nlib_rwlock *rwlock, const struct timespec *tm) NLIB_TRY_ACQUIRE_SHARED(0
 A version taking the timespec structure as the argument of nlib_rwlock_tryrdlock_for().
 
errno_t nlib_rwlock_tryrdlock_until (nlib_rwlock *rwlock, nlib_time abstime) NLIB_TRY_ACQUIRE_SHARED(0
 Gets the read lock, and attempts to enter the critical section. Times out. More...
 
static errno_t nlib_rwlock_tryrdlock_until_timespec (nlib_rwlock *rwlock, const struct timespec *tm) NLIB_TRY_ACQUIRE_SHARED(0
 A version taking the timespec structure as the argument of nlib_rwlock_tryrdlock_until().
 
errno_t nlib_rwlock_rdunlock (nlib_rwlock *rwlock) NLIB_RELEASE_SHARED(*rwlock)
 Releases the read lock. More...
 
errno_t nlib_rwlock_wrlock (nlib_rwlock *rwlock) NLIB_ACQUIRE(*rwlock)
 Gets a write lock, and enters the critical section. Blocks until it can get a lock. More...
 
errno_t nlib_rwlock_trywrlock (nlib_rwlock *rwlock) NLIB_TRY_ACQUIRE(0
 Gets a write lock, and attempts to enter the critical section. More...
 
errno_t nlib_rwlock_trywrlock_for (nlib_rwlock *rwlock, nlib_duration duration) NLIB_TRY_ACQUIRE(0
 Gets a write lock, and attempts to enter the critical section. Times out. More...
 
static errno_t nlib_rwlock_trywrlock_for_timespec (nlib_rwlock *rwlock, const struct timespec *tm) NLIB_TRY_ACQUIRE(0
 A version taking the timespec structure as the argument of nlib_rwlock_trywrlock_for().
 
errno_t nlib_rwlock_trywrlock_until (nlib_rwlock *rwlock, nlib_time abstime) NLIB_TRY_ACQUIRE(0
 Gets a write lock, and attempts to enter the critical section. Times out. More...
 
static errno_t nlib_rwlock_trywrlock_until_timespec (nlib_rwlock *rwlock, const struct timespec *tm) NLIB_TRY_ACQUIRE(0
 A version taking the timespec structure as the argument of nlib_rwlock_trywrlock_until().
 
errno_t nlib_rwlock_wrunlock (nlib_rwlock *rwlock) NLIB_RELEASE(*rwlock)
 Releases a write lock. More...
 
typedef struct nlib_rwlock_ nlib_rwlock
 The type for a read-write lock object. More...
 

Conditional Variable for Read-Write Locks

A conditional variable available for nlib_rwlock.

#define NLIB_CONDRWLOCK_INITIALIZER   { NLIB_COND_INITIALIZER, NLIB_MUTEX_INITIALIZER }
 Constant for statically initializing nlib_condrwlock.
 
errno_t nlib_condrwlock_init (nlib_condrwlock *cond)
 Initializes a read-write lock conditional variable. More...
 
errno_t nlib_condrwlock_destroy (nlib_condrwlock *cond)
 Destroys a read-write lock conditional variable. More...
 
errno_t nlib_condrwlock_signal (nlib_condrwlock *cond)
 Resumes the execution of one thread that is waiting for the read-write lock conditional variable cond. More...
 
errno_t nlib_condrwlock_broadcast (nlib_condrwlock *cond)
 Resumes the execution of all threads that are waiting for the read-write lock conditional variable cond. More...
 
errno_t nlib_condrwlock_wait (nlib_condrwlock *cond, nlib_rwlock *rwlock, int rdlock)
 Unlocks rwlock and waits for a conditional variable. It then locks rwlock again after the execution resumes. More...
 
errno_t nlib_condrwlock_wait_for (nlib_condrwlock *cond, nlib_rwlock *rwlock, nlib_duration duration, int rdlock)
 Unlocks rwlock and waits for a conditional variable. It then locks rwlock again after the execution resumes. More...
 
static errno_t nlib_condrwlock_wait_for_timespec (nlib_condrwlock *cond, nlib_rwlock *rwlock, const struct timespec *tm, int rdlock)
 A version taking the imespec structure as the argument of nlib_condrwlock_wait_for_timespec().
 
errno_t nlib_condrwlock_wait_until (nlib_condrwlock *cond, nlib_rwlock *rwlock, nlib_time abstime, int rdlock)
 Unlocks rwlock and waits for a conditional variable. It then locks rwlock again after the execution resumes. More...
 
static errno_t nlib_condrwlock_wait_until_timespec (nlib_condrwlock *cond, nlib_rwlock *rwlock, const struct timespec *tm, int rdlock)
 A version taking the timespec structure as the argument of nlib_condrwlock_wait_until_timespec().
 
typedef struct nlib_condrwlock_ nlib_condrwlock
 Type of the conditional variable for read-write locks. More...
 

Barriers

Synchronizes multiple threads to the end of a particular task. Can be used repeatedly.

errno_t nlib_barrier_init (nlib_barrier *barrier, unsigned int count)
 Initializes a barrier object. More...
 
errno_t nlib_barrier_destroy (nlib_barrier *barrier)
 Destroys a barrier object. More...
 
errno_t nlib_barrier_wait (nlib_barrier *barrier)
 Waits for a thread. More...
 
typedef struct nlib_barrier_ nlib_barrier
 The type for a barrier object. More...
 

Macros for Atomic Functions

#define NLIB_ATOMIC_RELAXED   __ATOMIC_RELAXED
 Similar to __ATOMIC_RELAXED of gcc or std::memory_order_relaxed of C++11.
 
#define NLIB_ATOMIC_ACQUIRE   __ATOMIC_ACQUIRE
 Similar to __ATOMIC_ACQUIRE of gcc or std::memory_order_acquire of C++11.
 
#define NLIB_ATOMIC_RELEASE   __ATOMIC_RELEASE
 Similar to __ATOMIC_RELEASE of gcc or std::memory_order_release of C++11.
 
#define NLIB_ATOMIC_ACQ_REL   __ATOMIC_ACQ_REL
 Similar to __ATOMIC_ACQ_REL of gcc or std::memory_order_acq_rel of C++11.
 
#define NLIB_ATOMIC_SEQ_CST   __ATOMIC_SEQ_CST
 Similar to __ATOMIC_SEQ_CST of gcc or std::memory_order_seq_cst of C++11.
 

Atomic Functions (32 bit)

Specify one of NLIB_ATOMIC_RELAXED, NLIB_ATOMIC_ACQUIRE, NLIB_ATOMIC_RELEASE, NLIB_ATOMIC_ACQ_REL, and NLIB_ATOMIC_CST_SEQ for the memorder argument of each function.

Description
For more information, see the following documents:
See also
https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html
int32_t nlib_atomic_load32 (const int32_t *ptr, int memorder)
 Loads a value in an atomic operation. Its behavior is similar to the one for __atomic_load_n() of gcc.
 
void nlib_atomic_store32 (int32_t *ptr, int32_t val, int memorder)
 Stores a value in an atomic operation. Its behavior is similar to the one for __atomic_store_n() of gcc.
 
int32_t nlib_atomic_exchange32 (int32_t *ptr, int32_t val, int memorder)
 Swaps values in an atomic operation. Its behavior is similar to the one for __atomic_exchange_n() of gcc.
 
int nlib_atomic_compare_exchange32 (int32_t *ptr, int32_t *expected, int32_t desired, int weak, int success_memorder, int failure_memorder)
 Compares and swaps atomic values. Its behavior is similar to the one for __atomic_compare_exchange_n() of gcc.
 
int32_t nlib_atomic_add_fetch32 (int32_t *ptr, int32_t val, int memorder)
 Adds atomic values. Its behavior is similar to the one for __atomic_add_fetch() of gcc.
 
int32_t nlib_atomic_sub_fetch32 (int32_t *ptr, int32_t val, int memorder)
 Subtracts atomic values. Its behavior is similar to the one for __atomic_sub_fetch() of gcc.
 
int32_t nlib_atomic_and_fetch32 (int32_t *ptr, int32_t val, int memorder)
 Calculates AND of atomic values. Its behavior is similar to the one for __atomic_and_fetch() of gcc.
 
int32_t nlib_atomic_xor_fetch32 (int32_t *ptr, int32_t val, int memorder)
 Calculates XOR of atomic values. Its behavior is similar to the one for __atomic_xor_fetch() of gcc.
 
int32_t nlib_atomic_or_fetch32 (int32_t *ptr, int32_t val, int memorder)
 Calculates OR of atomic values. Its behavior is similar to the one for __atomic_or_fetch() of gcc.
 
int32_t nlib_atomic_fetch_add32 (int32_t *ptr, int32_t val, int memorder)
 Adds atomic values. Its behavior is similar to the one for __atomic_fetch_add() of gcc.
 
int32_t nlib_atomic_fetch_sub32 (int32_t *ptr, int32_t val, int memorder)
 Subtracts atomic values. Its behavior is similar to the one for __atomic_fetch_sub() of gcc.
 
int32_t nlib_atomic_fetch_and32 (int32_t *ptr, int32_t val, int memorder)
 Calculates AND of atomic values. Its behavior is similar to the one for __atomic_fetch_and() of gcc.
 
int32_t nlib_atomic_fetch_xor32 (int32_t *ptr, int32_t val, int memorder)
 Calculates XOR of atomic values. Its behavior is similar to the one for __atomic_fetch_xor() of gcc.
 
int32_t nlib_atomic_fetch_or32 (int32_t *ptr, int32_t val, int memorder)
 Calculates OR of atomic values. Its behavior is similar to the one for __atomic_fetch_or() of gcc.
 

Atomic Functions (64 bit)

Specify one of NLIB_ATOMIC_RELAXED, NLIB_ATOMIC_ACQUIRE, NLIB_ATOMIC_RELEASE, NLIB_ATOMIC_ACQ_REL, and NLIB_ATOMIC_CST_SEQ for the memorder argument of each function.

Description
For more information, see the following documents:
See also
https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html
int64_t nlib_atomic_load64 (const int64_t *ptr, int memorder)
 Loads a value in an atomic operation. Its behavior is similar to the one for __atomic_load_n() of gcc.
 
void nlib_atomic_store64 (int64_t *ptr, int64_t val, int memorder)
 Stores a value in an atomic operation. Its behavior is similar to the one for __atomic_store_n() of gcc.
 
int64_t nlib_atomic_exchange64 (int64_t *ptr, int64_t val, int memorder)
 Swaps values in an atomic operation. Its behavior is similar to the one for __atomic_exchange_n() of gcc.
 
int nlib_atomic_compare_exchange64 (int64_t *ptr, int64_t *expected, int64_t desired, int weak, int success_memorder, int failure_memorder)
 Compares and swaps atomic values. Its behavior is similar to the one for __atomic_compare_exchange_n() of gcc.
 
int64_t nlib_atomic_add_fetch64 (int64_t *ptr, int64_t val, int memorder)
 Adds atomic values. Its behavior is similar to the one for __atomic_add_fetch() of gcc.
 
int64_t nlib_atomic_sub_fetch64 (int64_t *ptr, int64_t val, int memorder)
 Subtracts atomic values. Its behavior is similar to the one for __atomic_sub_fetch() of gcc.
 
int64_t nlib_atomic_and_fetch64 (int64_t *ptr, int64_t val, int memorder)
 Calculates AND of atomic values. Its behavior is similar to the one for __atomic_and_fetch() of gcc.
 
int64_t nlib_atomic_xor_fetch64 (int64_t *ptr, int64_t val, int memorder)
 Calculates XOR of atomic values. Its behavior is similar to the one for __atomic_xor_fetch() of gcc.
 
int64_t nlib_atomic_or_fetch64 (int64_t *ptr, int64_t val, int memorder)
 Calculates OR of atomic values. Its behavior is similar to the one for __atomic_or_fetch() of gcc.
 
int64_t nlib_atomic_fetch_add64 (int64_t *ptr, int64_t val, int memorder)
 Adds atomic values. Its behavior is similar to the one for __atomic_fetch_add() of gcc.
 
int64_t nlib_atomic_fetch_sub64 (int64_t *ptr, int64_t val, int memorder)
 Subtracts atomic values. Its behavior is similar to the one for __atomic_fetch_sub() of gcc.
 
int64_t nlib_atomic_fetch_and64 (int64_t *ptr, int64_t val, int memorder)
 Calculates AND of atomic values. Its behavior is similar to the one for __atomic_fetch_and() of gcc.
 
int64_t nlib_atomic_fetch_xor64 (int64_t *ptr, int64_t val, int memorder)
 Calculates XOR of atomic values. Its behavior is similar to the one for __atomic_fetch_xor() of gcc.
 
int64_t nlib_atomic_fetch_or64 (int64_t *ptr, int64_t val, int memorder)
 Calculates OR of atomic values. Its behavior is similar to the one for __atomic_fetch_or() of gcc.
 

Atomic Functions (pointer type)

Specify one of NLIB_ATOMIC_RELAXED, NLIB_ATOMIC_ACQUIRE, NLIB_ATOMIC_RELEASE, NLIB_ATOMIC_ACQ_REL, and NLIB_ATOMIC_CST_SEQ for the memorder argument of each function.

Description
For more information, see the following documents:
See also
https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html
void * nlib_atomic_loadptr (void *const *ptr, int memorder)
 Loads a value in an atomic operation. Its behavior is similar to the one for __atomic_load_n() of gcc.
 
void nlib_atomic_storeptr (void **ptr, void *val, int memorder)
 Stores a value in an atomic operation. Its behavior is similar to the one for __atomic_store_n() of gcc.
 
void * nlib_atomic_exchangeptr (void **ptr, void *val, int memorder)
 Swaps values in an atomic manner. Its behavior is similar to the one for __atomic_exchange_n() of gcc.
 
int nlib_atomic_compare_exchangeptr (void **ptr, void **expected, void *desired, int weak, int success_memorder, int failure_memorder)
 Compares and swaps atomic values. Its behavior is similar to the one for __atomic_compare_exchange_n() of gcc.
 

Memory Barrier

Specify one of NLIB_ATOMIC_RELAXED, NLIB_ATOMIC_ACQUIRE, NLIB_ATOMIC_RELEASE, NLIB_ATOMIC_ACQ_REL, and NLIB_ATOMIC_CST_SEQ for the memorder argument of each function.

Description
For more information, see the following documents:
See also
https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html
void nlib_atomic_thread_fence (int memorder)
 Places the specified memory barrier.
 

One-Time Execution

A mechanism for guaranteeing that a particular process is executed only once.

#define NLIB_ONCE_INIT   { 0 }
 The value for statically initializing nlib_onceflag.
 
errno_t nlib_once (nlib_onceflag *flag, nlib_oncefunc func)
 Ensures that func is executed only one time at most. More...
 
typedef struct nlib_onceflag_ nlib_onceflag
 The structure to use with nlib_once.
 
typedef void(* nlib_oncefunc) (void)
 The type for functions to execute with nlib_once.
 

Message Queue

See nlib_mq_open() for the features of nlib message queue.

errno_t nlib_mq_open (nlib_mq *mq, const nlib_mq_attr *attr)
 Creates a message queue to be used to exchange messages across threads. More...
 
errno_t nlib_mq_getattr (nlib_mq mq, nlib_mq_attr *attr)
 Obtains the attribute set to the message queue indicated with a handle. More...
 
errno_t nlib_mq_close (nlib_mq mq)
 Closes the message queue indicated with a handle. More...
 
errno_t nlib_mq_readonly (nlib_mq mq)
 Sets the message queue indicated with a handle as receive-only. More...
 
errno_t nlib_mq_send (nlib_mq mq, nlib_mq_msg msg, int prio)
 Sends a message to a queue. More...
 
errno_t nlib_mq_send_until (nlib_mq mq, nlib_mq_msg msg, int prio, nlib_time abstime)
 Sends a messages with a time-out set to the queue. More...
 
errno_t nlib_mq_receive (nlib_mq mq, nlib_mq_msg *msg, int *prio)
 Receives a message from a queue. It is the user's responsibility to delete the received messages using a destructor function. More...
 
errno_t nlib_mq_receive_until (nlib_mq mq, nlib_mq_msg *msg, int *prio, nlib_time abstime)
 Receives a message with a time-out set from a queue. It is the user's responsibility to delete the received messages using a destructor function. More...
 
errno_t nlib_mq_drop (nlib_mq mq, nlib_mq_msg *msg, int *prio)
 Receives a message with the lowest priority from a queue. It is the user's responsibility to delete the received messages using a destructor function. More...
 
typedef int32_t nlib_mq
 Handle associated with a message queue. If the handle is cleared to zero (using memset()), it will always be an invalid handle.
 
typedef void * nlib_mq_msg
 Type of messages stored in a message queue.
 
typedef void(* nlib_mq_msg_destructor) (nlib_mq_msg)
 Destructor function for messages taken from a message queue.
 
int32_t nlib_mq_attr::flag
 Settings to be used when creating a message queue. More...
 
int32_t nlib_mq_attr::max_msg
 When creating a message queue, you can set the maximum number of messages.
 
int32_t nlib_mq_attr::cur_msg
 For a queue other than a lock-free queue, you can obtain the number of messages that are currently in that message queue.
 
nlib_mq_msg_destructor nlib_mq_attr::destructor
 A destructor function for a message taken from a message queue can be set or obtained.
 

Threads

#define NLIB_THREAD_INVALID   (nlib_thread)(0)
 Value indicating an invalid thread.
 
#define nlib_yield   NLIB_CAPI(nlib_yield)
 Relinquishes thread execution rights. More...
 
#define nlib_thread_exit   NLIB_CAPI(nlib_thread_exit)
 Ends the called thread. More...
 
#define nlib_thread_exit_cpp   NLIB_CAPI(nlib_thread_exit_cpp)
 Ends the called thread. More...
 
static void nlib_pause (void)
 Waits for a very short time. More...
 
errno_t nlib_thread_create (nlib_thread *thread, const nlib_thread_attr *attr, nlib_thread_func func, void *arg)
 Creates and executes a new thread. More...
 
errno_t nlib_thread_join (nlib_thread thread)
 Waits for the thread to terminate. More...
 
errno_t nlib_thread_detach (nlib_thread thread)
 Detaches an executing thread. More...
 
errno_t nlib_thread_self (nlib_thread *thread)
 Stores the nlib_thread value corresponding to the executing thread. More...
 
errno_t nlib_thread_getconcurrency (unsigned int *num_cpu)
 Gets the number of hardware threads. More...
 
errno_t nlib_thread_getid (nlib_thread_id *id)
 Stores a unique integer value corresponding to the executing thread. More...
 
int nlib_thread_equal (nlib_thread th1, nlib_thread th2)
 Checks whether two threads point to the same thread. More...
 
errno_t nlib_thread_getcpu (int *result)
 Gets the CPU on which the called thread is executing. More...
 
errno_t nlib_thread_setaffinity (nlib_thread thread, uint32_t affinity)
 Sets a processor affinity mask for the specified thread. More...
 
errno_t nlib_thread_setname (nlib_thread thread, const char *name)
 Attaches a name to the thread. More...
 
errno_t nlib_thread_getname (nlib_thread thread, char *name, size_t len)
 Gets the thread name. More...
 
errno_t nlib_thread_attr_init (nlib_thread_attr *attr)
 Initializes a thread attribute object and sets it to the default. More...
 
errno_t nlib_thread_attr_setint (nlib_thread_attr *attr, int key, int value)
 Sets an integer corresponding to the key of the thread attribute object. More...
 
errno_t nlib_thread_attr_getint (const nlib_thread_attr *attr, int key, int *value)
 Gets the integer corresponding to the key of the thread attribute object. More...
 
errno_t nlib_thread_attr_setptr (nlib_thread_attr *attr, int key, void *value)
 Sets a pointer corresponding to the key of the thread attribute object. As of now, returns EINVAL only. More...
 
errno_t nlib_thread_attr_getptr (const nlib_thread_attr *attr, int key, void **value)
 Gets the pointer corresponding to the key of the thread attribute object. As of now, returns EINVAL only. More...
 
errno_t nlib_thread_attr_setstack (nlib_thread_attr *attr, void *stack_addr, size_t stack_size)
 Sets a stack setting for thread attribute objects. More...
 
errno_t nlib_thread_attr_getstack (const nlib_thread_attr *attr, void **stack_addr, size_t *stack_size)
 Obtains a stack setting for thread attribute objects. More...
 
errno_t nlib_thread_attr_destroy (nlib_thread_attr *attr)
 Destroys a thread-initialization object. More...
 
errno_t nlib_thread_getpriority (nlib_thread thread, int *priority)
 Gets the current execution priority of the thread. The meaning of the numerical value is implementation-dependent. More...
 
errno_t nlib_thread_setpriority (nlib_thread thread, int priority)
 Sets the execution priority of the thread. The meaning of the numerical value is implementation-dependent. More...
 
errno_t nlib_thread_priority_min (int *priority)
 Gets the smallest numerical value that can be specified for the execution priority. More...
 
errno_t nlib_thread_priority_max (int *priority)
 Gets the largest numerical value that can be specified for the execution priority. More...
 
errno_t nlib_thread_priority_default (int *priority)
 Gets the default numerical value that can be specified for the execution priority. More...
 
void nlib_thread_cleanup_push (void(*fn)(void *), void *arg)
 Pushes fn to a dedicated stack. More...
 
void nlib_thread_cleanup_pop (int exec)
 Deletes the handler at the top of the stack storing the cleanup handler. More...
 
typedef pthread_t nlib_thread
 The identifier for threads. More...
 
typedef struct nlib_thread_attr_ nlib_thread_attr
 The thread attribute to apply to a newly created thread.
 
typedef void(* nlib_thread_func) (void *arg)
 A function to be run on a different thread. More...
 
typedef int nlib_thread_id
 A unique integer value for each thread.
 

Debugging and Debug Output

#define nlib_debug_break   NLIB_CAPI(nlib_debug_break)
 A breakpoint. More...
 
errno_t nlib_write_stdout (size_t *result, const void *buf, size_t count)
 Writes a string to standard output. More...
 
errno_t nlib_write_stderr (size_t *result, const void *buf, size_t count)
 Writes a string to standard error output. More...
 
errno_t nlib_debug_backtrace (size_t *result, void **buffer, size_t count)
 Stores backtraces in the array specified by buffer. More...
 
errno_t nlib_debug_backtrace_gettext (char *str, size_t strbufsize, void *const *buf, size_t count)
 Creates string information from the data obtained using the nlib_debug_backtrace function. More...
 
errno_t nlib_getenv (size_t *result, char *buf, size_t bufsize, const char *varname)
 Gets the value for the environment variable as a string. More...
 

Logging

Outputs logs to standard output, syslog, and files.

 kNlibLogVerbose
 Specifies the output of verbose messages. More...
 
 kNlibLogDebug
 Specifies the output of debug-level messages. More...
 
 kNlibLogInfo
 Specifies the output of information-level messages. More...
 
 kNlibLogWarn
 Specifies the output of warning-level messages. More...
 
 kNlibLogError
 Specifies the output of error-level messages. More...
 
 kNlibLogFatal
 Specifies the output of fatal-level messages. More...
 
 kNlibLogLevelEqualOrAbove = 0x10
 Uses a bitwise OR to output levels at and above the specified level. Can be used with the nlib_log_attr_setint function. More...
 
 kNlibLogLevelEqualOrBelow = 0x20
 Uses a bitwise OR to output levels at and below the specified level. Can be used with the nlib_log_attr_setint function. More...
 
 kNlibLogLevelAll = 0x30
 Specifies all priority levels. Can be used with the nlib_log_attr_setint function. More...
 
enum  nlib_log_priority { ,
  kNlibLogVerbose,
  kNlibLogDebug,
  kNlibLogInfo,
  kNlibLogWarn,
  kNlibLogError,
  kNlibLogFatal ,
  kNlibLogLevelEqualOrAbove = 0x10,
  kNlibLogLevelEqualOrBelow = 0x20,
  kNlibLogLevelAll = 0x30
}
 Defines the priority (level category) for output. More...
 
int nlib_log_print (int prio, const char *tag, const char *fmt,...)
 Outputs log messages. More...
 
int nlib_log_vprint (int prio, const char *tag, const char *fmt, va_list ap)
 Outputs log messages. More...
 
errno_t nlib_log_attr_setint (int prio, int key, int value)
 Specifies where to output the log for each level of priority. More...
 
 kNlibLogVerbose
 Specifies the output of verbose messages. More...
 
 kNlibLogDebug
 Specifies the output of debug-level messages. More...
 
 kNlibLogInfo
 Specifies the output of information-level messages. More...
 
 kNlibLogWarn
 Specifies the output of warning-level messages. More...
 
 kNlibLogError
 Specifies the output of error-level messages. More...
 
 kNlibLogFatal
 Specifies the output of fatal-level messages. More...
 
 kNlibLogLevelEqualOrAbove = 0x10
 Uses a bitwise OR to output levels at and above the specified level. Can be used with the nlib_log_attr_setint function. More...
 
 kNlibLogLevelEqualOrBelow = 0x20
 Uses a bitwise OR to output levels at and below the specified level. Can be used with the nlib_log_attr_setint function. More...
 
 kNlibLogLevelAll = 0x30
 Specifies all priority levels. Can be used with the nlib_log_attr_setint function. More...
 

Files

#define NLIB_FD_O_RDONLY   O_RDONLY
 Used for the flags parameter of the nlib_fd_open function.
 
#define NLIB_FD_O_WRONLY   O_WRONLY
 Used for the flags parameter of the nlib_fd_open function.
 
#define NLIB_FD_O_RDWR   O_RDWR
 Used for the flags parameter of the nlib_fd_open function.
 
#define NLIB_FD_O_APPEND   O_APPEND
 Used for the flags parameter of the nlib_fd_open function.
 
#define NLIB_FD_O_CREAT   O_CREAT
 Used for the flags parameter of the nlib_fd_open function.
 
#define NLIB_FD_O_TRUNC   O_TRUNC
 Used for the flags parameter of the nlib_fd_open function.
 
#define NLIB_FD_O_EXCL   O_EXCL
 Used for the flags parameter of the nlib_fd_open function.
 
#define NLIB_SEEK_SET   SEEK_SET
 Used for the whence parameter of the nlib_fd_seek function.
 
#define NLIB_SEEK_CUR   SEEK_CUR
 Used for the whence parameter of the nlib_fd_seek function.
 
#define NLIB_FD_INVALID   (-1)
 A macro defining invalid file descriptors.
 
errno_t nlib_fd_open (nlib_fd *fd, const char *native_path, unsigned int flags, int mode)
 Opens a file. More...
 
static errno_t nlib_fd_creat (nlib_fd *fd, const char *native_path, int mode)
 Equivalent to nlib_fd_open(fd, native_path, NLIB_FD_O_CREAT | NLIB_FD_O_WRONLY | NLIB_FD_O_EXCL, mode). Note that it fails if the file already exists.
 
errno_t nlib_fd_close (nlib_fd fd)
 Closes a file. The file descriptor will be released even if an error is returned. More...
 
errno_t nlib_fd_read (size_t *result, nlib_fd fd, void *buf, size_t count)
 Reads (up to) count bytes from the file descriptor into buf. More...
 
errno_t nlib_fd_write (size_t *result, nlib_fd fd, const void *buf, size_t count)
 Writes (up to) count bytes from buf to the file descriptor. More...
 
errno_t nlib_fd_seek (nlib_offset *result, nlib_fd fd, nlib_offset offset, int whence)
 Changes the file offset. More...
 
errno_t nlib_fd_pread (size_t *result, nlib_fd fd, void *buf, size_t count, nlib_offset offset)
 Reads the file descriptor from the specified offset. The offset for the file descriptor will not be changed. More...
 
errno_t nlib_fd_pwrite (size_t *result, nlib_fd fd, const void *buf, size_t count, nlib_offset offset)
 Writes to the file descriptor at the specified offset. The offset for the file descriptor will not be changed. More...
 
errno_t nlib_fd_truncate (nlib_fd fd, nlib_offset length)
 Extends or truncates the file to be the specified size. More...
 
errno_t nlib_fd_getsize (nlib_offset *size, nlib_fd fd)
 Gets the file size. More...
 
errno_t nlib_fd_flush (nlib_fd fd)
 Flushes the write to the file descriptor. More...
 
errno_t nlib_fd_sync (nlib_fd fd)
 Synchronizes the content of a file in memory with what is on the device. More...
 
errno_t nlib_fd_native_handle (void **native_handle, nlib_fd fd)
 Gets (the equivalent of) the native file handle. More...
 
errno_t nlib_fd_readv (size_t *result, nlib_fd fd, const nlib_fd_iovec *iov, int iovcnt)
 Loads multiple non-continuous buffers from the file associated with fd. More...
 
errno_t nlib_fd_writev (size_t *result, nlib_fd fd, const nlib_fd_iovec *iov, int iovcnt)
 Writes from multiple non-continuous buffers to the file associated with fd. More...
 
errno_t nlib_fd_preadv (size_t *result, nlib_fd fd, const nlib_fd_iovec *iov, int iovcnt, nlib_offset offset)
 Same as the nlib_fd_readv function except when the pread or nlib_fd_pread function is used internally.
 
errno_t nlib_fd_pwritev (size_t *result, nlib_fd fd, const nlib_fd_iovec *iov, int iovcnt, nlib_offset offset)
 Same as the nlib_fd_writev function except when the pwrite or nlib_fd_pwrite function is used internally.
 
errno_t nlib_unlink (const char *native_path)
 Deletes a file. More...
 
errno_t nlib_mkdir (const char *native_path, unsigned int flags)
 Creates a directory. More...
 
errno_t nlib_rmdir (const char *native_path)
 Deletes a directory. More...
 
errno_t nlib_remove (const char *native_path)
 Deletes a file or directory. Calls nlib_unlink() for a file, or nlib_rmdir() for a directory.
 
errno_t nlib_rename (const char *old_path, const char *new_path)
 Renames a file. More...
 
errno_t nlib_dir_open (nlib_dir *dir, const char *native_path)
 Opens a directory. More...
 
errno_t nlib_dir_close (nlib_dir dir)
 Closes a directory. More...
 
errno_t nlib_dir_read (nlib_dirent *ent, nlib_dir dir)
 Reads one directory entry, if there are any. More...
 
errno_t nlib_is_dir (int *result, const char *native_path)
 Checks whether the path is for a directory. Sets 0 in *result and returns 0 if no path exists. More...
 
errno_t nlib_exist_path (int *result, const char *native_path)
 Checks whether the path exists. More...
 
errno_t nlib_disk_freespace (const char *native_path, uint64_t *free_bytes_available, uint64_t *total_bytes, uint64_t *total_free_bytes)
 Gets information related to the capacity of the storage region to which the specified path belongs. More...
 
const char * nlib_basename (const char *path)
 
const char * nlib_dirname (size_t *len, const char *path)
 
errno_t nlib_mkostemps (nlib_fd *fd, char *templ, int suffixlen, int flags)
 Creates a temporary file with a unique name that is hard to be guessed. More...
 
errno_t nlib_fd_fileid (nlib_fileid *result, nlib_fd fd)
 
errno_t nlib_readlink (size_t *len, const char *native_path, char *buf, size_t bufsize)
 Resolve a symbolic link. More...
 
typedef int64_t nlib_offset
 The offset to the file. A 64-bit integer.
 
typedef int nlib_fd
 The original file descriptor of nlib (a 32-bit integer value). More...
 

printf

Functions for handling differences with the standard library printf.

Description
When describing a format string for printf, you may need to pay attention to its portability. Please refer to the following information:
See also
https://google.github.io/styleguide/cppguide.html#64-bit_Portability
http://www.textdrop.net/google-styleguide-ja/cppguide.xml#64%E3%83%93%E3%83%83%E3%83%88%E3%81%AE%E7%A7%BB%E6%A4%8D%E6%80%A7
#define PRIdS   __PRIS_PREFIX "d"
 Used when a size_t type is shown by printf. Corresponds to %zd.
 
#define PRIxS   __PRIS_PREFIX "x"
 Used when a size_t type is shown by printf. Corresponds to %zx.
 
#define PRIuS   __PRIS_PREFIX "u"
 Used when a size_t type is shown by printf. Corresponds to %zu.
 
#define PRIXS   __PRIS_PREFIX "X"
 Used when a size_t type is shown by printf. Corresponds to %zX.
 
#define PRIoS   __PRIS_PREFIX "o"
 Used when a size_t type is shown by printf. Corresponds to %zo.
 
errno_t nlib_vsnprintf (size_t *count, char *buf, size_t size, const char *fmt, va_list args)
 A safer form of vsnprintf, with some differences from standard vsnprintf behavior. More...
 
template<size_t N>
errno_t nlib_vsnprintf (size_t *count, char(&buf)[N], const char *fmt, va_list args) noexcept
 The function template version of nlib_vsnprintf.
 
errno_t nlib_snprintf (size_t *count, char *buf, size_t size, const char *fmt,...)
 A safer form of snprintf.
 
template<size_t N>
errno_t nlib_snprintf (size_t *count, char(&buf)[N], const char *fmt,...) noexcept
 The function template version of nlib_snprintf.
 
errno_t nlib_vdprintf (nlib_fd fd, size_t *count, const char *fmt, va_list args)
 The version of the vsnprintf function that outputs to a file descriptor.
 
errno_t nlib_dprintf (nlib_fd fd, size_t *count, const char *fmt,...)
 The version of the snprintf function that outputs to a file descriptor.
 
int nlib_printf (const char *fmt,...)
 The substitute for the printf function.
 
errno_t nlib_vsnwprintf (size_t *count, wchar_t *buf, size_t size, const wchar_t *fmt, va_list args)
 A safer form of vswprintf, with some differences from standard vswprintf behavior. More...
 
template<size_t N>
errno_t nlib_vsnwprintf (size_t *count, wchar_t(&buf)[N], const wchar_t *fmt, va_list args) noexcept
 The function template version of nlib_vsnwprintf.
 
errno_t nlib_snwprintf (size_t *count, wchar_t *buf, size_t size, const wchar_t *fmt,...)
 A safer form of snwprintf.
 
template<size_t N>
errno_t nlib_snwprintf (size_t *count, wchar_t(&buf)[N], const wchar_t *fmt,...) noexcept
 The function template version of nlib_snwprintf.
 
errno_t nlib_vdwprintf (nlib_fd fd, size_t *count, const wchar_t *fmt, va_list args)
 The version of the vsnwprintf function that outputs to a file descriptor.
 
errno_t nlib_dwprintf (nlib_fd fd, size_t *count, const wchar_t *fmt,...)
 The version of the snwprintf function that outputs to a file descriptor.
 
int nlib_wprintf (const wchar_t *fmt,...)
 The substitute for the wprintf function.
 

Copying, comparing, and exploring a memory region.

static errno_t nlib_memcpy (void *s1, size_t s1max, const void *s2, size_t n)
 An implementation corresponding to N1078 memcpy_s. More...
 
static errno_t nlib_memmove (void *s1, size_t s1max, const void *s2, size_t n)
 An implementation corresponding to N1078 memmove_s. More...
 
static errno_t nlib_memset (void *buf, int ch, size_t n)
 Makes a function call corresponding to memset(buf, ch, n). More...
 
void * nlib_memccpy (void *dest, size_t dest_size, const void *src, size_t src_size, int c)
 Continues copying until c is found. Stops copying when it is found. More...
 
int nlib_memcmp (const void *buf1, const void *buf2, size_t n)
 Compares the n bytes from the starts of buf1 and buf2 as unsigned char data. More...
 
const void * nlib_memchr (const void *s, int c, size_t n)
 Searches the n bytes from the start of the memory region (s, s + n) and returns a pointer to byte c. More...
 
const void * nlib_memrchr (const void *s, int c, size_t n)
 Searches the n bytes from the end of memory region (s, s + n) and returns a pointer to byte c. More...
 
const void * nlib_memchr_not (const void *s, int c, size_t n)
 Searches the n bytes from the start of memory region(s, s + n) and returns a pointer that does not point to byte c. More...
 
const void * nlib_memchr_range_not (const void *s, const char *range, size_t n)
 Searches the n bytes from the start of memory region (s, s + n) and returns a pointer to a character not contained in range. More...
 
const void * nlib_memchr_lt (const void *s, int c, size_t n)
 Searches the n bytes from the start of memory region (s, s + n) and returns a pointer to data having a character less than byte c. More...
 
const void * nlib_memchr_gt (const void *s, int c, size_t n)
 Searches the n bytes from the start of memory region (s, s + n) and returns a pointer to data having a character larger than byte c. More...
 
const void * nlib_memchr_mb (const void *s, size_t n)
 Searches the n bytes from the start of memory region (s, s + n) and returns a pointer to the location where 0x80 or more bytes is stored. More...
 
size_t nlib_memspn (const void *buf, size_t len, const char *set, size_t n)
 Returns the length of the set of sub-bytes from the beginning of buf. The set of sub-bytes consists of only bytes contained in set. More...
 
size_t nlib_memcspn (const void *buf, size_t len, const char *set, size_t n)
 Returns the length of the set of sub-bytes from the beginning of buf. The set of sub-bytes consists of bytes other than those contained in set. More...
 

Function for null terminated strings.

const char * nlib_skipws (size_t *cnt_lf, const char **last_lf, const char *s, size_t n)
 Searches a string made up of n characters and returns the pointer to the first character found that is not a white-space character. More...
 
size_t nlib_strlen (const char *s)
 Internally calls strlen(). In some cases, it may operate as an independent implementation. More...
 
size_t nlib_strnlen (const char *s, size_t maxsize)
 An implementation corresponding to N1078 strnlen_s. More...
 
errno_t nlib_strcpy (char *s1, size_t s1max, const char *s2)
 An implementation corresponding to N1078 strcpy_s. More...
 
template<size_t N>
errno_t nlib_strcpy (char(&s1)[N], const char *s2) noexcept
 The function template version of nlib_strcpy.
 
template<size_t N>
size_t nlib_strlcpy (char(&s1)[N], const char *s2) noexcept
 Calls the nlib_strlcpy(s1, s2, N) function.
 
errno_t nlib_strncpy (char *s1, size_t s1max, const char *s2, size_t n)
 An implementation corresponding to N1078 strncpy_s. More...
 
template<size_t N>
errno_t nlib_strncpy (char(&s1)[N], const char *s2, size_t n) noexcept
 The function template version of nlib_strncpy.
 
const char * nlib_strchr (const char *s, int c)
 Searches for a character from the start of a string. More...
 
const char * nlib_strrchr (const char *s, int c)
 Searches for a character from the end of a string. More...
 
size_t nlib_wcslen (const wchar_t *s)
 Makes a call to thewcslen function. In some cases, it may operate as an independent implementation. More...
 
size_t nlib_wcsnlen (const wchar_t *s, size_t maxsize)
 An implementation corresponding to N1078 wcsnlen_s. More...
 
errno_t nlib_wcscpy (wchar_t *s1, size_t s1max, const wchar_t *s2)
 An implementation corresponding to N1078 wcscpy_s. More...
 
template<size_t N>
errno_t nlib_wcscpy (wchar_t(&s1)[N], const wchar_t *s2) noexcept
 The function template version of nlib_wcscpy.
 
errno_t nlib_wcsncpy (wchar_t *s1, size_t s1max, const wchar_t *s2, size_t n)
 An implementation corresponding to N1078 wcsncpy_s. More...
 
template<size_t N>
errno_t nlib_wcsncpy (wchar_t(&s1)[N], const wchar_t *s2, size_t n) noexcept
 The function template version of nlib_wcsncpy.
 

Substitute for <tt>strtol()</tt>.

Substitutes for strtol(). For more information, see the item describing nlib_strto_int32().

errno_t nlib_strto_int32 (int32_t *result, const char *nptr, char **endptr, int base)
 Converts a string to the int32_t type. More...
 
errno_t nlib_strto_int64 (int64_t *result, const char *nptr, char **endptr, int base)
 Converts a string to the int64_t type. For details, see nlib_strto_int32().
 
errno_t nlib_strto_uint32 (uint32_t *result, const char *nptr, char **endptr, int base)
 Converts a string to the uint32_t type. For details, see nlib_strto_int32().
 
errno_t nlib_strto_uint64 (uint64_t *result, const char *nptr, char **endptr, int base)
 Converts a string to the uint64_t type. For details, see nlib_strto_int32().
 
errno_t nlib_strto_double (double *result, const char *nptr, char **endptr)
 Converts a string to the double type. For details, see nlib_strto_int32().
 
errno_t nlib_strto_float (float *result, const char *nptr, char **endptr)
 Converts a string to the float type. For details, see nlib_strto_int32().
 
errno_t nlib_strto_int32_fallback (int32_t *result, const char *nptr, char **endptr, int base)
 Converts a string to the int32_t type without using a standard C function. For details, see nlib_strto_int32().
 
errno_t nlib_strto_int64_fallback (int64_t *result, const char *nptr, char **endptr, int base)
 Converts a string to the int64_t type without using a standard C function. For details, see nlib_strto_int32().
 
errno_t nlib_strto_uint32_fallback (uint32_t *result, const char *nptr, char **endptr, int base)
 Converts a string to the uint32_t type without using a standard C function. For details, see nlib_strto_int32().
 
errno_t nlib_strto_uint64_fallback (uint64_t *result, const char *nptr, char **endptr, int base)
 Converts a string to the uint64_t type without using a standard C function. For details, see nlib_strto_int32().
 
errno_t nlib_strto_double_fallback (double *result, const char *nptr, char **endptr)
 Converts a string to the double type without using a standard C function. For details, see nlib_strto_int32().
 
errno_t nlib_strto_float_fallback (float *result, const char *nptr, char **endptr)
 Converts a string to the float type without using a standard C function. For details, see nlib_strto_int32().
 

The second substitute strtol().

Implementation using from_chars() incorporated in C++17. If from_chars() is not available in the standard C++ library, the substitute implementation is used. For more information, refer to the description for nlib_int32_from_chars().

errno_t nlib_int32_from_chars (int32_t *result, const char **endptr, const char *first, const char *last, int base)
 Converts a string to the int32_t type. More...
 
errno_t nlib_int64_from_chars (int64_t *result, const char **endptr, const char *first, const char *last, int base)
 Converts a string to the int64_t type. For more information, refer to the description for nlib_int32_from_chars().
 
errno_t nlib_int8_from_chars (int8_t *result, const char **endptr, const char *first, const char *last, int base)
 Converts a string to the int8_t type. For more information, refer to the description for nlib_int32_from_chars().
 
errno_t nlib_int16_from_chars (int16_t *result, const char **endptr, const char *first, const char *last, int base)
 Converts a string to the int16_t type. For more information, refer to the description for nlib_int32_from_chars().
 
errno_t nlib_uint8_from_chars (uint8_t *result, const char **endptr, const char *first, const char *last, int base)
 Converts a string to the uint8_t type. For more information, refer to the description for nlib_int32_from_chars().
 
errno_t nlib_uint16_from_chars (uint16_t *result, const char **endptr, const char *first, const char *last, int base)
 Converts a string to the uint16_t type. For more information, refer to the description for nlib_int32_from_chars().
 
errno_t nlib_uint32_from_chars (uint32_t *result, const char **endptr, const char *first, const char *last, int base)
 Converts a string to the uint32_t type. For more information, refer to the description for nlib_int32_from_chars().
 
errno_t nlib_uint64_from_chars (uint64_t *result, const char **endptr, const char *first, const char *last, int base)
 Converts a string to the uint64_t type. For more information, refer to the description for nlib_int32_from_chars().
 
errno_t nlib_double_from_chars (double *result, const char **endptr, const char *first, const char *last)
 Converts a string to the double type. More...
 
errno_t nlib_float_from_chars (float *result, const char **endptr, const char *first, const char *last)
 Converts a string to the float type. For more information, refer to the description for nlib_double_from_chars().
 

Substitute for <tt>ctype.h<tt>.

A substitute for functions declared in ctype.h, a standard header for C. It isn't affected by the locale.

static int nlib_isalnum (int ch)
 If ch is an ASCII character '0'-'9', 'A'-'Z', or 'a'-'z', the function returns non-zero. Otherwise, the function returns 0.
 
static int nlib_isalpha (int ch)
 If ch is an ASCII character 'A'-'Z' or 'a'-'z', the function returns non-zero. Othewise, the function returns 0.
 
static int nlib_isblank (int ch)
 If ch is an ASCII character ' ' or '\t', the function returns non-zero. Otherwise, the function returns 0.
 
static int nlib_iscntrl (int ch)
 If ch is an ASCII code '0'-'31' or '127', the function returns non-zero. Otherwise, the function returns 0.
 
static int nlib_isdigit (int ch)
 If ch is an ASCII character '0'-'9', the function returns non-zero. Otherwise, the function returns 0.
 
static int nlib_isgraph (int ch)
 If ch is an ASCII character '33'-'126', the function returns non-zero. Otherwise, the function returns 0.
 
static int nlib_islower (int ch)
 If ch is an ASCII character 'a'-'z', the function returns non-zero. Otherwise, the function returns 0.
 
static int nlib_isprint (int ch)
 If ch is an ASCII character '32'-'126', the function returns non-zero. Otherwise, the function returns 0.
 
static int nlib_ispunct (int ch)
 If ch is an ASCII character '0'-'32' or '127', the function returns non-zero. Otherwise, the function returns 0.
 
static int nlib_isspace (int ch)
 If ch is an ASCII character ' ', '\t', or '\n', the function returns non-zero. Otherwise, the function returns 0.
 
static int nlib_isupper (int ch)
 If ch is an ASCII character 'A'-'Z', the function returns non-zero. Otherwise, the function returns 0.
 
static int nlib_isxdigit (int ch)
 If ch is an ASCII character '0'-'9', 'A'-'F', or 'a'-'f', the function returns non-zero. Otherwise, the function returns 0.
 
static int nlib_tolower (int ch)
 If ch is an ASCII character 'A'-'Z', the function returns its lowercase letter. Otherwise, the function returns ch.
 
static int nlib_toupper (int ch)
 If ch is an ASCII character 'a'-'z', the function returns its uppercase letter. Otherwise, the function returns ch.
 

Unicode

Unicode-related functionality is also implemented in the nn::nlib::unicode namespace.

int nlib_utf16_to_utf32char (nlib_utf32_t *utf32, nlib_utf16_t upper, nlib_utf16_t lower)
 Converts a single code point from UTF-16 into UTF-32. More...
 
int nlib_utf32char_to_utf16 (nlib_utf16_t *upper, nlib_utf16_t *lower, nlib_utf32_t utf32)
 Converts a single UTF-32 character into UTF-16. More...
 
int nlib_utf8_to_utf32char (nlib_utf32_t *utf32, const nlib_utf8_t *utf8)
 Converts UTF-8 into one character's worth of UTF-32. More...
 
int nlib_utf32char_to_utf8 (nlib_utf8_t(&utf8)[4], nlib_utf32_t utf32)
 Converts the UTF-32 for one character into UTF-8. More...
 
errno_t nlib_wide_to_utf8 (size_t *utf8count, nlib_utf8_t *utf8, size_t buflen, const wchar_t *wcstr)
 Converts a UTF-16/UTF-32 string into a UTF-8 string. More...
 
template<size_t N>
errno_t nlib_wide_to_utf8 (size_t *result, nlib_utf8_t(&utf8)[N], const wchar_t *wcstr) noexcept
 The function template version of nlib_wide_to_utf8.
 
errno_t nlib_utf8_to_wide (size_t *wccount, wchar_t *wcstr, size_t buflen, const nlib_utf8_t *utf8)
 Converts a UTF-8 string into a UTF-16/UTF-32 string. More...
 
template<size_t N>
errno_t nlib_utf8_to_wide (size_t *result, wchar_t(&wcstr)[N], const nlib_utf8_t *utf8) noexcept
 The function template version of nlib_utf8_to_wide.
 
errno_t nlib_utf16_to_utf8 (size_t *utf8count, nlib_utf8_t *utf8, size_t buflen, const nlib_utf16_t *utf16)
 Converts a UTF-16 string into a UTF-8 string. More...
 
template<size_t N>
errno_t nlib_utf16_to_utf8 (size_t *utf8count, nlib_utf8_t(&utf8)[N], const nlib_utf16_t *utf16) noexcept
 The function template version of nlib_utf16_to_utf8.
 
errno_t nlib_utf8_to_utf16 (size_t *utf16count, nlib_utf16_t *utf16, size_t buflen, const nlib_utf8_t *utf8)
 Converts a UTF-8 string into a UTF-16 string. The UTF-16 string is null-terminated. More...
 
template<size_t N>
errno_t nlib_utf8_to_utf16 (size_t *utf16count, nlib_utf16_t(&utf16)[N], const nlib_utf8_t *utf8) noexcept
 The function template version of nlib_utf8_to_utf16.
 
errno_t nlib_utf32_to_utf8 (size_t *utf8count, nlib_utf8_t *utf8, size_t buflen, const nlib_utf32_t *utf32)
 Converts a UTF-32 string into a UTF-8 string. More...
 
template<size_t N>
errno_t nlib_utf32_to_utf8 (size_t *utf8count, nlib_utf8_t(&utf8)[N], const nlib_utf32_t *utf32) noexcept
 The function template version of nlib_utf32_to_utf8.
 
errno_t nlib_utf8_to_utf32 (size_t *utf32count, nlib_utf32_t *utf32, size_t buflen, const nlib_utf8_t *utf8)
 Converts a UTF-8 string into a UTF-32 string. More...
 
template<size_t N>
errno_t nlib_utf8_to_utf32 (size_t *utf32count, nlib_utf32_t(&utf32)[N], const nlib_utf8_t *utf8) noexcept
 The function template version of nlib_utf8_to_utf32.
 
errno_t nlib_memutf16_to_utf8 (size_t *to_count, size_t *from_count, nlib_utf8_t *to, size_t to_size, const nlib_utf16_t *from, size_t from_size) NLIB_NONNULL_5
 Converts a UTF-16 string that is not null terminated to a UTF-8 string. More...
 
template<size_t N>
errno_t nlib_memutf16_to_utf8 (size_t *to_count, size_t *from_count, nlib_utf8_t(&to)[N], const nlib_utf16_t *from, size_t from_size) noexcept
 The function template version of nlib_memutf16_to_utf8().
 
errno_t nlib_memutf8_to_utf16 (size_t *to_count, size_t *from_count, nlib_utf16_t *to, size_t to_size, const nlib_utf8_t *from, size_t from_size) NLIB_NONNULL_5
 Converts a UTF-8 string that is not null terminated to a UTF-16 string. More...
 
template<size_t N>
errno_t nlib_memutf8_to_utf16 (size_t *to_count, size_t *from_count, nlib_utf16_t(&to)[N], const nlib_utf8_t *from, size_t from_size) noexcept
 The function template version of nlib_memutf8_to_utf16().
 
errno_t nlib_memutf32_to_utf8 (size_t *to_count, size_t *from_count, nlib_utf8_t *to, size_t to_size, const nlib_utf32_t *from, size_t from_size) NLIB_NONNULL_5
 Converts a UTF-32 string that is not null terminated to a UTF-8 string. More...
 
template<size_t N>
errno_t nlib_memutf32_to_utf8 (size_t *to_count, size_t *from_count, nlib_utf8_t(&to)[N], const nlib_utf32_t *from, size_t from_size) noexcept
 The function template version of nlib_memutf32_to_utf8().
 
errno_t nlib_memutf8_to_utf32 (size_t *to_count, size_t *from_count, nlib_utf32_t *to, size_t to_size, const nlib_utf8_t *from, size_t from_size) NLIB_NONNULL_5
 Converts a UTF-8 string that is not null terminated to a UTF-32 string. More...
 
template<size_t N>
errno_t nlib_memutf8_to_utf32 (size_t *to_count, size_t *from_count, nlib_utf32_t(&to)[N], const nlib_utf8_t *from, size_t from_size) noexcept
 The function template version of nlib_memutf8_to_utf32().
 
errno_t nlib_memwide_to_utf8 (size_t *to_count, size_t *from_count, nlib_utf8_t *to, size_t to_size, const wchar_t *from, size_t from_size) NLIB_NONNULL_5
 Depending on the size of wchar_t, nlib_memutf16_to_utf8() or nlib_memutf32_to_utf8() is called.
 
template<size_t N>
errno_t nlib_memwide_to_utf8 (size_t *to_count, size_t *from_count, nlib_utf8_t(&to)[N], const wchar_t *from, size_t from_size) noexcept
 The function template version of nlib_memwide_to_utf8().
 
errno_t nlib_memutf8_to_wide (size_t *to_count, size_t *from_count, wchar_t *to, size_t to_size, const nlib_utf8_t *from, size_t from_size) NLIB_NONNULL_5
 Depending on the size of wchar_t, nlib_memutf8_to_utf16 or nlib_memutf8_to_utf32 is called.
 
template<size_t N>
errno_t nlib_memutf8_to_wide (size_t *to_count, size_t *from_count, wchar_t(&to)[N], const nlib_utf8_t *from, size_t from_size) noexcept
 The function template version of nlib_memutf8_to_wide().
 
static size_t nlib_utf16len (const nlib_utf16_t *str)
 Counts the number of nlib_utf16_t-type characters, not including the null character. More...
 
static size_t nlib_utf16nlen (const nlib_utf16_t *str, size_t maxsize)
 The UTF-16 version of the nlib_strnlen function. More...
 
static errno_t nlib_utf16cpy (nlib_utf16_t *s1, size_t s1max, const nlib_utf16_t *s2)
 The UTF-16 version of the nlib_strcpy function. More...
 
static errno_t nlib_utf16ncpy (nlib_utf16_t *s1, size_t s1max, const nlib_utf16_t *s2, size_t n)
 The UTF-16 version of the nlib_strcpy function. More...
 
static size_t nlib_utf32len (const nlib_utf32_t *str)
 Counts the number of nlib_utf32_t-type characters, not including the null character. More...
 
static size_t nlib_utf32nlen (const nlib_utf32_t *str, size_t maxsize)
 The UTF-32 version of the nlib_strnlen function. More...
 
static errno_t nlib_utf32cpy (nlib_utf32_t *s1, size_t s1max, const nlib_utf32_t *s2)
 The UTF-32 version of the nlib_strcpy function. More...
 
static errno_t nlib_utf32ncpy (nlib_utf32_t *s1, size_t s1max, const nlib_utf32_t *s2, size_t n)
 The UTF-32 version of the nlib_strcpy function. More...
 
errno_t nlib_strcplen (size_t *codepoint_count, size_t *supplementary_codepoint_count, size_t *len, const nlib_utf8_t *str)
 Gets the number of code points contained in the string, the number of supplementary characters contained in the string, and the string length. If the function returns EILSEQ, a value, including the number of code points to the point that cannot be converted, is stored. More...
 
errno_t nlib_wcscplen (size_t *count, const wchar_t *str)
 Gets the number of code points in the string. More...
 
static errno_t nlib_utf16cplen (size_t *count, const nlib_utf16_t *str)
 Gets the number of code points in the string. More...
 
static errno_t nlib_utf16cplen_ex (size_t *count, size_t *len, const nlib_utf16_t *str)
 Gets the number of code points in the string. More...
 
errno_t nlib_utf32cplen (size_t *count, const nlib_utf32_t *str)
 Gets the number of code points in the string. More...
 
errno_t nlib_memcplen (size_t *codepoint_count, size_t *supplementary_codepoint_count, size_t *from_read, const nlib_utf8_t *from, size_t from_size)
 Gets the number of code points contained in the string and the number of supplementary characters contained in the string.. More...
 
static uint16_t nlib_bswap16 (uint16_t x)
 Returns __builtin_bswap16(x) or _byteswap_ushort(x).
 
static uint32_t nlib_bswap32 (uint32_t x)
 Returns __builtin_bswap32(x) or _byteswap_ulong(x).
 
static uint64_t nlib_bswap64 (uint64_t x)
 Returns __builtin_bswap64(x) or _byteswap_uint64(x).
 
errno_t nlib_swapendian_16 (uint16_t *p, size_t count)
 Swaps the endianness. More...
 
errno_t nlib_swapendian_32 (uint32_t *p, size_t count)
 Swaps the endianness. More...
 
errno_t nlib_swapendian_64 (uint64_t *p, size_t count)
 Swaps the endianness. More...
 
typedef char nlib_utf8_t
 Defines char with a typedef. Indicates that it is a UTF-8 string.
 
typedef uint16_t nlib_utf16_t
 Uses typedef to define as char16_t if that can be used. If not, it uses typedef to define as uint16_t.
 
typedef uint32_t nlib_utf32_t
 Uses typedef to define as char32_t if that can be used. If not, it uses typedef to define as uint32_t.
 

count leading zeros, count trailing zeros, popcnt, bitreverse

static int nlib_clz32 (uint32_t x)
 Returns the number of consecutive zero bits, with respect to the most significant bit (MSB). More...
 
static int nlib_clz64 (uint64_t x)
 Returns the number of consecutive zero bits, with respect to the most significant bit (MSB). More...
 
static int nlib_ctz32 (uint32_t x)
 Returns the number of consecutive zero bits, with respect to the least significant bit (LSB). More...
 
static int nlib_ctz64 (uint64_t x)
 Returns the number of consecutive zero bits, with respect to the least significant bit (LSB). More...
 
static int nlib_popcnt32 (uint32_t x)
 Returns the number of bits that are 1. More...
 
static int nlib_popcnt64 (uint64_t x)
 Returns the number of bits that are 1. More...
 
static int nlib_popcnt16 (uint16_t x)
 Returns the number of bits that are 1. More...
 
static uint32_t nlib_bitreverse32 (uint32_t x)
 Reverses the bit order within an entire 32-bit integer. More...
 
static uint64_t nlib_bitreverse64 (uint64_t x)
 Reverses the bit order within an entire 64-bit integer. More...
 

malloc

void * nlib_malloc (size_t size)
 A weak function that calls the C standard function malloc. nlib calls malloc via this function. More...
 
void nlib_free (void *ptr)
 A weak function that calls the C standard function free. nlib calls free via this function. More...
 
size_t nlib_malloc_size (const void *ptr)
 Returns the allocated memory size. More...
 
void nlib_free_size (void *ptr, size_t size)
 Frees memory of a specified size. The default action is to call the nlib_free function. More...
 
void * nlib_calloc (size_t nmemb, size_t size)
 A weak function that calls the C standard function calloc. nlib calls calloc via this function. More...
 
void * nlib_realloc (void *ptr, size_t size)
 A weak function that calls the C standard function realloc. nlib calls realloc via this function. More...
 
void * nlib_memalign (size_t alignment, size_t size)
 A weak function that calls the C standard function memalign. nlib calls memalign via this function. More...
 

Detailed Description

The most basic nlib API that has C linkage.

Description
The purpose is to assimilate the differences between platforms and enable programming using the same interface.

Macro Definition Documentation

◆ NLIB_ALWAYS_INLINE

NLIB_ALWAYS_INLINE   inline __attribute__((always_inline))

Indicates that the compiler is forced to perform inline expansion of functions.

Description
Platform Definition
Win32 __forceinline
Linux inline __attribute__((always_inline))
FreeBSD inline __attribute__((always_inline))
OS X inline __attribute__((always_inline))
CAFE inline __attribute__((always_inline))
CTR __forceinline

Definition at line 97 of file Platform_unix.h.

◆ NLIB_ASSUME

NLIB_ASSUME (   cond)    switch (0) case 0: default: if (cond) ; else __builtin_unreachable() /* NOLINT */

Indicates that cond is true and provides tips for optimizing the compiler.

Parameters
[in]condAn expression assumed to be true.
Description
In some cases, code like the following can optimize switch statements.
switch (x) {
case 0:
....
break;
case 1:
....
break;
case 2:
....
break;
default :
}

Definition at line 264 of file Platform.h.

◆ NLIB_ATTRIBUTE_CONST

NLIB_ATTRIBUTE_CONST   __attribute__((const))

Defines __attribute__((const)) if it is available for use.

Description
Platform Definition
Win32 Empty string.
Linux __attribute__((const))
FreeBSD __attribute__((const))
OS X __attribute__((const))
CAFE __attribute__((const))
CTR __attribute__((const))

Definition at line 126 of file Platform_unix.h.

◆ NLIB_ATTRIBUTE_MALLOC

NLIB_ATTRIBUTE_MALLOC   __attribute__((malloc))

Defines __attribute__((malloc)) if it is available for use.

Description
Platform Definition
Win32 Empty string.
Linux __attribute__((malloc))
FreeBSD __attribute__((malloc))
OS X __attribute__((malloc))
CAFE __attribute__((malloc))
CTR __attribute__((malloc))

Definition at line 124 of file Platform_unix.h.

◆ NLIB_ATTRIBUTE_PURE

NLIB_ATTRIBUTE_PURE   __attribute__((pure))

Defines __attribute__((pure)) if it is available for use.

Description
Platform Definition
Win32 Empty string.
Linux __attribute__((pure))
FreeBSD __attribute__((pure))
OS X __attribute__((pure))
CAFE __attribute__((pure))
CTR __attribute__((pure))

Definition at line 125 of file Platform_unix.h.

◆ NLIB_CHECK_RESULT

NLIB_CHECK_RESULT   __attribute__((warn_unused_result))

Indicates that the caller of the function must check the returned value.

Description
Platform Definition
Win32 _Check_return_
Linux __attribute__((warn_unused_result))
FreeBSD __attribute__((warn_unused_result))
OS X __attribute__((warn_unused_result))
CAFE __attribute__((warn_unused_result))
CTR Empty string.

Definition at line 105 of file Platform_unix.h.

◆ nlib_compiler_version

nlib_compiler_version   NLIB_CAPI(nlib_compiler_version)

Dynamically obtains the compiler version used to compile nlib.

Returns
An integer value indicating the compiler version.
Description
Compiler implementation
MSVC _MSC_FULL_VER
clang __clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__
gcc __GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__
armcc __ARMCC_VERSION
ghs __GHS_VERSION_NUMBER

Definition at line 35 of file Platform_rename.h.

◆ nlib_debug_break

nlib_debug_break   NLIB_CAPI(nlib_debug_break)

A breakpoint.

Description
Platform Implementation
Win32 DebugBreak()
Linux __builtin_trap()
FreeBSD __builtin_trap()
OS X __builtin_trap()
CAFE OSDebug()
CTR nn::dbg::Break()

Definition at line 142 of file Platform_rename.h.

◆ NLIB_DEPRECATED

NLIB_DEPRECATED   [[deprecated]]

Indicates that a function or something has been deprecated.

Description
Platform Definition
Win32 __declspec(deprecated)
Linux __attribute__((deprecated))
FreeBSD __attribute__((deprecated))
OS X __attribute__((deprecated))
CAFE __attribute__((deprecated))
CTR Empty string (because prefix format is not possible).

Definition at line 109 of file Config.h.

◆ nlib_get_native_last_error

nlib_get_native_last_error   NLIB_CAPI(nlib_get_native_last_error)

Returns the last generated native error code.

Returns
The native error code for the last generated error.
Description
Platform Implementation
Win32 GetLastError()
Linux Always return 0.
FreeBSD Always return 0.
OS X Always return 0.
CAFE The error value generated by the call to an SDK function inside the nlib_xxxx function.
CTR The return value of the GetPrintableBits member function for the error generated by the call to an SDK function inside the nlib_xxxx function.

Definition at line 33 of file Platform_rename.h.

◆ nlib_getversion

nlib_getversion   NLIB_CAPI(nlib_getversion)

Dynamically gets the nlib version.

Returns
Returns NLIB_VERSION.
Description
Depending on which version of nlib you are using, you may need to change the behavior of the user code at run time.

Definition at line 34 of file Platform_rename.h.

◆ NLIB_LIKELY

NLIB_LIKELY (   x)    __builtin_expect(!!(x), 1)

Indicates to the compiler that condition x is likely to be true.

Parameters
[in]xA conditional expression.
Description
Platform Definition
Win32 (x)
Linux __builtin_expect(!!(x), 1)
FreeBSD __builtin_expect(!!(x), 1)
OS X __builtin_expect(!!(x), 1)
CAFE __builtin_expect(!!(x), 1)
CTR __builtin_expect(!!(x), 1)

Definition at line 99 of file Platform_unix.h.

◆ NLIB_NEVER_INLINE

NLIB_NEVER_INLINE   __attribute__((__noinline__))

Indicates that the compiler does not perform inline expansion of functions.

Description
Platform Definition
Win32 __declspec(noinline)
Linux __attribute__((__noinline__))
FreeBSD __attribute__((__noinline__))
OS X __attribute__((__noinline__))
CAFE __attribute__((__noinline__))
CTR __declspec(noinline)

Definition at line 98 of file Platform_unix.h.

◆ NLIB_NONNULL

NLIB_NONNULL   __attribute__((nonnull))

Indicates that you cannot specify NULL for all arguments.

Description
If NULL is passed, a warning is output at compile time.
Platform Definition
Win32 Empty string.
Linux __attribute__((nonnull))
FreeBSD __attribute__((nonnull))
OS X __attribute__((nonnull))
CAFE __attribute__((nonnull))
CTR __attribute__((nonnull))

Definition at line 117 of file Platform_unix.h.

◆ NLIB_NONNULL_1

NLIB_NONNULL_1   __attribute__((nonnull (1)))

Indicates that you cannot specify NULL for the first argument.

Description
If NULL is passed, a warning is output at compile time.
Platform Definition
Win32 Empty string.
Linux __attribute__((nonnull (1)))
FreeBSD __attribute__((nonnull (1)))
OS X __attribute__((nonnull (1)))
CAFE __attribute__((nonnull (1)))
CTR __attribute__((nonnull (1)))

Definition at line 118 of file Platform_unix.h.

◆ NLIB_NONNULL_2

NLIB_NONNULL_2   __attribute__((nonnull (2)))

Indicates that you cannot specify NULL for the second argument.

Description
If NULL is passed, a warning is output at compile time.
Platform Definition
Win32 Empty string.
Linux __attribute__((nonnull (2)))
FreeBSD __attribute__((nonnull (2)))
OS X __attribute__((nonnull (2)))
CAFE __attribute__((nonnull (2)))
CTR __attribute__((nonnull (2)))

Definition at line 119 of file Platform_unix.h.

◆ NLIB_NONNULL_3

NLIB_NONNULL_3   __attribute__((nonnull (3)))

Indicates that you cannot specify NULL for the third argument.

Description
If NULL is passed, a warning is output at compile time.
Platform Definition
Win32 Empty string.
Linux __attribute__((nonnull (3)))
FreeBSD __attribute__((nonnull (3)))
OS X __attribute__((nonnull (3)))
CAFE __attribute__((nonnull (3)))
CTR __attribute__((nonnull (3)))

Definition at line 120 of file Platform_unix.h.

◆ NLIB_NONNULL_4

NLIB_NONNULL_4   __attribute__((nonnull (4)))

Indicates that you cannot specify NULL for the fourth argument.

Description
If NULL is passed, a warning is output at compile time.
Platform Definition
Win32 Empty string.
Linux __attribute__((nonnull (4)))
FreeBSD __attribute__((nonnull (4)))
OS X __attribute__((nonnull (4)))
CAFE __attribute__((nonnull (4)))
CTR __attribute__((nonnull (4)))

Definition at line 121 of file Platform_unix.h.

◆ NLIB_NONNULL_5

NLIB_NONNULL_5   __attribute__((nonnull (5)))

Indicates that you cannot specify NULL for the fifth argument.

Description
If NULL is passed, a warning is output at compile time.
Platform Definition
Win32 Empty string.
Linux __attribute__((nonnull (5)))
FreeBSD __attribute__((nonnull (5)))
OS X __attribute__((nonnull (5)))
CAFE __attribute__((nonnull (5)))
CTR __attribute__((nonnull (5)))

Definition at line 122 of file Platform_unix.h.

◆ NLIB_NORETURN

NLIB_NORETURN   __attribute__((noreturn))

Indicates that the process will not return from functions.

Description
Platform Definition
Win32 Empty string.
Linux __attribute__((noreturn))
FreeBSD __attribute__((noreturn))
OS X __attribute__((noreturn))
CAFE __attribute__((noreturn))
CTR __attribute__((noreturn))

Definition at line 110 of file Platform_unix.h.

◆ nlib_thread_exit

nlib_thread_exit   NLIB_CAPI(nlib_thread_exit)

Ends the called thread.

Description
A call of the destructor for C++ automatic objects is not guaranteed (it depends on the platform). For this reason, objects built on the heap must be destroyed explicitly by using nlib_thread_cleanup_push() and nlib_thread_cleanup_pop().
Platform Implementation
Win32 _endthreadex(0)
Linux pthread_exit(0)
FreeBSD pthread_exit(0)
OS X pthread_exit(0)
CAFE OSExitThread(0)
CTR No implementation found (compiler error).
Bug:
For Linux and FreeBSD, a destructor for C++ automatic variables is run. For other cases, it will not be run.

Definition at line 136 of file Platform_rename.h.

◆ nlib_thread_exit_cpp

nlib_thread_exit_cpp   NLIB_CAPI(nlib_thread_exit_cpp)

Ends the called thread.

Description
An implementation-dependent C++ exception is thrown internally, and as a result, a destructor for C++ objects is run. Accordingly, this function will not operate properly if an exception is caught by catch (...). In addition, all functions in the caller of this function must not be set to no exceptions (such as noexcept). Note that behavior is undefined (depending on the platform) when nlib_thread_cleanup_push() and nlib_thread_cleanup_pop() are used.
Platform Implementation
Win32 Throws nlib_unwind_exception.
Linux Throws abi::__forced_unwind inside pthread_exit(0).
FreeBSD Throws _Unwind_Exception inside pthread_exit(0).
OS X Throws nlib_unwind_exception.
CAFE No implementation found (compiler error).
CTR No implementation found (compiler error).
Bug:
A destructor registered with nlib_thread_cleanup_push() is run for Linux and FreeBSD. In addition, for FreeBSD, a thrown (special) C++ exception cannot be caught.

Definition at line 137 of file Platform_rename.h.

◆ NLIB_UNLIKELY

NLIB_UNLIKELY (   x)    __builtin_expect(!!(x), 0)

Indicates to the compiler that condition x is likely to be false.

Parameters
[in]xA conditional expression.
Description
Platform Definition
Win32 (x)
Linux __builtin_expect(!!(x), 0)
FreeBSD __builtin_expect(!!(x), 0)
OS X __builtin_expect(!!(x), 0)
CAFE __builtin_expect(!!(x), 0)
CTR __builtin_expect(!!(x), 0)

Definition at line 100 of file Platform_unix.h.

◆ NLIB_VIS_HIDDEN

NLIB_VIS_HIDDEN   __attribute__((visibility("hidden")))

Symbols for functions and classes are not made available outside of the library.

Description
When using shared libraries, the load time gets longer when there are more public symbols. Also, the size of the library increases in step with the size of the symbol table. This phenomenon is most noticeable when using the template library.
Generally, public symbols can be checked as shown below.
nm -C -D lib***.so
You can use NLIB_VIS_HIDDEN to set symbols so they are not made available outside the library. You can also make symbols private by default by passing the -fvisibility=hidden option to the compiler.
Platform Definition
Win32 Empty string.
Linux __attribute__((visibility("hidden"))), or an empty string in the Cygwin environment.
FreeBSD __attribute__((visibility("hidden")))
OS X __attribute__((visibility("hidden")))
CAFE Empty string.
CTR Empty string.
See also
https://gcc.gnu.org/wiki/Visibility

Definition at line 88 of file Platform_unix.h.

◆ NLIB_VIS_PUBLIC

NLIB_VIS_PUBLIC   __attribute__((visibility("default")))

Symbols for functions and classes are made available outside of the library.

Description
You can pass -fvisibility=hidden to the compiler to explicitly make the symbols public. You must use this macro in such cases.
Platform Definition
Win32 __declspec(dllimport) when using the DLL version, or an empty string otherwise.
Linux __attribute__((visibility("default"))), or an empty string in the Cygwin environment.
FreeBSD __attribute__((visibility("default")))
OS X __attribute__((visibility("default")))
CAFE Empty string.
CTR Empty string.
See also
NLIB_VIS_HIDDEN

Definition at line 89 of file Platform_unix.h.

◆ NLIB_WARN

NLIB_WARN (   exp)    ("WARNING: " exp)

Outputs a warning.

Parameters
[in]expA warning message.
Description
Denote and use like the #pragma message NLIB_WARN("message").

Definition at line 229 of file Platform.h.

◆ NLIB_WEAKSYMBOL

NLIB_WEAKSYMBOL   __attribute__((weak))

Used for defining weak symbols.

Description
Platform Definition
Win32 Empty string.
Linux __attribute__((weak)), or an empty string in the cygwin environment.
FreeBSD __attribute__((weak))
OS X __attribute__((weak))
CAFE __attribute__((weak))
CTR __attribute__((weak))

Definition at line 90 of file Platform_unix.h.

◆ nlib_yield

nlib_yield   NLIB_CAPI(nlib_yield)

Relinquishes thread execution rights.

Returns
Returns 0 on success.
Description
Platform Implementation
Win32 Sleep(0)
Linux sched_yield()
FreeBSD sched_yield()
OS X sched_yield()
CAFE OSYieldThread()
CTR nn::os::Thread::Yield()
Examples:
misc/threading/simpleringbuffer/simpleringbuffer.cpp, msgpack/jsonrpc/jsonrpc.cpp, and msgpack/jsonrpc/server.cpp.

Definition at line 111 of file Platform_rename.h.

◆ RSIZE_MAX

RSIZE_MAX   0x7FFFFFFFFFFFFFFFLL

Defines a value somewhat smaller than the maximum value of size_t.

Description
A macro used to avoid unexpected overflow by checking the argument values of size_t.
See also
https://www.securecoding.cert.org/confluence/display/c/INT01-C.+Use+rsize_t+or+size_t+for+all+integer+values+representing+the+size+of+an+object
https://www.jpcert.or.jp/sc-rules/c-int01-c.html (in Japanese)

Definition at line 224 of file Platform.h.

Typedef Documentation

◆ nlib_barrier

The type for a barrier object.

Description
Platform Implementation
Win32 Implemented by nlib, SYNCHRONIZATION_BARRIER
Linux pthread_barrier_t
FreeBSD pthread_barrier_t
OS X Implemented by nlib.
CAFE Implemented by nlib.
CTR Implemented by nlib.

Definition at line 1091 of file Platform.h.

◆ nlib_cond

The type for a condition variable object.

Description
Platform Implementation
Win32 CONDITION_VARIABLE
Linux pthread_cond_t
FreeBSD pthread_cond_t
OS X pthread_cond_t
CAFE OSFastCond
CTR nn::os::Event

Definition at line 253 of file Platform_unix.h.

◆ nlib_condrwlock

Type of the conditional variable for read-write locks.

Description
This variable is defined as a structure containing nlib_cond and nlib_mutex. However, the Windows conditional variable (CONDITION_VARIABLE) only has its conditional variable since it can have read-write locks directly.

◆ nlib_fd

The original file descriptor of nlib (a 32-bit integer value).

Description
Platform Implementation
Win32 Implemented by nlib.
Linux In accordance with the native file descriptor.
FreeBSD In accordance with the native file descriptor.
OS X In accordance with the native file descriptor.
CAFE Implemented by nlib.
CTR Implemented by nlib.

Definition at line 1536 of file Platform.h.

◆ nlib_mutex

The type for mutex variables.

Description
Platform Implementation
Win32 HANDLE or CRITICAL_SECTION
Linux pthread_mutex_t
FreeBSD pthread_mutex_t
OS X pthread_mutex_t
CAFE OSFastMutex
CTR nn::os::CriticalSection

Definition at line 202 of file Platform_unix.h.

◆ nlib_rwlock

The type for a read-write lock object.

Description
Platform Implementation
Win32 SRWLOCK
Linux pthread_rwlock_t
FreeBSD pthread_rwlock_t
OS X pthread_rwlock_t
CAFE Implemented by nlib.
CTR Implemented by nlib.
Sample code
nlib_rwlock rwlock;
MyVector vec;
.....
// Init nlib_rwlock
e = nlib_rwlock_init(&rwlock);
if (nlib_is_error(e)) {
// ERROR
}
.....
{
// Reads vector:nlib_rwlock_rdlock() does not block the other ones.
....
// retrieve vec[i] for example
....
}
....
{
// Writes vector:nlib_rwlock_wrlock() blocks both nlib_rwlock_wrlock() and nlib_rwlock_rdlock()
....
// vec.push_back() for example
....
}

Definition at line 875 of file Platform.h.

◆ nlib_semaphore

The type for a semaphore object.

Description
Platform Implementation
Win32 HANDLE
Linux sem_t
FreeBSD sem_t
OS X int (Make sure that it is not sem_t.)
CAFE OSSemaphore
CTR nn::os::Semaphore

Definition at line 250 of file Platform_unix.h.

◆ nlib_spinlock

Spinlock variable type. Used by statically initializing with NLIB_SPINLOCK_INITIALIZER.

Description
Platform Implementation
Win32 int32_t
Linux int32_t
FreeBSD int32_t
OS X OSSpinLock
CAFE OSSpinLock
CTR int32_t

Definition at line 1224 of file Platform.h.

◆ nlib_thread

The identifier for threads.

Description
Platform Implementation
Win32 HANDLE
Linux pthread_t
FreeBSD pthread_t
OS X pthread_t
CAFE OSThread*
CTR nn::os::Thread

Definition at line 262 of file Platform_unix.h.

◆ nlib_thread_func

void(* nlib_thread_func)(void *arg)

A function to be run on a different thread.

Parameters
[in]argThe argument passed to the thread.

Definition at line 1245 of file Platform.h.

◆ nlib_tls_destructor

void(* nlib_tls_destructor)(void *tls_value)

The type for the TLS destructor function called when the thread is ended.

Parameters
[in]tls_valueThe value stored in the TLS slot.
Description
Note
If you set a value by using nlib_tls_setvalue() in the destructor function, a normal implementation should run a destructor corresponding to the TLS again in order to prevent issues such as memory leaks. Currently, however, no destructor will run again for CTR or cygwin.

Definition at line 562 of file Platform.h.

Enumeration Type Documentation

◆ nlib_log_priority

Defines the priority (level category) for output.

Description
This setting can be used for the prio parameter of the nlib_log_print, nlib_log_vprint, and nlib_log_attr_setint functions.
Enumerator
kNlibLogVerbose 

Specifies the output of verbose messages.

kNlibLogDebug 

Specifies the output of debug-level messages.

kNlibLogInfo 

Specifies the output of information-level messages.

kNlibLogWarn 

Specifies the output of warning-level messages.

kNlibLogError 

Specifies the output of error-level messages.

kNlibLogFatal 

Specifies the output of fatal-level messages.

kNlibLogLevelEqualOrAbove 

Uses a bitwise OR to output levels at and above the specified level. Can be used with the nlib_log_attr_setint function.

kNlibLogLevelEqualOrBelow 

Uses a bitwise OR to output levels at and below the specified level. Can be used with the nlib_log_attr_setint function.

kNlibLogLevelAll 

Specifies all priority levels. Can be used with the nlib_log_attr_setint function.

Definition at line 1411 of file Platform.h.

Function Documentation

◆ nlib_barrier_destroy()

nlib_barrier_destroy ( nlib_barrier barrier)

Destroys a barrier object.

Parameters
[in]barrierA barrier object.
Return values
0Success.
EINVALbarrier is set to NULL.
OtherAn implementation-dependent error.
Description
Platform Implementation
Win32 Implemented by nlib, DeleteSynchronizationBarrier()
Linux pthread_barrier_destroy()
FreeBSD pthread_barrier_destroy()
OS X Implemented by nlib.
CAFE Implemented by nlib.
CTR Implemented by nlib.

◆ nlib_barrier_init()

nlib_barrier_init ( nlib_barrier barrier,
unsigned int  count 
)

Initializes a barrier object.

Parameters
[in,out]barrierA barrier object.
[in]countNumber of threads to wait for.
Return values
0Success.
EINVALbarrier is set to NULL.
OtherAn implementation-dependent error.
Description
Platform Implementation
Win32 Implemented by nlib, InitializeSynchronizationBarrier()
Linux pthread_barrier_init()
FreeBSD pthread_barrier_init()
OS X Implemented by nlib.
CAFE Implemented by nlib.
CTR Implemented by nlib.

◆ nlib_barrier_wait()

nlib_barrier_wait ( nlib_barrier barrier)

Waits for a thread.

Parameters
[in]barrierA barrier object.
Return values
0Success (PTHREAD_BARRIER_SERIAL_THREAD will never be returned)
EINVALbarrier is set to NULL.
OtherAn implementation-dependent error.
Description
Platform Implementation
Win32 Implemented by nlib, EnterSynchronizationBarrier()
Linux pthread_barrier_wait()
FreeBSD pthread_barrier_wait()
OS X Implemented by nlib.
CAFE Implemented by nlib.
CTR Implemented by nlib.

◆ nlib_basename()

nlib_basename ( const char *  path)
Parameters
[in]pathThe path string.
Returns
Returns the file name part from the string.
Description
The following example shows the behavior of this function (The same behavior as that of the GNU version of basename()).
path return value
"" ""
"/" ""
"." "."
".." ".."
"../" ""
"./" ""
"/usr/lib" "lib"
"/usr/" ""
"usr" "usr"
"sdmc:/test.txt" "test.txt"
"C:\\test.txt" "test.txt"(Windows only)

◆ nlib_bitreverse32()

static uint32_t nlib_bitreverse32 ( uint32_t  x)
inlinestatic

Reverses the bit order within an entire 32-bit integer.

Parameters
[in]xA 32-bit integer.
Returns
A value with the x bit order reversed.

Definition at line 2642 of file Platform.h.

◆ nlib_bitreverse64()

static uint64_t nlib_bitreverse64 ( uint64_t  x)
inlinestatic

Reverses the bit order within an entire 64-bit integer.

Parameters
[in]xA 64-bit integer.
Returns
A value with the x bit order reversed.

Definition at line 2665 of file Platform.h.

◆ nlib_calloc()

nlib_calloc ( size_t  nmemb,
size_t  size 
)

A weak function that calls the C standard function calloc. nlib calls calloc via this function.

Parameters
[in]nmembThe number of elements.
[in]sizeThe length of each element, in bytes.
Returns
The pointer to the allocated region.
Description
With the exception of the Cygwin version, this function can be overridden by the user program. Overriding this function is a way to customize nlib memory allocation.
If you are going to override the function, do not forget to code for C linkage using something like the following.
extern "C" void* nlib_calloc(size_t nmemb, size_t size) {
.....
}
Bug:
With the Cygwin version, the user program cannot override the function.
Examples:
heap/replace_malloc/replace_malloc.cpp.

◆ nlib_clz32()

static int nlib_clz32 ( uint32_t  x)
inlinestatic

Returns the number of consecutive zero bits, with respect to the most significant bit (MSB).

Parameters
[in]xThe 32-bit value to operate on.
Returns
Returns an integer between 0 and 32.
Description
Platform Implementation
Win32 _BitScanReverse()
Linux __builtin_clz()
FreeBSD __builtin_clz()
OS X __builtin_clz()
CAFE __CLZ32()
CTR __builtin_clz()
Sample code
nlib_clz32(0x80000000); // returns 0
nlib_clz32(0x00000001); // returns 31

Definition at line 2615 of file Platform.h.

◆ nlib_clz64()

static int nlib_clz64 ( uint64_t  x)
inlinestatic

Returns the number of consecutive zero bits, with respect to the most significant bit (MSB).

Parameters
[in]xThe 64-bit value to operate on.
Returns
Returns an integer between 0 and 64.
Description
Platform Implementation
Win32 _BitScanReverse64() or _BitScanReverse()
Linux __builtin_clzll()
FreeBSD __builtin_clzll()
OS X __builtin_clzll()
CAFE __CLZ32()
CTR __builtin_clzll()
Sample code
nlib_clz64(0x8000000000000000ULL); // returns 0
nlib_clz64(0x0000000000000001ULL); // returns 63

Definition at line 2617 of file Platform.h.

◆ nlib_cond_broadcast()

nlib_cond_broadcast ( nlib_cond cond)

Resumes the execution of all threads that are waiting for the conditional variable cond.

Parameters
[in]condThe condition variable object.
Return values
0Success.
EINVALcond is set to NULL.
Description
Platform Implementation
Win32 WakeAllConditionVariable()
Linux pthread_cond_broadcast()
FreeBSD pthread_cond_broadcast()
OS X pthread_cond_broadcast()
CAFE OSFastCond_Signal()
CTR Event::Signal()

◆ nlib_cond_destroy()

nlib_cond_destroy ( nlib_cond cond)

Destroys a condition variable object.

Parameters
[in]condThe condition variable object.
Return values
0Success.
EINVALcond is set to NULL.
Description
Platform Implementation
Win32 System calls are not called.
Linux pthread_cond_destroy()
FreeBSD pthread_cond_destroy()
OS X pthread_cond_destroy()
CAFE System calls are not called.
CTR Event::~Event()

◆ nlib_cond_init()

nlib_cond_init ( nlib_cond cond)

Initializes a condition variable.

Parameters
[in]condThe condition variable object.
Return values
0Success.
EINVALcond is set to NULL.
Description
Platform Implementation
Win32 InitializeConditionVariable()
Linux pthread_cond_init()
FreeBSD pthread_cond_init()
OS X pthread_cond_init()
CAFE OSFastCond_Init()
CTR Event::TryInitialize(true)

◆ nlib_cond_signal()

nlib_cond_signal ( nlib_cond cond)

Resumes the execution of one thread that is waiting for condition variable cond.

Parameters
[in]condThe condition variable object.
Return values
0Success.
EINVALcond is set to NULL.
Description
Platform Implementation
Win32 WakeConditionVariable()
Linux pthread_cond_signal()
FreeBSD pthread_cond_signal()
OS X pthread_cond_signal()
CAFE OSFastCond_Signal()
CTR Event::Signal()
On the CAFE and CTR platforms, this function resumes the execution of all threads.

◆ nlib_cond_wait()

nlib_cond_wait ( nlib_cond cond,
nlib_mutex mutex 
)

Unlocks mutex and waits for a condition variable. It then relocks mutex after execution resumes.

Parameters
[in]condThe condition variable object.
[in]mutexA mutex object.
Return values
0Success.
EINVALcond is set to NULL.
Description
The mutex must be locked only once before the function is called.
Platform Implementation
Win32 SleepConditionVariableCS()
Linux pthread_cond_wait()
FreeBSD pthread_cond_wait()
OS X pthread_cond_wait()
CAFE OSFastCond_Wait()
CTR Event::Wait() + Event::ClearSignal()
On the CTR platform, operations are not atomic during the time between when mutex is unlocked and relocked.

◆ nlib_cond_wait_for()

nlib_cond_wait_for ( nlib_cond cond,
nlib_mutex mutex,
nlib_duration  duration 
)

Unlocks mutex and waits for just the duration amount of time for a condition variable. It then relocks mutex after execution resumes.

Parameters
[in]condThe condition variable object.
[in]mutexA mutex object.
[in]durationThe length of time for the timeout.
Return values
0Success.
ETIMEDOUTIndicates a timeout.
EINVALcond is set to NULL.
Description
The mutex must be locked only once before the function is called.
Platform Implementation
Win32 SleepConditionVariableCS()
Linux pthread_cond_timedwait() - If errno is EINTR, the function is executed again internally.
FreeBSD pthread_cond_timedwait() - If errno is EINTR, the function is executed again internally.
OS X pthread_cond_timedwait() - If errno is EINTR, the function is executed again internally.
CAFE nlib_sleep()
CTR Event::Wait() + Event::ClearSignal()
On the CTR platform, operations are not atomic during the time between when mutex is unlocked and relocked. On the CAFE platform, the function unlocks mutex, sleeps for 100 microseconds, relocks the mutex object, and then returns 0. If duration is a negative value, the function returns ETIMEDOUT.

◆ nlib_cond_wait_until()

nlib_cond_wait_until ( nlib_cond cond,
nlib_mutex mutex,
nlib_time  abstime 
)

Unlocks mutex and waits until abstime for a condition variable. It then relocks mutex after execution resumes.

Parameters
[in]condThe condition variable object.
[in]mutexA mutex object.
[in]abstimeThe time when the timeout occurs.
Return values
0Success.
ETIMEDOUTIndicates a timeout.
EINVALcond is set to NULL.
Description
Considering the complication of spurious wakeups with condition variables, it could be argued that this function, which times out at a specified time, operates with more certainty than the nlib_cond_wait_for function, which times out after a specified duration of time.
The mutex must be locked only once before the function is called.
Platform Implementation
Win32 nlib_epochtime() + nlib_cond_wait_for()
Linux pthread_cond_timedwait()
FreeBSD pthread_cond_timedwait()
OS X pthread_cond_timedwait()
CAFE nlib_epochtime() + nlib_sleep()
CTR Event::Wait() + Event::ClearSignal()
On the CTR platform, operations are not atomic during the time between when mutex is unlocked and relocked. On the CAFE platform, the function unlocks mutex, sleeps for 100 microseconds, relocks the mutex, and then returns 0. If the current time is already past the time set for abstime, the function returns ETIMEDOUT.

◆ nlib_condrwlock_broadcast()

nlib_condrwlock_broadcast ( nlib_condrwlock cond)

Resumes the execution of all threads that are waiting for the read-write lock conditional variable cond.

Parameters
[in]condA read-write lock conditional variable.
Return values
0Success.
EINVALcond is set to NULL.
Description
Platform Implementation
Win32 WakeAllConditionVariable()
Linux nlib_mutex_lock(), nlib_cond_broadcast(), nlib_mutex_unlock()
FreeBSD nlib_mutex_lock(), nlib_cond_broadcast(), nlib_mutex_unlock()
OS X nlib_mutex_lock(), nlib_cond_broadcast(), nlib_mutex_unlock()
CAFE nlib_mutex_lock(), nlib_cond_broadcast(), nlib_mutex_unlock()
CTR nlib_mutex_lock(), nlib_cond_broadcast(), nlib_mutex_unlock()

◆ nlib_condrwlock_destroy()

nlib_condrwlock_destroy ( nlib_condrwlock cond)

Destroys a read-write lock conditional variable.

Parameters
[in]condA read-write lock conditional variable.
Return values
0Success.
EINVALcond is set to NULL.
Description
Platform Implementation
Win32 Does nothing.
Linux nlib_mutex_destroy(), nlib_cond_destroy()
FreeBSD nlib_mutex_destroy(), nlib_cond_destroy()
OS X nlib_mutex_destroy(), nlib_cond_destroy()
CAFE nlib_mutex_destroy(), nlib_cond_destroy()
CTR nlib_mutex_destroy(), nlib_cond_destroy()

◆ nlib_condrwlock_init()

nlib_condrwlock_init ( nlib_condrwlock cond)

Initializes a read-write lock conditional variable.

Parameters
[in]condA read-write lock conditional variable.
Return values
0Success.
EINVALcond is set to NULL.
Description
Platform Implementation
Win32 InitializeConditionVariable()
Linux nlib_mutex_init(), nlib_cond_init()
FreeBSD nlib_mutex_init(), nlib_cond_init()
OS X nlib_mutex_init(), nlib_cond_init()
CAFE nlib_mutex_init(), nlib_cond_init()
CTR nlib_mutex_init(), nlib_cond_init()

◆ nlib_condrwlock_signal()

nlib_condrwlock_signal ( nlib_condrwlock cond)

Resumes the execution of one thread that is waiting for the read-write lock conditional variable cond.

Parameters
[in]condA read-write lock conditional variable.
Return values
0Success.
EINVALcond is set to NULL.
Description
Platform Implementation
Win32 WakeConditionVariable()
Linux nlib_mutex_lock(), nlib_cond_signal(), nlib_mutex_unlock()
FreeBSD nlib_mutex_lock(), nlib_cond_signal(), nlib_mutex_unlock()
OS X nlib_mutex_lock(), nlib_cond_signal(), nlib_mutex_unlock()
CAFE nlib_mutex_lock(), nlib_cond_signal(), nlib_mutex_unlock()
CTR nlib_mutex_lock(), nlib_cond_signal(), nlib_mutex_unlock()

◆ nlib_condrwlock_wait()

nlib_condrwlock_wait ( nlib_condrwlock cond,
nlib_rwlock rwlock,
int  rdlock 
)

Unlocks rwlock and waits for a conditional variable. It then locks rwlock again after the execution resumes.

Parameters
[in]condA read-write lock conditional variable.
[in]rwlockRead-write locks.
[in]rdlockSpecify 0 for a write lock, or 1 for a read lock.
Return values
0Success.
EINVALIndicates that cond or rwlock is NULL.
Description
Platform Implementation
Win32 SleepConditionVariableSRW()
Linux nlib_mutex_lock(), nlib_rwlock_rdunlock() or nlib_rwlock_wrunlock(), nlib_cond_wait(), nlib_mutex_unlock(), nlib_rwlock_rdlock() or nlib_rwlock_wrlock()
FreeBSD nlib_mutex_lock(), nlib_rwlock_rdunlock() or nlib_rwlock_wrunlock(), nlib_cond_wait(), nlib_mutex_unlock(), nlib_rwlock_rdlock() or nlib_rwlock_wrlock()
OS X nlib_mutex_lock(), nlib_rwlock_rdunlock() or nlib_rwlock_wrunlock(), nlib_cond_wait(), nlib_mutex_unlock(), nlib_rwlock_rdlock() or nlib_rwlock_wrlock()
CAFE nlib_mutex_lock(), nlib_rwlock_rdunlock() or nlib_rwlock_wrunlock(), nlib_cond_wait(), nlib_mutex_unlock(), nlib_rwlock_rdlock() or nlib_rwlock_wrlock()
CTR nlib_mutex_lock(), nlib_rwlock_rdunlock() or nlib_rwlock_wrunlock(), nlib_cond_wait(), nlib_mutex_unlock(), nlib_rwlock_rdlock() or nlib_rwlock_wrlock()
See also
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2406.html#gen_cond_var

◆ nlib_condrwlock_wait_for()

nlib_condrwlock_wait_for ( nlib_condrwlock cond,
nlib_rwlock rwlock,
nlib_duration  duration,
int  rdlock 
)

Unlocks rwlock and waits for a conditional variable. It then locks rwlock again after the execution resumes.

Parameters
[in]condA read-write lock conditional variable.
[in]rwlockRead-write locks.
[in]durationThe length of time for the timeout.
[in]rdlockSpecify 0 for a write lock, or 1 for a read lock.
Return values
0Success.
ETIMEDOUTIndicates a timeout.
EINVALIndicates that cond or rwlock is NULL.
Description
Platform implementation
Win32 SleepConditionVariableSRW()
Linux nlib_mutex_lock(), nlib_rwlock_rdunlock() or nlib_rwlock_wrunlock(), nlib_cond_wait_for(), nlib_mutex_unlock(), nlib_rwlock_rdlock() or nlib_rwlock_wrlock()
FreeBSD nlib_mutex_lock(), nlib_rwlock_rdunlock() or nlib_rwlock_wrunlock(), nlib_cond_wait_for(), nlib_mutex_unlock(), nlib_rwlock_rdlock() or nlib_rwlock_wrlock()
OS X nlib_mutex_lock(), nlib_rwlock_rdunlock() or nlib_rwlock_wrunlock(), nlib_cond_wait_for(), nlib_mutex_unlock(), nlib_rwlock_rdlock() or nlib_rwlock_wrlock()
CAFE nlib_mutex_lock(), nlib_rwlock_rdunlock() or nlib_rwlock_wrunlock(), nlib_cond_wait_for(), nlib_mutex_unlock(), nlib_rwlock_rdlock() or nlib_rwlock_wrlock()
CTR nlib_mutex_lock(), nlib_rwlock_rdunlock() or nlib_rwlock_wrunlock(), nlib_cond_wait_for(), nlib_mutex_unlock(), nlib_rwlock_rdlock() or nlib_rwlock_wrlock()
See also
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2406.html#gen_cond_var

◆ nlib_condrwlock_wait_until()

nlib_condrwlock_wait_until ( nlib_condrwlock cond,
nlib_rwlock rwlock,
nlib_time  abstime,
int  rdlock 
)

Unlocks rwlock and waits for a conditional variable. It then locks rwlock again after the execution resumes.

Parameters
[in]condA read-write lock conditional variable.
[in]rwlockRead-write locks.
[in]abstimeThe time when the timeout occurs.
[in]rdlockSpecify 0 for a write lock, or 1 for a read lock.
Return values
0Success.
ETIMEDOUTIndicates a timeout.
EINVALIndicates that cond or rwlock is NULL.
Description
Platform implementation
Win32 SleepConditionVariableSRW()
Linux nlib_mutex_lock(), nlib_rwlock_rdunlock() or nlib_rwlock_wrunlock(), nlib_cond_wait_until(), nlib_mutex_unlock(), nlib_rwlock_rdlock() or nlib_rwlock_wrlock()
FreeBSD nlib_mutex_lock(), nlib_rwlock_rdunlock() or nlib_rwlock_wrunlock(), nlib_cond_wait_until(), nlib_mutex_unlock(), nlib_rwlock_rdlock() or nlib_rwlock_wrlock()
OS X nlib_mutex_lock(), nlib_rwlock_rdunlock() or nlib_rwlock_wrunlock(), nlib_cond_wait_until(), nlib_mutex_unlock(), nlib_rwlock_rdlock() or nlib_rwlock_wrlock()
CAFE nlib_mutex_lock(), nlib_rwlock_rdunlock() or nlib_rwlock_wrunlock(), nlib_cond_wait_until(), nlib_mutex_unlock(), nlib_rwlock_rdlock() or nlib_rwlock_wrlock()
CTR nlib_mutex_lock(), nlib_rwlock_rdunlock() or nlib_rwlock_wrunlock(), nlib_cond_wait_until(), nlib_mutex_unlock(), nlib_rwlock_rdlock() or nlib_rwlock_wrlock()
See also
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2406.html#gen_cond_var

◆ nlib_crc32()

nlib_crc32 ( uint32_t  crc32,
const void *  p,
size_t  n 
)

This function calculates the CRC-32 checksum value for data.

Parameters
[in]crc32The previous CRC-32 checksum value (its initial value is 0)
[in]pPointer to n-byte data.
[in]nData size.
Returns
The CRC-32 checksum value that is based on the specified data.
Description
While many ways are available to calculate CRC-32, this function uses the same means as those described in RFC 2083 (PNG) and RFC 1952 (gzip).
// Takes the checksum for the string.
const char str[] = "This is a string";
uint32_t crc32 = nlib_crc32(0, &str[0], strlen(str)); // 0x0876633FUL
Platform implementation
SSE Table lookup.
NEON __crc32b(),__crc32h(),__crc32w(),__crc32d()
CAFE Table lookup.
CTR Table lookup.
See also
https://tools.ietf.org/html/rfc2083 (RFC2083)
https://www.ietf.org/rfc/rfc1952.txt (RFC1952)
http://www.futomi.com/lecture/japanese/rfc1952.html (RFC1952, in Japanese)

◆ nlib_crc32c()

nlib_crc32c ( uint32_t  crc32c,
const void *  p,
size_t  n 
)

This function calculates the CRC-32C checksum value for data.

Parameters
[in]crc32cThe previous CRC-32C checksum value (its initial value is 0)
[in]pPointer to n-byte data.
[in]nData size.
Returns
The CRC-32C checksum value that is based on the specified data.
Description
While many ways are available to calculate CRC-32, this function uses the same means as those described in RFC 3720.
Platform implementation
SSE _mm_crc32_u8(),_mm_crc32_u16(),_mm_crc32_u32(),_mm_crc32_u64()
NEON __crc32b(),__crc32h(),__crc32w(),__crc32d()
CAFE Table lookup.
CTR Table lookup.
See also
https://tools.ietf.org/html/rfc3720 (RFC3720)

◆ nlib_ctz32()

static int nlib_ctz32 ( uint32_t  x)
inlinestatic

Returns the number of consecutive zero bits, with respect to the least significant bit (LSB).

Parameters
[in]xThe 32-bit value to operate on.
Returns
Returns an integer between 0 and 32.
Description
Platform Implementation
Win32 _BitScanForward()
Linux __builtin_ctz()
FreeBSD __builtin_ctz()
OS X __builtin_ctz()
CAFE 32 - nlib_clz32(~x & (x - 1));
CTR 32 - nlib_clz32(~x & (x - 1));
Sample code
nlib_ctz32(0x80000000); // returns 31
nlib_ctz32(0x00000001); // returns 0

Definition at line 2616 of file Platform.h.

◆ nlib_ctz64()

static int nlib_ctz64 ( uint64_t  x)
inlinestatic

Returns the number of consecutive zero bits, with respect to the least significant bit (LSB).

Parameters
[in]xThe 64-bit value to operate on.
Returns
Returns an integer between 0 and 64.
Description
Platform Implementation
Win32 _BitScanForward64() or _BitScanForward()
Linux __builtin_ctzll()
FreeBSD __builtin_ctzll()
OS X __builtin_ctzll()
CAFE 64 - nlib_clz64(~x & (x - 1));
CTR 64 - nlib_clz64(~x & (x - 1));
Sample code
nlib_ctz64(0x8000000000000000ULL); // returns 63
nlib_ctz64(0x0000000000000001ULL); // returns 0

Definition at line 2618 of file Platform.h.

◆ nlib_debug_backtrace()

nlib_debug_backtrace ( size_t *  result,
void **  buffer,
size_t  count 
)

Stores backtraces in the array specified by buffer.

Parameters
[out]resultThe number of stored backtraces.
[in,out]bufferThe buffer where the backtraces are stored.
[in]countThe number of backtraces that can be stored in buffer. (The number of void pointers).
Return values
0Success.
ENOTSUPThe feature is not supported. buffer gets filled with zeros.
EINVALWhen result is 0, buffer is NULL, or count is 0.
Description
Platform Implementation
Win32 CaptureStackBackTrace()
Linux backtrace(). For cygwin, return ENOTSUP.
FreeBSD backtrace()
OS X backtrace()
CAFE Returns ENOTSUP.
CTR Returns ENOTSUP.

◆ nlib_debug_backtrace_gettext()

nlib_debug_backtrace_gettext ( char *  str,
size_t  strbufsize,
void *const *  buf,
size_t  count 
)

Creates string information from the data obtained using the nlib_debug_backtrace function.

Parameters
[out]strBuffer for the string.
[in]strbufsizeSize of the buffer for the string.
[in]bufThe buffer storing the backtraces.
[in]countThe number of stored backtraces.
Return values
0Success.
ENOTSUPThe feature is not supported. An empty string gets set in str.
EINVALWhen str is NULL, strbufsize is 0, buf is NULL, or count is 0.
Description
The written text is terminated with the null character.
Platform Implementation
Win32 SymFromAddr()
Linux backtrace_symbols(). For cygwin, return ENOTSUP.
FreeBSD backtrace_symbols()
OS X backtrace_symbols()
CAFE Returns ENOTSUP.
CTR Returns ENOTSUP.

◆ nlib_dir_close()

nlib_dir_close ( nlib_dir  dir)

Closes a directory.

Parameters
[in]dirA nlib_dir structure.
Return values
0Success.
OtherFailed for some reason.
Description
Platform Implementation
Win32 FindClose()
Linux closedir()
FreeBSD closedir()
OS X closedir()
CAFE FSCloseDir()
CTR nn::fs::Directory::Finalize() + nn::fs::Directory::~Directory()

◆ nlib_dir_open()

nlib_dir_open ( nlib_dir *  dir,
const char *  native_path 
)

Opens a directory.

Parameters
[in]dirPointer to the nlib_dir structure to initialize.
[in]native_pathThe path name (UTF-8).
Return values
0Success.
EINVALIndicates that dir and native_path were NULL.
ENOENTNo directory exists.
ENOTDIRnative_path is not a directory.
ENOMEMmemory allocation failed.
OtherFailed for some reason.
Description
Platform Implementation
Win32 FindFirstFileW()
Linux opendir()
FreeBSD opendir()
OS X opendir()
CAFE FSOpenDir()
CTR nn::fs::Directory::Directory() + nn::fs::Directory::TryInitialize()
Sample code
nlib_dir dir;
e = nlib_dir_open(&dir, "path");
if (nlib_is_error(e)) {
// ERROR
}
nlib_dirent ent;
while ((e = nlib_dir_read(&ent, dir)) != ENOENT) {
// file if (ent.flags & 1) == 0
// directory if (ent.flags & 1) == 1
// ent.name is a name of entry.
}
if (e != ENOENT) {
// ERROR
}
e = nlib_dir_close(dir);
if (nlib_is_error(e)) {
// ERROR
}

◆ nlib_dir_read()

nlib_dir_read ( nlib_dirent *  ent,
nlib_dir  dir 
)

Reads one directory entry, if there are any.

Parameters
[in]entPointer to a directory entry.
[in]dirA nlib_dir structure.
Return values
0Success.
ENOENTReached the end and there are no more files in the directory.
OtherFailed for some reason.
Description
Platform Implementation
Win32 FindNextFileW()
Linux readdir(), dirfd(), fstatat()
FreeBSD readdir(), dirfd(), fstatat()
OS X readdir(), dirfd(), fstatat()
CAFE FSReadDir()
CTR nn::fs::Directory::TryRead()

◆ nlib_dirname()

nlib_dirname ( size_t *  len,
const char *  path 
)
Parameters
[out]lenLength of the string representing the directory.
[in]pathThe path string.
Returns
The first *len characters from the pointer, namely the return value, represents the directory.
Description
The following example shows the behavior of this function.
path rval[0] .. rval[*len - 1]
"" "."
"/" "/"
"." "."
".." "."
"../" ".."
"./" "."
"/usr/lib" "/usr"
"/usr/" "/usr"
"usr" "."
"sdmc:/test.txt" "sdmc:"
"C:\\test.txt" "C:"(Windows only)

◆ nlib_disk_freespace()

nlib_disk_freespace ( const char *  native_path,
uint64_t *  free_bytes_available,
uint64_t *  total_bytes,
uint64_t *  total_free_bytes 
)

Gets information related to the capacity of the storage region to which the specified path belongs.

Parameters
[in]native_pathThe path name (UTF-8).
[out]free_bytes_availableThe number of bytes available to the calling thread.
[out]total_bytesThe total number of bytes of storage.
[out]total_free_bytesThe total number of bytes of free storage.
Return values
0Success.
OtherPlatform-dependent error (user does not have appropriate access rights, etc.).
Description
Platform Implementation
Win32 GetDiskFreeSpaceExW()
Linux statvfs()
FreeBSD statvfs()
OS X statvfs()
CAFE FSGetFreeSpaceSize()
CTR nn::fs::GetSdmcSize()
Note
On CAFE, all of the variables store the number of available bytes as obtained with the FSGetFreeSpaceSize function.
On CTR, ignores the specified path string and gets the amount of free space available on the SD Card.

◆ nlib_double_from_chars()

nlib_double_from_chars ( double *  result,
const char **  endptr,
const char *  first,
const char *  last 
)

Converts a string to the double type.

Parameters
[out]resultA converted numeric value.
[out]endptrThe pointer to the first character that was not converted to a numeric value is stored.
[in]firstThe first character of the string to be parsed.
[in]lastThe last character of the string to be parsed.
Returns
Returns 0 on success.
Description
Runs from_chars() with std::chars_format::general specified as the format. For more information on return values, refer to the description for nlib_int32_from_chars().

◆ nlib_epochtime()

nlib_epochtime ( nlib_time t)

Gets the current time.

Parameters
[out]tPointer to where the current time is stored.
Return values
0Success.
EINVALIndicates that t is NULL.
Description
Platform Implementation
Win32 GetSystemTimeAsFileTime(), GetSystemTimePreciseAsFileTime()
Linux clock_gettime(CLOCK_REALTIME, now)
FreeBSD clock_gettime(CLOCK_REALTIME, now)
OS X host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock), clock_get_time(cclock, &mts)
CAFE OSGetTime()
CTR nn::fnd::DateTime::GetNow()

◆ nlib_error_string()

nlib_error_string ( errno_t  e)

Returns a string literal corresponding to the error value of nlib.

Parameters
[in]eAn error value.
Returns
A string literal corresponding to the error value.

◆ nlib_exist_path()

nlib_exist_path ( int *  result,
const char *  native_path 
)

Checks whether the path exists.

Parameters
[out]resultIf the path exists, some non-zero value gets set.
[in]native_pathThe path name (UTF-8).
Return values
0Success.
OtherA platform-dependent error.
Description
Platform Implementation
Win32 PathFileExistsW()
Linux stat()
FreeBSD stat()
OS X stat()
CAFE FSGetStat()
CTR nlib_fd_open()

◆ nlib_fd_close()

nlib_fd_close ( nlib_fd  fd)

Closes a file. The file descriptor will be released even if an error is returned.

Parameters
[in]fdThe file descriptor.
Return values
0Success.
EBADFfd is valid but not an open descriptor.
EIOAn I/O error occurred.
OtherAn error was returned by the native API.
Description
Platform Implementation
Win32 CloseHandle()
Linux close()
FreeBSD close()
OS X close()
CAFE FSCloseFile()
CTR FileStream::Finalize()

◆ nlib_fd_fileid()

nlib_fd_fileid ( nlib_fileid *  result,
nlib_fd  fd 
)
Parameters
[out]resultA unique byte string for the file.
[in]fdThe file descriptor.
Returns
Returns 0 on success. All other values represent an error.
Description
Obtains a unique ID for a file stored in a single computer. This allows you to check whether the files pointed with two descriptors are identical. As each of the IDs is stored in a structure with a definition different for each environment, use memcmp() for the comparison. Deleting and creating files repeatedly may cause the same IDs to be reused. Therefore, the file descriptors for the both files that you want to compare need to be kept opened.
Platform implementation
Win32 GetFileInformationByHandleEx()
Linux fstat()
FreeBSD fstat()
OS X fstat()
CAFE Returns ENOTSUP.
CTR Returns ENOTSUP.

◆ nlib_fd_flush()

nlib_fd_flush ( nlib_fd  fd)

Flushes the write to the file descriptor.

Parameters
[in]fdThe file descriptor.
Return values
0Success.
EBADFfd is valid but not an open descriptor.
OtherAn error was returned by the native API.
Description
Platform Implementation
Win32 FlushFileBuffers()
Linux Do nothing.
FreeBSD Do nothing.
OS X Do nothing.
CAFE FSFlushFile()
CTR FileStream::TryFlush()

◆ nlib_fd_getsize()

nlib_fd_getsize ( nlib_offset size,
nlib_fd  fd 
)

Gets the file size.

Parameters
[out]sizePointer to where the file size is stored.
[in]fdThe file descriptor.
Return values
0Success.
EINVALIndicates that size is NULL.
EBADFfd is valid but not an open descriptor.
OtherAn error was returned by the native API.
Description
Platform Implementation
Win32 GetFileSizeEx()
Linux fstat()
FreeBSD fstat()
OS X fstat()
CAFE FSGetStatFile()
CTR FileStream::TryGetSize()

◆ nlib_fd_native_handle()

nlib_fd_native_handle ( void **  native_handle,
nlib_fd  fd 
)

Gets (the equivalent of) the native file handle.

Parameters
[in]native_handlePointer to where the native file handle is stored.
[in]fdThe file descriptor.
Return values
0Success.
EBADFfd is valid but not an open descriptor.
OtherAn error was returned by the native API.
Description
Platform Implementation
Win32 HANDLE is stored.
Linux The same value as fd is stored.
FreeBSD The same value as fd is stored.
OS X The same value as fd is stored.
CAFE FSFileHandle is stored.
CTR The pointer to nn::fs::FileStream is stored.

◆ nlib_fd_open()

nlib_fd_open ( nlib_fd fd,
const char *  native_path,
unsigned int  flags,
int  mode 
)

Opens a file.

Parameters
[out]fdStores the file descriptor if the file is successfully opened.
[in]native_pathThe file path as a UTF-8 string.
[in]flagsA value that is a bitwise OR combination of flags for opening files.
[in]modeIf creating a file with NLIB_FD_O_CREAT, access permission must be specified. Otherwise, this argument needs not to be specified.
Return values
0Success.
EINVALIndicates that fd and native_path were NULL.
ENOTSUPIndicates that the value in flags is not supported.
ENOMEMMemory allocation failed.
ELOOPThe specified path represented a symbolic link.
OtherAn error was returned by the native API.
Description
flags can be set to any combination of relevant values including NLIB_FD_O_RDONLY, NLIB_FD_O_WRONLY, and NLIB_FD_O_RDWR.
Platform Implementation
Win32 CreateFileW(). The mode value is ignored.
Linux open()
FreeBSD open()
OS X open()
CAFE FSOpenFile(), The mode value is ignored.
CTR FileStream::TryInitialize(), The mode value is ignored.
Details of behavior in Windows
The following processes are internally performed.
  1. Returns EACCES if the path string specifies a reserved device name or device namespace.
  2. Converts a path string to a UTF-16-coded string and then to a UNC path.
  3. Sets FILE_FLAG_OVERLAPPED, FILE_FLAG_OPEN_REPARSE_POINT, and FILE_FLAG_POSIX_SEMANTICS and opens the file.
  4. Gets the file handle information, and returns ELOOP if FILE_ATTRIBUTE_REPARSE_POINT representing a symbolic link or junction is set.
  5. Returns the file descriptor to the user.
Details of behavior in Unix OSs
The following processes are internally performed.
  1. Gets the status with lstat(), and returns EACCES if it is not for a regular file or directory.
  2. Appends O_CLOEXEC, O_NOFOLLOW, and O_NONBLOCK to the flag given by the user and opens the file.
  3. Executes the function again if open() returns EINTR. For any other error, returns the error value, except EMLINK and EFTYPE which it returns as ELOOP.
  4. Returns EACCES if the status obtained with <t>fstat() does not match the one obtained with lstat().
  5. Resets O_NONBLOCK if the user has not set it.
  6. Returns the file descriptor to the user.

◆ nlib_fd_pread()

nlib_fd_pread ( size_t *  result,
nlib_fd  fd,
void *  buf,
size_t  count,
nlib_offset  offset 
)

Reads the file descriptor from the specified offset. The offset for the file descriptor will not be changed.

Parameters
[out]resultPointer to where the number of loaded bytes is stored.
[in]fdThe file descriptor.
[in]bufThe read buffer.
[in]countThe maximum number of bytes to read.
[in]offsetThe offset.
Returns
The values that can be returned by the nlib_fd_seek and nlib_fd_read functions.
Description
Platform Implementation
Win32 ReadFile
Linux pread
FreeBSD pread
OS X pread
CAFE FSReadFileWithPos()
CTR nlib_fd_seek() + nlib_fd_read()
Bug:
The behavior when opening a file using the NLIB_FD_O_APPEND flag is undefined.

◆ nlib_fd_pwrite()

nlib_fd_pwrite ( size_t *  result,
nlib_fd  fd,
const void *  buf,
size_t  count,
nlib_offset  offset 
)

Writes to the file descriptor at the specified offset. The offset for the file descriptor will not be changed.

Parameters
[out]resultPointer to where the number of loaded bytes is written.
[in]fdThe file descriptor.
[in]bufThe write buffer.
[in]countThe maximum number of bytes to write.
[in]offsetThe offset.
Returns
The values that can be returned by the nlib_fd_seek and nlib_fd_write functions.
Description
Platform Implementation
Win32 WriteFile
Linux pwrite
FreeBSD pwrite
OS X pwrite
CAFE FSWriteFileWithPos()
CTR nlib_fd_seek() + nlib_fd_write()
Bug:
The behavior when opening a file using the NLIB_FD_O_APPEND flag is undefined.

◆ nlib_fd_read()

nlib_fd_read ( size_t *  result,
nlib_fd  fd,
void *  buf,
size_t  count 
)

Reads (up to) count bytes from the file descriptor into buf.

Parameters
[out]resultPointer to where the number of loaded bytes is stored.
[in]fdThe file descriptor.
[in]bufThe read buffer.
[in]countThe maximum number of bytes to read.
Return values
0Success.
EINVALIndicates that result or buf is NULL.
EBADFfd is valid but not an open descriptor.
OtherAn error was returned by the native API.
Description
If 0 is stored in *result without generating an error, that indicates the end of the file.
Platform Implementation
Win32 ReadFile()
Linux read() - If errno is EINTR, the function is executed again internally.
FreeBSD read() - If errno is EINTR, the function is executed again internally.
OS X read() - If errno is EINTR, the function is executed again internally.
CAFE FSReadFile()
CTR FileStream::TryRead()

◆ nlib_fd_readv()

nlib_fd_readv ( size_t *  result,
nlib_fd  fd,
const nlib_fd_iovec *  iov,
int  iovcnt 
)

Loads multiple non-continuous buffers from the file associated with fd.

Parameters
[out]resultIf function call is successful, stores the number of loaded bytes.
[in]fdThe file descriptor.
[in]iovPointers to iovcnt number of buffers and the corresponding sizes.
[in]iovcntThe number of iov.
Return values
0Success.
EINVALresult was NULL.
EINVALiovcnt was less than 0 or more than 1024.
EINVALTotal combined buffer size exceeds RSIZE_MAX.
EBADFfd is not a valid open descriptor.
ENOMEMDynamic memory allocation failed.
OtherAn error was returned by the native API.
Description
A single call to the readv or nlib_fd_read function loads the data.
Platform Implementation
Win32 nlib_malloc(), nlib_fd_read(), nlib_free()
Linux readv() - If errno is EINTR, the function is executed again internally.
FreeBSD readv() - If errno is EINTR, the function is executed again internally.
OS X readv() - If errno is EINTR, the function is executed again internally.
CAFE nlib_malloc(), nlib_fd_read(), nlib_free()
CTR nlib_malloc(), nlib_fd_read(), nlib_free()

◆ nlib_fd_seek()

nlib_fd_seek ( nlib_offset result,
nlib_fd  fd,
nlib_offset  offset,
int  whence 
)

Changes the file offset.

Parameters
[out]resultPointer to where the changed offset is stored.
[in]fdThe file descriptor.
[in]offsetThe offset.
[in]whenceNLIB_SEEK_SET or NLIB_SEEK_CUR.
Return values
0Success.
EINVALIndicates that result is NULL, or whence is an invalid value.
EINVALThe offset after being changed is a negative value.
EBADFfd is valid but not an open descriptor.
OtherAn error was returned by the native API.
Description
Platform Implementation
Win32 Implemented by nlib.
Linux lseek()
FreeBSD lseek()
OS X lseek()
CAFE FSSetPosFile(), No offset is allowed to be set to a position after the end of the file.
CTR FileStream::TrySeek(), No offset is allowed to be set to a position after the end of the file.

◆ nlib_fd_sync()

nlib_fd_sync ( nlib_fd  fd)

Synchronizes the content of a file in memory with what is on the device.

Parameters
[in]fdThe file descriptor.
Return values
0Success.
EBADFfd is valid but not an open descriptor.
OtherAn error was returned by the native API.
Description
Platform Implementation
Win32 nlib_fd_flush()
Linux fsync()
FreeBSD fsync()
OS X fsync()
CAFE nlib_fd_flush()
CTR nlib_fd_flush()

◆ nlib_fd_truncate()

nlib_fd_truncate ( nlib_fd  fd,
nlib_offset  length 
)

Extends or truncates the file to be the specified size.

Parameters
[in]fdThe file descriptor.
[in]lengthThe length of the file.
Return values
0Success.
EBADFfd is not a valid open descriptor.
Othersdepending on an error returned by the native API.
Description
If the file has been extended, that added length is filled with zeroes. The file offset (the position for reading and writing) does not change. The file descriptor fd must be open for writing.
Platform Implementation
Win32 SetFilePointerEx() + SetEndOfFile()
Linux ftruncate()
FreeBSD ftruncate()
OS X ftruncate()
CAFE FSGetStatFile() + FSGetPosFile() + FSSetPosFile() + FSWriteFile() or FSTruncateFile()
CTR FileStream::TryGetSize() + FileStream::TrySetSize() + FileStream::TryWrite()

◆ nlib_fd_write()

nlib_fd_write ( size_t *  result,
nlib_fd  fd,
const void *  buf,
size_t  count 
)

Writes (up to) count bytes from buf to the file descriptor.

Parameters
[out]resultPointer to where the number of loaded bytes is written.
[in]fdThe file descriptor.
[in]bufThe write buffer.
[in]countThe maximum number of bytes to write.
Return values
0Success.
EINVALIndicates that result or buf is NULL.
EBADFfd is valid but not an open descriptor.
OtherAn error was returned by the native API.
Description
Platform Implementation
Win32 WriteFile()
Linux write() - If errno is EINTR, the function is executed again internally.
FreeBSD write() - If errno is EINTR, the function is executed again internally.
OS X write() - If errno is EINTR, the function is executed again internally.
CAFE FSWriteFile()
CTR FileStream::TryWrite()

◆ nlib_fd_writev()

nlib_fd_writev ( size_t *  result,
nlib_fd  fd,
const nlib_fd_iovec *  iov,
int  iovcnt 
)

Writes from multiple non-continuous buffers to the file associated with fd.

Parameters
[out]resultIf function call is successful, stores the number of bytes written.
[in]fdThe file descriptor.
[in]iovPointers to iovcnt number of buffers and the corresponding sizes.
[in]iovcntThe number of iov.
Return values
0Success.
EINVALresult was NULL.
EINVALiovcnt was less than 0 or more than 1024.
EINVALTotal combined buffer size exceeds RSIZE_MAX.
EBADFfd is not a valid open descriptor.
ENOMEMDynamic memory allocation failed.
OtherAn error was returned by the native API.
Description
A single call to the writev or nlib_fd_write function writes the data.
Platform Implementation
Win32 nlib_malloc(), nlib_fd_write(), nlib_free()
Linux writev() - If errno is EINTR, the function is executed again internally.
FreeBSD writev() - If errno is EINTR, the function is executed again internally.
OS X writev() - If errno is EINTR, the function is executed again internally.
CAFE nlib_malloc(), nlib_fd_write(), nlib_free()
CTR nlib_malloc(), nlib_fd_write(), nlib_free()

◆ nlib_free()

nlib_free ( void *  ptr)

A weak function that calls the C standard function free. nlib calls free via this function.

Parameters
[in]ptrThe pointer to free.
Description
With the exception of the Cygwin version, this function can be overridden by the user program. Overriding this function is a way to customize nlib memory deallocation.
If you are going to override the function, do not forget to code for C linkage using something like the following.
extern "C" void nlib_free(void* ptr) {
.....
}
Bug:
With the Cygwin version, the user program cannot override the function.
Examples:
heap/replace_malloc/replace_malloc.cpp.

◆ nlib_free_size()

nlib_free_size ( void *  ptr,
size_t  size 
)

Frees memory of a specified size. The default action is to call the nlib_free function.

Parameters
[in]ptrThe pointer to free.
[in]sizeThe size allocated to ptr.
Description
This function was designed to correspond to sized deallocation of C++14.
Examples:
heap/replace_malloc/replace_malloc.cpp.

◆ nlib_gen_random()

nlib_gen_random ( void *  buf,
size_t  size 
)

Generates a random value of size bytes and stores it in buf.

Parameters
[out]bufPointer to the region where the random value is stored.
[in]sizeThe size of the region where the random value is stored.
Returns
Returns 0 on success.
Description
Platform Implementation
Win32 CryptGenRandom()
Linux Loads /dev/urandom.
FreeBSD Loads /dev/urandom.
OS X Loads /dev/urandom.
CAFE Returns ENOTSUP.
CTR Returns ENOTSUP.
Sample code
if (nlib_is_error(nlib_gen_random(buf, size))) {
// try another method to generate random values
}

◆ nlib_getenv()

nlib_getenv ( size_t *  result,
char *  buf,
size_t  bufsize,
const char *  varname 
)

Gets the value for the environment variable as a string.

Parameters
[out]resultStores the required size for the buffer. 0 is stored if the corresponding environment variable does not exist.
[out]bufThe buffer that stores the environment variable.
[in]bufsizeThe size of buf.
[in]varnameThe name of the environment variable.
Return values
0Success.
EINVALIndicates that result or varname is NULL.
EINVALIndicates that buf is NULL and bufsize is not 0.
ERANGEThe prepared buffer was too small. The required buffer size gets written to result.
Description
To get the size of buffer needed for storing the value of the environment variable, call this function with buf set to NULL and bufsize set to 0.
Platform Implementation
Win32 getenv_s()
Linux getenv()
FreeBSD getenv()
OS X getenv()
CAFE ENVGetEnvironmentVariable()
CTR nn::hio::CTR::GetEnvironmentVariable(), hio must have been initialized.

◆ nlib_int32_from_chars()

nlib_int32_from_chars ( int32_t *  result,
const char **  endptr,
const char *  first,
const char *  last,
int  base 
)

Converts a string to the int32_t type.

Parameters
[out]resultA value converted into an integer value.
[out]endptrThe pointer to the first character that was not converted into an integer value is stored.
[in]firstThe first character of the string to be parsed.
[in]lastThe last character of the string to be parsed.
[in]baseA cardinal number (at least 8, 10, and 16 are supported.)
Return values
0Success.
EINVALIndicates that no character to be converted exists.
ERANGEIndicates that the numerical value could not be represented with the int32_t type.
Description
Implementation using from_chars() incorporated in C++17 and working based on the from_chars() specifications. If from_chars() is not available in the standard C++ library, substitute implementation is run.
The relationship between the return value and the value to be stored is described below:
  • If 0 is returned, the value converted into an integer value is stored in result and a pointer to the first character that could not be parsed as an integer value is stored in endptr.
  • If EINVAL is returned, result is not altered and first is stored in endptr.
  • If ERANGE is returned, result is not altered and a pointer to the first character that could not be parsed as an integer value is stored in endptr.

◆ nlib_is_dir()

nlib_is_dir ( int *  result,
const char *  native_path 
)

Checks whether the path is for a directory. Sets 0 in *result and returns 0 if no path exists.

Parameters
[out]resultIf the path is for a directory, some non-zero value gets set.
[in]native_pathThe path name (UTF-8).
Return values
0Success.
OtherA platform-dependent error.
Description
Platform Implementation
Win32 PathIsDirectoryW()
Linux stat()
FreeBSD stat()
OS X stat()
CAFE FSGetStat()
CTR nlib_dir_open()

◆ nlib_is_error()

template<class T >
nlib_is_error ( const T &  obj)
inlinenoexcept

Returns true when the process result or object status is in an erroneous condition.

Template Parameters
TThe value of bool or errno_t, or a class implementing operator bool()
Parameters
[in]objA return value from a function, or an object
Returns
True if an error has occurred
Description
A function that returns bool is generally evaluated as Success when it returns true and Failed when it returns false. A function that returns errno_t is evaluated as Success when it returns 0 and Failed when it returns a non-zero value.
Using nlib_is_error() allows the both types of functions to be properly evaluated for errors with the identical representation for their return values. In addition, they are implemented so that using a pointer as any of their arguments causes a compiling error.
Examples:
exi/script/script.cpp, exi/simple1/simple1.cpp, exi/textparser/textparser.cpp, heap/cachedheap/cachedheap.cpp, misc/datetime/datetime.cpp, misc/nflags/nflags.cpp, misc/readfile/readfile.cpp, misc/stringutils/stringutils.cpp, misc/threading/condvar/condvar.cpp, misc/threading/future/future.cpp, misc/threading/threadpool/threadpool.cpp, misc/threading/tls/tls.cpp, misc/uri/uri.cpp, misc/usezlib/usezlib.cpp, misc/writefile/writefile.cpp, msgpack/json/json.cpp, msgpack/jsonrpc/jsonrpc.cpp, msgpack/jsonrpc/server.cpp, msgpack/msgpack1/msgpack1.cpp, msgpack/msgpack2/msgpack2.cpp, msgpack/usertype/usertype.cpp, oss/binarypatch/binarypatch.cpp, succinct/detection/detection.cpp, succinct/ngc/ngc.cpp, and succinct/simple/simple.cpp.

Definition at line 682 of file Config.h.

◆ nlib_log_attr_setint()

nlib_log_attr_setint ( int  prio,
int  key,
int  value 
)

Specifies where to output the log for each level of priority.

Parameters
[in]prioSpecifies the nlib_log_priority value. (See kNlibLogVerbose.)
[in]keySpecifies where to output from nlib_log_key.
[in]valueThe value to set (Any non-zero value is ON.)
Returns
Returns 0 on success.
Description
key Value Description
kNlibLogAttrStdout Specifies output to standard output.
kNlibLogAttrStderr Specifies output to standard error output.
kNlibLogAttrMsvcTrace Specifies output using the OutputDebugString function in the Windows environment.
kNlibLogAttrSyslog Specifies output to the event log (Windows) or to syslog (Linux/FreeBSD).
kNlibLogAttrNlibFd Specifies output to a file. nlib_fd is specified for value.
An example configuration is shown below.
// Sets all log levels to be output to standard output.
nlib_log_attr_setint(kNlibLogLevelAll, kNlibLogAttrStdout, 1);
// Sets log levels of ERROR and above to be output to syslog.

◆ nlib_log_print()

nlib_log_print ( int  prio,
const char *  tag,
const char *  fmt,
  ... 
)

Outputs log messages.

Parameters
[in]prioValues of nlib_log_priority from kNlibLogVerbose to kNlibLogFatal.
[in]tagTagged text.
[in]fmtFormatted text.
Returns
The number of characters that were output.
Description
In the following sample code, the log priority level is set to DEBUG and the log output is set to standard output.
nlib_log_attr_setint(kNlibLogDebug, kNlibLogAttrStdout, 1);
nlib_log_print(kNlibLogDebug, "mytag", "my message");

◆ nlib_log_vprint()

nlib_log_vprint ( int  prio,
const char *  tag,
const char *  fmt,
va_list  ap 
)

Outputs log messages.

Parameters
[in]prioValues of nlib_log_priority from kNlibLogVerbose to kNlibLogFatal.
[in]tagTagged text.
[in]fmtFormatted text.
[in]apVariable length argument for the formatted text.
Returns
The number of characters that were output.

◆ nlib_malloc()

nlib_malloc ( size_t  size)

A weak function that calls the C standard function malloc. nlib calls malloc via this function.

Parameters
[in]sizeThe number of bytes to allocate.
Returns
The pointer to the allocated region.
Description
With the exception of the Cygwin version, this function can be overridden by the user program. Overriding this function is a way to customize nlib memory allocation.
If you are going to override the function, do not forget to code for C linkage using something like the following.
extern "C" void* nlib_malloc(size_t size) {
.....
}
Bug:
With the Cygwin version, the user program cannot override the function.
Examples:
heap/replace_malloc/replace_malloc.cpp, msgpack/jsonrpc/jsonrpc.cpp, and msgpack/jsonrpc/server.cpp.

◆ nlib_malloc_size()

nlib_malloc_size ( const void *  ptr)

Returns the allocated memory size.

Parameters
[in]ptrPointer to memory allocated by nlib_malloc.
Returns
Allocated size
Description
Note that no implementation is available for CAFE and CTR.
Platform implementation
Win32 _msize()
Linux malloc_usable_size()
FreeBSD malloc_usable_size()
OS X malloc_size()
CAFE No implementation found.
CTR No implementation found.

◆ nlib_memalign()

nlib_memalign ( size_t  alignment,
size_t  size 
)

A weak function that calls the C standard function memalign. nlib calls memalign via this function.

Parameters
[in]alignmentThe alignment.
[in]sizeThe size.
Returns
The pointer to the allocated region.
Description
This function can be overridden by a user program. Overriding this function is a way to customize nlib memory allocation.
If you are going to override the function, do not forget to code for C linkage using something like the following.
extern "C" void* nlib_memalign(size_t alignment, size_t size) {
.....
}
Note that no implementation for Win32 and CTR is available. For this reason, it is recommended that nn::nlib::DynamicAlignedStorage be used for portability.
Bug:
With the Cygwin version, the user program cannot override the function.
Examples:
heap/replace_malloc/replace_malloc.cpp.

◆ nlib_memccpy()

nlib_memccpy ( void *  dest,
size_t  dest_size,
const void *  src,
size_t  src_size,
int  c 
)

Continues copying until c is found. Stops copying when it is found.

Parameters
[in,out]destThe destination buffer that accepts the copied data.
[in]dest_sizeThe size of the destination buffer.
[in]srcThe source buffer that stores the original data to be copied to another buffer.
[in]src_sizeThe size of the source buffer.
[in]cCopying bytes of this value causes this function to return upon completion of that copy.
Returns
If the bytes of c have been successfully copied, the function returns the pointer to the byte following the bytes of c in the destination buffer. Otherwise, it returns NULL.
Description
The bytes of up to dest_size or src_size, whichever is smaller, are copied. Note that this behavior is the same as that of memccpy(dest, src, c, dest_size > src_size ? src_size : dest_size). If used as shown below, this function can be used to process strings, such as reading a single line of strings at once.
// copy one line
char* buf; // [buf, buf + n) available
char* p = (char*)nlib_memccpy(buf, n - 1, src, src_size, '\n');
if (p) {
*(p - 1) = '\0'; // deletes '\n'
} else {
if (src_size > n - 1) {
// you might have to expand buf and copy again.
buf[n - 1] = '\0';
} else {
// you might have to refill src buffer and copy again.
buf[src_size] = '\0';
}
}

◆ nlib_memchr()

nlib_memchr ( const void *  s,
int  c,
size_t  n 
)

Searches the n bytes from the start of the memory region (s, s + n) and returns a pointer to byte c.

Parameters
[in]sThe memory region to examine.
[in]cThe character to search for.
[in]nThe number of bytes to search through.
Returns
If found, returns a pointer to the byte. Otherwise, returns NULL.
Description
Platform Implementation
Win32 Implemented using SIMD.
Linux Implemented using SIMD.
FreeBSD Implemented using SIMD.
OS X Implemented using SIMD.
CAFE Scan in units of words.
CTR Scan in units of words.

◆ nlib_memchr_gt()

nlib_memchr_gt ( const void *  s,
int  c,
size_t  n 
)

Searches the n bytes from the start of memory region (s, s + n) and returns a pointer to data having a character larger than byte c.

Parameters
[in]sThe memory region to examine.
[in]cThe character to search for.
[in]nThe number of bytes to search through.
Returns
If found, returns a pointer to the byte. Otherwise, returns NULL.
Description
The comparison involves 8-bit unsigned integers. c must be 127 or less.

◆ nlib_memchr_lt()

nlib_memchr_lt ( const void *  s,
int  c,
size_t  n 
)

Searches the n bytes from the start of memory region (s, s + n) and returns a pointer to data having a character less than byte c.

Parameters
[in]sThe memory region to examine.
[in]cThe character to search for.
[in]nThe number of bytes to search through.
Returns
If found, returns a pointer to the byte. Otherwise, returns NULL.
Description
The comparison involves 8-bit unsigned integers. c must be 127 or less.
To detect, for example, an ASCII control character in a string, you would code something like the following.
const void* p = nlib_memchr_lt(s, 0x20, len);
Platform Implementation
Win32 Implemented using SIMD.
Linux Implemented using SIMD.
FreeBSD Implemented using SIMD.
OS X Implemented using SIMD.
CAFE Scan in units of words.
CTR Scan in units of words.

◆ nlib_memchr_mb()

nlib_memchr_mb ( const void *  s,
size_t  n 
)

Searches the n bytes from the start of memory region (s, s + n) and returns a pointer to the location where 0x80 or more bytes is stored.

Parameters
[in]sThe memory region to examine.
[in]nThe number of bytes to search through.
Returns
If found, returns a pointer to the byte. Otherwise, returns NULL.
Description
Use this function to find a UTF-8 multibyte character in a UTF-8 string.
Platform Implementation
Win32 Implemented using SIMD.
Linux Implemented using SIMD.
FreeBSD Implemented using SIMD.
OS X Implemented using SIMD.
CAFE Scan in units of bytes.
CTR Scan in units of bytes.

◆ nlib_memchr_not()

nlib_memchr_not ( const void *  s,
int  c,
size_t  n 
)

Searches the n bytes from the start of memory region(s, s + n) and returns a pointer that does not point to byte c.

Parameters
[in]sThe memory region to examine.
[in]cThe character to skip over.
[in]nThe number of bytes to search through.
Returns
If found, returns a pointer to the byte. Otherwise, returns NULL.
Description
Platform Implementation
Win32 Implemented using SIMD.
Linux Implemented using SIMD.
FreeBSD Implemented using SIMD.
OS X Implemented using SIMD.
CAFE Scan in units of words.
CTR Scan in units of words.

◆ nlib_memchr_range_not()

nlib_memchr_range_not ( const void *  s,
const char *  range,
size_t  n 
)

Searches the n bytes from the start of memory region (s, s + n) and returns a pointer to a character not contained in range.

Parameters
[in]sThe memory region to examine.
[in]rangeAn ASCII string representing the range.
[in]nThe number of bytes to search through.
Returns
If found, returns a pointer to the byte. Otherwise, returns NULL.
Description
range must be an ASCII string of length 2 (for example "09","AZ" or "az").
For a string range that matches [a-z]* you would code something like the following.
const void* end = nlib_memchr_range_not(start, "az", len);
Platform Implementation
Win32 Implemented using SIMD.
Linux Implemented using SIMD.
FreeBSD Implemented using SIMD.
OS X Implemented using SIMD.
CAFE Scan in units of words.
CTR Scan in units of words.

◆ nlib_memcmp()

nlib_memcmp ( const void *  buf1,
const void *  buf2,
size_t  n 
)

Compares the n bytes from the starts of buf1 and buf2 as unsigned char data.

Parameters
[in]buf1Comparison source - memory block 1.
[in]buf2Comparison source - memory block 2.
[in]nThe number of bytes to compare.
Return values
Positivebuf1 > buf2.
0buf1 == buf2.
Negativebuf1 < buf2.
Description
Platform Implementation
Win32 Implemented using SIMD.
Linux Implemented using SIMD.
FreeBSD Implemented using SIMD.
OS X Implemented using SIMD.
CAFE Scan in units of words.
CTR memcmp()

◆ nlib_memcplen()

nlib_memcplen ( size_t *  codepoint_count,
size_t *  supplementary_codepoint_count,
size_t *  from_read,
const nlib_utf8_t from,
size_t  from_size 
)

Gets the number of code points contained in the string and the number of supplementary characters contained in the string..

Parameters
[out]codepoint_countPointer that contains the number of code points.
[out]supplementary_codepoint_countPointer that contains the number of code points for supplementary characters (U+10000 - U+10FFFF).
[out]from_readPointer that contains the number of bytes that the number of code points was counted for.
[in]fromThe region that contains a non-null terminated UTF-8 string.
[in]from_sizeThe size of from.
Return values
0Success.
EINVALfrom_read or from is NULL.
EILSEQIndicates that invalid data that cannot be converted into a code point was detected.
Description
Counts UTF-8 strings of up to from_size bytes. Counts a null character as one character without stopping counting at that character. If a UTF-8 string starting from from is terminated in the middle of the code point, this function halts immediately before the terminating character and returns 0. When the function returns EILSEQ, it also halts immediately before the terminating character. In that case, data from from + *from_read has not been converted.
The number of characters when the string is converted to UTF-32 will be *codepoint_count. Note that you can use the formula *codepoint_count + *supplementary_codepoint_count to calculate the number of characters when the string is converted to UTF-16.

◆ nlib_memcpy()

static errno_t nlib_memcpy ( void *  s1,
size_t  s1max,
const void *  s2,
size_t  n 
)
inlinestatic

An implementation corresponding to N1078 memcpy_s.

Parameters
[in,out]s1The buffer to copy to.
[in]s1maxThe size of the buffer to copy to.
[in]s2The buffer to copy from.
[in]nThe number of bytes to copy.
Return values
0Success.
EINVALIndicates that s1 or s2 is NULL.
ERANGEThe buffer is not large enough.
Description
s1[0]=0 is set if the function fails and s1 is not NULL. The behavior is undefined if the buffers overlap.
Platform Implementation
Win32 memcpy()
Linux memcpy()
FreeBSD memcpy()
OS X memcpy()
CAFE OSBlockMove()
CTR memcpy()
Examples:
succinct/kwlink/kwlink.cpp.

Definition at line 2437 of file Platform.h.

◆ nlib_memcspn()

nlib_memcspn ( const void *  buf,
size_t  len,
const char *  set,
size_t  n 
)

Returns the length of the set of sub-bytes from the beginning of buf. The set of sub-bytes consists of bytes other than those contained in set.

Parameters
[in]bufA pointer to the region to be scanned.
[in]lenThe number of bytes contained in buf.
[in]setA set of bytes (It need not be null-terminated).
[in]nThe number of bytes contained in set.
Returns
The number of bytes contained in a section consisting of bytes not contained in set.
Description
You can use this function to skip strings until a specific string appears. Although it is similar to the standard C function strcspn(), buf need not be null-terminated.

◆ nlib_memmove()

static errno_t nlib_memmove ( void *  s1,
size_t  s1max,
const void *  s2,
size_t  n 
)
inlinestatic

An implementation corresponding to N1078 memmove_s.

Parameters
[in,out]s1The buffer to copy to.
[in]s1maxThe size of the buffer to copy to.
[in]s2The buffer to copy from.
[in]nThe number of bytes to copy.
Return values
0Success.
EINVALIndicates that s1 or s2 is NULL.
ERANGEThe buffer is not large enough.
Description
s1[0]=0 is set if the function fails and s1 is not NULL.
Platform Implementation
Win32 memmove()
Linux memmove()
FreeBSD memmove()
OS X memmove()
CAFE OSBlockMove()
CTR memmove()

Definition at line 2455 of file Platform.h.

◆ nlib_mempagesize()

nlib_mempagesize ( size_t *  size)

Gets the page size.

Parameters
[out]sizeStores the page size.
Returns
Returns 0 on success.
Description
Platform Implementation
Win32 The GetSystemInfo function. (Call once at startup.)
Linux The getpagesize function. (Call once when running the first time.)
FreeBSD The getpagesize function. (Call once when running the first time.)
OS X The getpagesize function. (Call once when running the first time.)
CAFE Set the OSGetPageSize function and return 0.
CTR Set NN_OS_MEMORY_PAGE_SIZE and return 0.

◆ nlib_memrchr()

nlib_memrchr ( const void *  s,
int  c,
size_t  n 
)

Searches the n bytes from the end of memory region (s, s + n) and returns a pointer to byte c.

Parameters
[in]sThe memory region to examine.
[in]cThe character to search for.
[in]nThe number of bytes to search through.
Returns
If found, returns a pointer to the byte. Otherwise, returns NULL.
Description
Platform Implementation
Win32 Implemented using SIMD.
Linux Implemented using SIMD.
FreeBSD Implemented using SIMD.
OS X Implemented using SIMD.
CAFE Scan in units of words.
CTR Scan in units of words.

◆ nlib_memset()

static errno_t nlib_memset ( void *  buf,
int  ch,
size_t  n 
)
inlinestatic

Makes a function call corresponding to memset(buf, ch, n).

Parameters
[in,out]bufThe memory block to set the data to.
[in]chThe byte data (character) to set.
[in]nThe number of bytes.
Returns
Returns 0 on success.
Description

Definition at line 2469 of file Platform.h.

◆ nlib_memspn()

nlib_memspn ( const void *  buf,
size_t  len,
const char *  set,
size_t  n 
)

Returns the length of the set of sub-bytes from the beginning of buf. The set of sub-bytes consists of only bytes contained in set.

Parameters
[in]bufA pointer to the region to be scanned.
[in]lenThe number of bytes contained in buf.
[in]setA set of bytes (It need not be null-terminated).
[in]nThe number of bytes contained in set.
Returns
The number of bytes contained in a section consisting of bytes contained in set.
Description
You can use this function to skip a specific string. Although it is similar to the standard C function strspn(), buf need not be null-terminated.

◆ nlib_memutf16_to_utf8()

nlib_memutf16_to_utf8 ( size_t *  to_count,
size_t *  from_count,
nlib_utf8_t to,
size_t  to_size,
const nlib_utf16_t from,
size_t  from_size 
)

Converts a UTF-16 string that is not null terminated to a UTF-8 string.

Parameters
[out]to_countStores the number of converted characters.
[out]from_countStores the number of characters successfully converted.
[out]toPointer to the region that is to contain a converted UTF-8 string (not null terminated).
[in]to_sizeThe size, in the number of characters, of the to buffer.
[in]fromPointer to the region that contains a UTF-16 string (not null terminated).
[in]from_sizeThe size, in the number of characters, of the from buffer.
Return values
0All the conversions have successfully completed.
EINVALIndicates that to_count, from_count, or from is NULL.
EINVALIndicates that to is NULL and to_size is not 0.
EILSEQIndicates that invalid data that cannot be converted was detected.
Description
If a UTF-16 string starting from from is terminated in the middle of the code point, this function halts immediately before the terminating character and returns 0. When the function returns EILSEQ, it also halts immediately before the terminating code point. In that case, data from from + *from_count has not been converted.

◆ nlib_memutf32_to_utf8()

nlib_memutf32_to_utf8 ( size_t *  to_count,
size_t *  from_count,
nlib_utf8_t to,
size_t  to_size,
const nlib_utf32_t from,
size_t  from_size 
)

Converts a UTF-32 string that is not null terminated to a UTF-8 string.

Parameters
[out]to_countStores the number of converted characters.
[out]from_countStores the number of characters successfully converted.
[out]toPointer to the region that is to contain a converted UTF-8 string (not null terminated).
[in]to_sizeThe size, in the number of characters, of the to buffer.
[in]fromPointer to the region that contains a UTF-32 string (not null terminated).
[in]from_sizeThe size, in the number of characters, of the from buffer.
Return values
0All the conversions have successfully completed.
EINVALIndicates that to_count, from_count, or from is NULL.
EINVALIndicates that to is NULL and to_size is not 0.
EILSEQIndicates that invalid data that cannot be converted was detected.

◆ nlib_memutf8_to_utf16()

nlib_memutf8_to_utf16 ( size_t *  to_count,
size_t *  from_count,
nlib_utf16_t to,
size_t  to_size,
const nlib_utf8_t from,
size_t  from_size 
)

Converts a UTF-8 string that is not null terminated to a UTF-16 string.

Parameters
[out]to_countStores the number of converted characters.
[out]from_countStores the number of characters successfully converted.
[out]toPointer to the region that is to contain a converted UTF-16 string (not null terminated).
[in]to_sizeThe size, in the number of characters, of the to buffer.
[in]fromPointer to the region that contains a UTF-8 string (not null terminated).
[in]from_sizeThe size, in the number of characters, of the from buffer.
Return values
0All the conversions have successfully completed.
EINVALIndicates that to_count, from_count, or from is NULL.
EINVALIndicates that to is NULL and to_size is not 0.
EILSEQIndicates that invalid data that cannot be converted was detected.
Description
If a UTF-8 string starting from from is terminated in the middle of the code point, this function halts immediately before the terminating character and returns 0. When the function returns EILSEQ, it also halts immediately before the terminating code point. In that case, data from from + *from_count has not been converted.

◆ nlib_memutf8_to_utf32()

nlib_memutf8_to_utf32 ( size_t *  to_count,
size_t *  from_count,
nlib_utf32_t to,
size_t  to_size,
const nlib_utf8_t from,
size_t  from_size 
)

Converts a UTF-8 string that is not null terminated to a UTF-32 string.

Parameters
[out]to_countStores the number of converted characters.
[out]from_countStores the number of characters successfully converted.
[out]toPointer to the region that is to contain a converted UTF-32 string (not null terminated).
[in]to_sizeThe size, in the number of characters, of the to buffer.
[in]fromPointer to the region that contains a UTF-8 string (not null terminated).
[in]from_sizeThe size, in the number of characters, of the from buffer.
Return values
0All the conversions have successfully completed.
EINVALIndicates that to_count, from_count, or from is NULL.
EINVALIndicates that to is NULL and to_size is not 0.
EILSEQIndicates that invalid data that cannot be converted was detected.
Description
If a UTF-8 string starting from from is terminated in the middle of the code point, this function halts immediately before the terminating character and returns 0. When the function returns EILSEQ, it also halts immediately before the terminating code point. In that case, data from from + *from_count has not been converted.

◆ nlib_mkdir()

nlib_mkdir ( const char *  native_path,
unsigned int  flags 
)

Creates a directory.

Parameters
[in]native_pathThe path name (UTF-8).
[in]flagsThis parameter is currently not being used.
Return values
0Success.
EINVALnative_path was set to NULL.
EEXISTnative_path already exists.
OtherFailed for some reason.
Description
Platform Implementation
Win32 CreateDirectoryW()
Linux mkdir()
FreeBSD mkdir()
OS X mkdir()
CAFE FSMakeDir()
CTR nn::fs::TryCreateDirectory()

◆ nlib_mkostemps()

nlib_mkostemps ( nlib_fd fd,
char *  templ,
int  suffixlen,
int  flags 
)

Creates a temporary file with a unique name that is hard to be guessed.

Parameters
[out]fdThe file descriptor of a temporary file.
[in,out]templA file name template and created file name.
[in]suffixlenThe length of the suffix within the template.
[in]flagsThe flag to be specified when opening a temporary file (NLIB_FD_O_APPEND can be specified).
Return values
0Success.
EINVALIndicates that fd or templ was NULL. The set of six letters immediately before the suffix of templ was not XXXXXX.
EEXISTIndicates that retrying multiple times by specifying a different file name each time encountered the same file names that already exist. templ is undefined.
Description
Creates a temporary file from a string specified in templ, and stores the file descriptor in fd. 0600 is specified as an access permission, and NLIB_FD_O_RDWR, NLIB_FD_O_CREAT, or NLIB_FD_O_EXCL is always specified as the file creation flag. O_CLOEXEC is also specified in an environment where it can be specified.
The set of six letters immediately before the suffix of the argument templ has to be XXXXXX. That is, it must be in the 'mytmpfileXXXXXXsuffix' format. This function rewrites this part of templ to create a temporary file.
In an environment, including Linux, that supports the file creation flag O_TMPFILE, specifying a directory in templ opens the file with O_TMPFILE specified. Note that templ should be terminated with '/'. In this case, the file is opened without O_EXCL specified.
Platform implementation
Win32 nlib_fd_open()
Linux mkostemps(), open()
FreeBSD mkostemps()
OS X mkstemps()
CAFE nlib_fd_open()
CTR nlib_fd_open()

◆ nlib_mlock()

nlib_mlock ( void *  addr,
size_t  len 
)

The specified memory region is not swapped out.

Parameters
[in]addrStart of the region to lock.
[in]lenThe size.
Returns
Returns 0 on success.
Description
Platform Implementation
Win32 VirtualLock()
Linux mlock()
FreeBSD mlock()
OS X mlock()
CAFE Return 0.
CTR Return 0.

◆ nlib_mq_close()

nlib_mq_close ( nlib_mq  mq)

Closes the message queue indicated with a handle.

Parameters
[in]mqHandle to a message queue.
Return values
0Success.
EBADFIndicates the handle specified with mq is invalid.
Description
When messages remain in the queue, a destructor is run for each of the messages.

◆ nlib_mq_drop()

nlib_mq_drop ( nlib_mq  mq,
nlib_mq_msg msg,
int *  prio 
)

Receives a message with the lowest priority from a queue. It is the user's responsibility to delete the received messages using a destructor function.

Parameters
[in]mqHandle to a message queue.
[out]msgStores received messages.
[out]prioIf a value other than NULL is specified, stores the priority of a received message.
Return values
0Success.
EINVALIndicates msg is set to NULL.
EBADFIndicates the handle specified with mq is invalid.
ENOENTIndicates the queue is empty.

◆ nlib_mq_getattr()

nlib_mq_getattr ( nlib_mq  mq,
nlib_mq_attr attr 
)

Obtains the attribute set to the message queue indicated with a handle.

Parameters
[in]mqHandle to a message queue.
[in]attrMessage queue attribute.
Return values
0Success.
EBADFIndicates the handle specified with mq is invalid.
EINVALIndicates attr is NULL.

◆ nlib_mq_open()

nlib_mq_open ( nlib_mq mq,
const nlib_mq_attr attr 
)

Creates a message queue to be used to exchange messages across threads.

Parameters
[out]mqStores the handle to a message queue.
[in]attrMessage queue attribute.
Return values
0Success.
ENOMEMMemory allocation failed.
ENFILEIndicates the number of created message queues has reached its upper limit.
EINVALIndicates mq or attr is NULL.
Description
This function can open a message queue that can be used for communications that exchange objects across threads. Message queues in nlib have the following features:
  • Queue with 32 priority levels from 0 to 31 (the larger the value, the higher the priority).
  • Supports message exchange with blocking queues, non-blocking queues, and lock-free queues.
  • When using a blocking queue, messages with a time-out set can be sent and received.
  • When messages have the same priority, they are received in the order they were sent.
  • Can be closed in a thread-safe manner. An error is returned for read or write using an invalid handle.
  • Can be closed even when messages remain in the queue. The messages remaining in the queue will be deleted by the destructor.
  • Can be set as receive-only. A receive-only queue can be used for finalization.
  • Messages with a low priority can be taken from the queue. This feature is useful when you need to send a message with a higher priority when the queue is full.

◆ nlib_mq_readonly()

nlib_mq_readonly ( nlib_mq  mq)

Sets the message queue indicated with a handle as receive-only.

Parameters
[in]mqHandle to a message queue.
Return values
0Success.
EBADFIndicates the handle specified with mq is invalid.
Description
After running this function, any attempt to write into this message queue causes an EPERM error to be returned. This function is useful when you no longer want to accept new messages and need to process messages remaining in the queue.

◆ nlib_mq_receive()

nlib_mq_receive ( nlib_mq  mq,
nlib_mq_msg msg,
int *  prio 
)

Receives a message from a queue. It is the user's responsibility to delete the received messages using a destructor function.

Parameters
[in]mqHandle to a message queue.
[out]msgStores received messages.
[out]prioIf a value other than NULL is specified, stores the priority of a received message.
Return values
0Success.
EINVALIndicates msg is set to NULL.
EBADFIndicates the handle specified with mq is invalid.
EAGAINIndicates the message queue that is not a blocking queue is empty.
Description
When using a lock-free queue, if a message with a higher priority is sent and stored in the queue while running this function, a message with the highest priority (the message sent as described above) stored in the queue may no longer be taken from the queue.

◆ nlib_mq_receive_until()

nlib_mq_receive_until ( nlib_mq  mq,
nlib_mq_msg msg,
int *  prio,
nlib_time  abstime 
)

Receives a message with a time-out set from a queue. It is the user's responsibility to delete the received messages using a destructor function.

Parameters
[in]mqHandle to a message queue.
[out]msgStores received messages.
[out]prioIf a value other than NULL is specified, stores the priority of a received message.
[in]abstimeThe time when the timeout occurs.
Return values
0Success.
EINVALIndicates msg is set to NULL.
EBADFIndicates the handle specified with mq is invalid.
EINVALIndicates msg is set to NULL.
EINVALIndicates the message queue is not a blocking queue.
ETIMEDOUTIndicates an attempt to receive a message in a blocking queue has timed-out.

◆ nlib_mq_send()

nlib_mq_send ( nlib_mq  mq,
nlib_mq_msg  msg,
int  prio 
)

Sends a message to a queue.

Parameters
[in]mqHandle to a message queue.
[in]msgA message to send.
[in]prioAn integer between 0 to 31 indicating the message priority (with 31 being the highest priority).
Return values
0Success.
EBADFIndicates the handle specified with mq is invalid.
EINVALIndicates the priority specified with prio is below 0 or exceeds 32.
EAGAINIndicates the message queue that is not a blocking queue is full.
EPERMIndicates the queue is set as receive-only.

◆ nlib_mq_send_until()

nlib_mq_send_until ( nlib_mq  mq,
nlib_mq_msg  msg,
int  prio,
nlib_time  abstime 
)

Sends a messages with a time-out set to the queue.

Parameters
[in]mqHandle to a message queue.
[in]msgA message to send.
[in]prioAn integer between 0 to 31 indicating the message priority (with 31 being the highest priority).
[in]abstimeThe time when the timeout occurs.
Return values
0Success.
EBADFIndicates the handle specified with mq is invalid.
EINVALIndicates the priority specified with prio is below 0 or exceeds 32.
EINVALIndicates the message queue is not a blocking queue.
ETIMEDOUTIndicates an attempt to send a message to a blocking queue has timed-out.
EPERMIndicates the queue is set as receive-only.

◆ nlib_munlock()

nlib_munlock ( void *  addr,
size_t  len 
)

The specified memory region can be swapped out.

Parameters
[in]addrStart of the region to unlock.
[in]lenThe size.
Returns
Returns 0 on success.
Description
Platform Implementation
Win32 VirtualUnlock()
Linux munlock()
FreeBSD munlock()
OS X munlock()
CAFE Return 0.
CTR Return 0.

◆ nlib_mutex_destroy()

nlib_mutex_destroy ( nlib_mutex mutex)

Destroys the specified mutex object and frees any associated resources.

Parameters
[in]mutexThe mutex to destroy.
Return values
0Success.
EINVALIndicates that mutex is NULL.
OtherIndicates something else, like that mutex is locked.
Description
Platform Implementation
Win32 CloseHandle() or DeleteCriticalSection()
Linux pthread_mutex_destroy()
FreeBSD pthread_mutex_destroy()
OS X pthread_mutex_destroy()
CAFE No SDK API called.
CTR CriticalSection::~CriticalSection()

◆ nlib_mutex_init()

nlib_mutex_init ( nlib_mutex mutex)

Initializes a mutex.

Parameters
[in]mutexIndicates the mutex object to initialize.
Returns
Always returns 0.
Description
Platform Implementation
Win32 InitializeCriticalSectionEx()
Linux pthread_mutex_init()
FreeBSD pthread_mutex_init()
OS X pthread_mutex_init()
CAFE OSFastMutex_Init()
CTR CriticalSection::CriticalSection()

◆ nlib_mutex_lock()

nlib_mutex_lock ( nlib_mutex mutex)

Locks the specified mutex.

Parameters
[in]mutexThe mutex to lock.
Return values
0Success.
EINVALIndicates that mutex is NULL or is not initialized.
EDEADLKIndicates that a deadlock is detected successfully.
Description
In all platforms, it is possible to implement the code in which 0 is always returned unless there is any programming error.
Platform Implementation
Win32 WaitForSingleObject() or EnterCriticalSection()
Linux pthread_mutex_lock()
FreeBSD pthread_mutex_lock()
OS X pthread_mutex_lock()
CAFE OSFastMutex_Lock()
CTR CriticalSection::Enter()
Examples:
heap/nmalloc_simple/nmalloc_simple.cpp.

◆ nlib_mutex_recursive_init()

nlib_mutex_recursive_init ( nlib_mutex mutex)

Initializes a recursive mutex.

Parameters
[in]mutexIndicates the mutex object to initialize.
Returns
Always returns 0.
Description
Platform Implementation
Win32 InitializeCriticalSectionEx()
Linux pthread_mutex_init()
FreeBSD pthread_mutex_init()
OS X pthread_mutex_init()
CAFE OSFastMutex_Init()
CTR CriticalSection::CriticalSection()

◆ nlib_mutex_recursive_timed_init()

nlib_mutex_recursive_timed_init ( nlib_mutex mutex)

Initializes a mutex that is recursive and can time out.

Parameters
[in]mutexIndicates the mutex object to initialize.
Returns
Always returns 0.
Description
Platform Implementation
Win32 CreateMutex()
Linux Assign NLIB_RECURSIVE_TIMED_MUTEX_INITIALIZER.
FreeBSD pthread_mutex_init()
OS X pthread_mutex_init()
CAFE OSFastMutex_Init()
CTR CriticalSection::CriticalSection()

◆ nlib_mutex_trylock()

nlib_mutex_trylock ( nlib_mutex mutex)

Locks mutex, but only if it is not locked.

Parameters
[in]mutexThe mutex to lock.
Return values
0Success.
EINVALIndicates that mutex is NULL or is not initialized.
EBUSYThe mutex is already locked by some other thread.
OtherCould not lock for some reason.
Description
Platform Implementation
Win32 WaitForSingleObject() or TryEnterCriticalSection()
Linux pthread_mutex_trylock()
FreeBSD pthread_mutex_trylock()
OS X pthread_mutex_trylock()
CAFE OSFastMutex_TryLock()
CTR CriticalSection::TryEnter()

◆ nlib_mutex_trylock_for()

nlib_mutex_trylock_for ( nlib_mutex mutex,
nlib_duration  delta 
)

Locks the specified mutex. Times out.

Parameters
[in]mutexThe mutex to lock.
[in]deltaThe timeout time.
Return values
0Success.
EINVALIndicates that mutex is NULL or is not initialized.
ETIMEDOUTIndicates a timeout.
OtherCould not lock for some reason.
Description
Platform Implementation
Win32 WaitForSingleObject()
Linux pthread_mutex_timedlock()
FreeBSD pthread_mutex_timedlock()
OS X nlib_mutex_trylock(), nlib_sleep()
CAFE OSFastMutex_TryLock(), nlib_sleep()
CTR CriticalSection::TryEnter()
On the CAFE and CTR platforms, tries again to lock mutex after sleeping for 100 microseconds repeatedly.

◆ nlib_mutex_unlock()

nlib_mutex_unlock ( nlib_mutex mutex)

Unlocks the specified mutex.

Parameters
[in]mutexThe mutex to unlock.
Return values
0Success.
EINVALIndicates that mutex is NULL or is not initialized.
Indicatesthat unlocking has failed due to other programming errors.
Description
In all platforms, it is possible to implement the code in which 0 is always returned unless there is any programming error.
Platform Implementation
Win32 ReleaseMutex() or LeaveCriticalSection()
Linux pthread_mutex_unlock()
FreeBSD pthread_mutex_unlock()
OS X pthread_mutex_unlock()
CAFE OSFastMutex_Unlock()
CTR CriticalSection::Leave()
Examples:
heap/nmalloc_simple/nmalloc_simple.cpp.

◆ nlib_once()

nlib_once ( nlib_onceflag flag,
nlib_oncefunc  func 
)

Ensures that func is executed only one time at most.

Parameters
[in]flagInitializes with NLIB_ONCE_INIT and changes the value after the function executes.
[in]funcThe function to execute only one time at most.
Return values
0Indicates that execution of the function has completed.
EINVALflag was set to NULL.
Description
The value indicated by flag must be initialized with NLIB_ONCE_INIT ahead of time. If the nlib_once function has been called multiple times, this function does nothing if it has already been called.
The code is typically implemented in the following way.
static nlib_onceflag onceflag = NLIB_ONCE_INIT; // Statically initialized, usually.
static void oncefunc() {
// The process when you want a function to execute at most only one time.
}
void func() {
nlib_once(&onceflag, oncefunc);
// The coding assumes that oncefunc() has been called.
}
Examples:
heap/gameheap/gameheap.cpp, misc/threading/callonce/callonce.cpp, and misc/threading/safeinit/safeinit.cpp.

◆ nlib_pause()

nlib_pause ( void  )
inlinestatic

Waits for a very short time.

Description
Used in order to reduce the power consumption of the processor by avoiding a busy wait while spinning a waiting loop. This poses less overhead than nlib_yield() does, and can indicate to the hardware that a waiting state is now placed.
Platform implementation
x86/x86_64 _mm_pause()
arm __yield() if __ARM_ACLE defined
others nlib_yield()

Definition at line 1211 of file Platform.h.

◆ nlib_physical_alloc()

nlib_physical_alloc ( void *  ptr,
size_t  size,
int  prot 
)

Allocates physical memory.

Parameters
[in]ptrA pointer to virtual memory.
[in]sizeThe size (in bytes) of the physical memory to allocate.
[in]protThe access specification.
Returns
Returns 0 on success.
Description
Specifies a region in the range allocated by the nlib_virtual_alloc function and allocates physical memory.
prot is given a bitwise OR of the following values.
Value Description
NLIB_PHYSICAL_ALLOC_PROT_NONE Cannot access memory.
NLIB_PHYSICAL_ALLOC_PROT_READ Can read memory.
NLIB_PHYSICAL_ALLOC_PROT_WRITE Can change memory.
NLIB_PHYSICAL_ALLOC_PROT_EXEC Can execute memory.
Platform Implementation
Win32 VirtualAlloc(ptr, size, MEM_COMMIT, ...)
Linux mprotect()
FreeBSD mprotect()
OS X mprotect()
CAFE Return 0.
CTR Return 0.

◆ nlib_physical_free()

nlib_physical_free ( void *  ptr,
size_t  size 
)

Frees the allocated physical memory.

Parameters
[in]ptrA pointer to virtual memory.
[in]sizeThe size (in bytes) of the region of allocated physical memory to free.
Returns
Returns 0 on success.
Description
Specifies a region in the range allocated by the nlib_virtual_alloc function and frees the allocated physical memory.
Platform Implementation
Win32 VirtualFree(..., MEM_DECOMMIT)
Linux mprotect(..., PROT_NONE)
FreeBSD mprotect(..., PROT_NONE)
OS X mprotect(..., PROT_NONE)
CAFE Return 0.
CTR Return 0.

◆ nlib_popcnt16()

static int nlib_popcnt16 ( uint16_t  x)
inlinestatic

Returns the number of bits that are 1.

Parameters
[in]xA 16-bit integer.
Returns
Returns an integer between 0 and 16.

Definition at line 2479 of file Platform.h.

◆ nlib_popcnt32()

static int nlib_popcnt32 ( uint32_t  x)
inlinestatic

Returns the number of bits that are 1.

Parameters
[in]xA 32-bit integer.
Returns
Returns an integer between 0 and 32.
Description
Platform Implementation
SSE _mm_popcnt_u32()
NEON vcnt_u8()
CAFE Table lookup.
CTR Table lookup.

Definition at line 2482 of file Platform.h.

◆ nlib_popcnt64()

static int nlib_popcnt64 ( uint64_t  x)
inlinestatic

Returns the number of bits that are 1.

Parameters
[in]xA 64-bit integer.
Returns
Returns an integer between 0 and 64.
Description
Platform Implementation
SSE _mm_popcnt_u32(), _mm_popcnt_u64()
NEON vcnt_u8()
CAFE Table lookup.
CTR Table lookup.

Definition at line 2485 of file Platform.h.

◆ nlib_readlink()

nlib_readlink ( size_t *  len,
const char *  native_path,
char *  buf,
size_t  bufsize 
)

Resolve a symbolic link.

Parameters
[out]lenThe length of the string stored in buf (not including null characters).
[in]native_pathThe path to the symbolic link.
[out]bufThe buffer to store the content of the symbolic link.
[in]bufsizeThe size of the buffer.
Return values
0Success.
EINVALnaitive_path is not a symbolic link, or other conditions.
ERANGEThe buffer length was insufficient (the string length for the content of the symbolic link is stored in *len).
Otherplatform dependent error value.
Description
If successful, the string stored in buf will be null terminated. In addition, if buf was too small, returns ERANGE and stores the string length in *len. In that case, you can run the function again by preparing a buffer with a length of *len plus one or more bytes.
Platform implementation
Win32 GetFinalPathNameByHandle()
Linux readlink(), lstat()
FreeBSD readlink(), lstat()
OS X readlink(), lstat()
CAFE Returns ENOTSUP.
CTR Returns ENOTSUP.

◆ nlib_realloc()

nlib_realloc ( void *  ptr,
size_t  size 
)

A weak function that calls the C standard function realloc. nlib calls realloc via this function.

Parameters
[in]ptrPointer to the memory block allocated ahead of time.
[in]sizeThe new size, in bytes.
Returns
The pointer to the allocated region.
Description
With the exception of the Cygwin version, this function can be overridden by the user program. Overriding this function is a way to customize nlib memory allocation.
If you are going to override the function, do not forget to code for C linkage using something like the following.
extern "C" void* nlib_realloc(void* ptr, size_t size) {
.....
}
Bug:
With the Cygwin version, the user program cannot override the function.
Examples:
heap/replace_malloc/replace_malloc.cpp.

◆ nlib_rename()

nlib_rename ( const char *  old_path,
const char *  new_path 
)

Renames a file.

Parameters
[in]old_pathA path name (UTF-8).
[in]new_pathA path name (UTF-8).
Return values
0Success.
EINVALIndicates that old_path and new_path were NULL.
ENOENTNo old_path exists.
EEXISTnew_path already exists.
ENOTEMPTYThe same as EEXIST.
EISDIRnew_path is a directory, but new_path is not a directory. EEXIST may be returned.
OtherFailed for some reason.
Description
Platform Implementation
Win32 MoveFileW()
Linux rename()
FreeBSD rename()
OS X rename()
CAFE FSRename()
CTR nn::fs::TryRenameFile() / nn::fs::TryRenameDirectory()
Note
For CTR, this function returns ENOENT when it should return EEXIST or EISDIR in other cases.
In Linux and similar platforms, this function replaces a file without returning EEXIST.

◆ nlib_rmdir()

nlib_rmdir ( const char *  native_path)

Deletes a directory.

Parameters
[in]native_pathThe path name (UTF-8).
Return values
0Success.
EINVALnative_path was set to NULL.
ENOENTNo native_path exists.
EEXISTThe directory is not empty.
ENOTEMPTYThe same as EEXIST.
ENOTDIRnative_path was not a directory.
OtherFailed for some reason.
Description
Platform Implementation
Win32 RemoveDirectoryW()
Linux rmdir()
FreeBSD rmdir()
OS X rmdir()
CAFE nlib_unlink()
CTR nn::fs::TryDeleteDirectory()

◆ nlib_rwlock_destroy()

nlib_rwlock_destroy ( nlib_rwlock rwlock)

Destroys a read-write lock object.

Parameters
[in]rwlockA read-write lock object.
Return values
0Success.
EINVALrwlock is set to NULL.
Description
Platform Implementation
Win32 Does nothing.
Linux pthread_rwlock_destroy()
FreeBSD pthread_rwlock_destroy()
OS X pthread_rwlock_destroy()
CAFE Implemented by nlib.
CTR Implemented by nlib.

◆ nlib_rwlock_init()

nlib_rwlock_init ( nlib_rwlock rwlock)

Initializes a read-write lock object.

Parameters
[in]rwlockA read-write lock object.
Return values
0Success.
EINVALrwlock is set to NULL.
Description
Platform Implementation
Win32 InitializeSRWLock()
Linux pthread_rwlock_init()
FreeBSD pthread_rwlock_init()
OS X pthread_rwlock_init()
CAFE Implemented by nlib.
CTR Implemented by nlib.

◆ nlib_rwlock_rdlock()

nlib_rwlock_rdlock ( nlib_rwlock rwlock)

Gets the read lock, and enters the critical section. Blocks until it can get a lock.

Parameters
[in]rwlockA read-write lock object.
Return values
0Success.
EINVALrwlock is set to NULL.
OtherAn implementation-dependent error.
Description
Platform Implementation
Win32 AcquireSRWLockShared()
Linux pthread_rwlock_rdlock()
FreeBSD pthread_rwlock_rdlock()
OS X pthread_rwlock_rdlock()
CAFE Implemented by nlib.
CTR Implemented by nlib.

◆ nlib_rwlock_rdunlock()

nlib_rwlock_rdunlock ( nlib_rwlock rwlock)

Releases the read lock.

Parameters
[in]rwlockA read-write lock object.
Return values
0Success.
EINVALrwlock is set to NULL.
OtherAn implementation-dependent error.
Description
Platform Implementation
Win32 ReleaseSRWLockShared()
Linux pthread_rwlock_unlock()
FreeBSD pthread_rwlock_unlock()
OS X pthread_rwlock_unlock()
CAFE Implemented by nlib.
CTR Implemented by nlib.

◆ nlib_rwlock_tryrdlock()

nlib_rwlock_tryrdlock ( nlib_rwlock rwlock)

Gets the read lock, and attempts to enter the critical section.

Parameters
[in]rwlockA read-write lock object.
Return values
0Success.
EINVALrwlock is set to NULL.
EBUSYCould not get the lock.
OtherAn implementation-dependent error.
Description
Platform Implementation
Win32 TryAcquireSRWLockShared()
Linux pthread_rwlock_tryrdlock()
FreeBSD pthread_rwlock_tryrdlock()
OS X pthread_rwlock_tryrdlock()
CAFE Implemented by nlib.
CTR Implemented by nlib.

◆ nlib_rwlock_tryrdlock_for()

nlib_rwlock_tryrdlock_for ( nlib_rwlock rwlock,
nlib_duration  duration 
)

Gets the read lock, and attempts to enter the critical section. Times out.

Parameters
[in]rwlockA read-write lock object.
[in]durationThe length of time for the timeout.
Return values
0Success.
EINVALrwlock is set to NULL.
ETIMEDOUTIndicates a timeout.
OtherAn implementation-dependent error.
Description
Platform Implementation
Win32 TryAcquireSRWLockShared(), nlib_sleep()
Linux pthread_rwlock_timedrdlock()
FreeBSD pthread_rwlock_timedrdlock()
OS X nlib_rwlock_tryrdlock(), nlib_sleep()
CAFE Implemented by nlib.
CTR Implemented by nlib.

◆ nlib_rwlock_tryrdlock_until()

nlib_rwlock_tryrdlock_until ( nlib_rwlock rwlock,
nlib_time  abstime 
)

Gets the read lock, and attempts to enter the critical section. Times out.

Parameters
[in]rwlockA read-write lock object.
[in]abstimeThe time when the timeout occurs.
Return values
0Success.
EINVALrwlock is set to NULL.
ETIMEDOUTIndicates a timeout.
OtherAn implementation-dependent error.
Description
Platform Implementation
Win32 TryAcquireSRWLockShared() and sleep.
Linux pthread_rwlock_timedrdlock()
FreeBSD pthread_rwlock_timedrdlock()
OS X nlib_rwlock_tryrdlock(), nlib_sleep()
CAFE Implemented by nlib.
CTR Implemented by nlib.

◆ nlib_rwlock_trywrlock()

nlib_rwlock_trywrlock ( nlib_rwlock rwlock)

Gets a write lock, and attempts to enter the critical section.

Parameters
[in]rwlockA read-write lock object.
Return values
0Success.
EINVALrwlock is set to NULL.
EBUSYCould not get the lock.
OtherAn implementation-dependent error.
Description
Platform Implementation
Win32 TryAcquireSRWLockExclusive()
Linux pthread_rwlock_trywrlock()
FreeBSD pthread_rwlock_trywrlock()
OS X pthread_rwlock_trywrlock()
CAFE Implemented by nlib.
CTR Implemented by nlib.

◆ nlib_rwlock_trywrlock_for()

nlib_rwlock_trywrlock_for ( nlib_rwlock rwlock,
nlib_duration  duration 
)

Gets a write lock, and attempts to enter the critical section. Times out.

Parameters
[in]rwlockA read-write lock object.
[in]durationThe length of time for the timeout.
Return values
0Success.
EINVALrwlock is set to NULL.
ETIMEDOUTIndicates a timeout.
OtherAn implementation-dependent error.
Description
Platform Implementation
Win32 TryAcquireSRWLockExclusive() and sleep.
Linux pthread_rwlock_timedwrlock()
FreeBSD pthread_rwlock_timedwrlock()
OS X nlib_rwlock_trywrlock(), nlib_sleep()
CAFE Implemented by nlib.
CTR Implemented by nlib.

◆ nlib_rwlock_trywrlock_until()

nlib_rwlock_trywrlock_until ( nlib_rwlock rwlock,
nlib_time  abstime 
)

Gets a write lock, and attempts to enter the critical section. Times out.

Parameters
[in]rwlockA read-write lock object.
[in]abstimeThe time when the timeout occurs.
Return values
0Success.
EINVALrwlock is set to NULL.
ETIMEDOUTIndicates a timeout.
OtherAn implementation-dependent error.
Description
Platform Implementation
Win32 TryAcquireSRWLockExclusive() and sleep.
Linux pthread_rwlock_timedwrlock()
FreeBSD pthread_rwlock_timedwrlock()
OS X nlib_rwlock_trywrlock(), nlib_sleep()
CAFE Implemented by nlib.
CTR Implemented by nlib.

◆ nlib_rwlock_wrlock()

nlib_rwlock_wrlock ( nlib_rwlock rwlock)

Gets a write lock, and enters the critical section. Blocks until it can get a lock.

Parameters
[in]rwlockA read-write lock object.
Return values
0Success.
EINVALrwlock is set to NULL.
OtherAn implementation-dependent error.
Description
Platform Implementation
Win32 AcquireSRWLockExclusive()
Linux pthread_rwlock_wrlock()
FreeBSD pthread_rwlock_wrlock()
OS X pthread_rwlock_wrlock()
CAFE Implemented by nlib.
CTR Implemented by nlib.

◆ nlib_rwlock_wrunlock()

nlib_rwlock_wrunlock ( nlib_rwlock rwlock)

Releases a write lock.

Parameters
[in]rwlockA read-write lock object.
Return values
0Success.
EINVALrwlock is set to NULL.
OtherAn implementation-dependent error.
Description
Platform Implementation
Win32 ReleaseSRWLockExclusive()
Linux pthread_rwlock_unlock()
FreeBSD pthread_rwlock_unlock()
OS X pthread_rwlock_unlock()
CAFE Implemented by nlib.
CTR Implemented by nlib.

◆ nlib_semaphore_destroy()

nlib_semaphore_destroy ( nlib_semaphore sem)

Destroys the semaphore count.

Parameters
[in]semPointer to the semaphore object.
Return values
0Success.
EINVALIndicates that sem is NULL.
OtherSome invalid state, such as a blocking thread, has been detected.
Description
Platform Implementation
Win32 CloseHandle()
Linux sem_destroy()
FreeBSD sem_destroy()
OS X sem_close(), sem_unlink()
CAFE No SDK API called.
CTR Semaphore::~Semaphore()

◆ nlib_semaphore_init()

nlib_semaphore_init ( nlib_semaphore sem,
int  initial_count 
)

Initializes the semaphore object specified by sem.

Parameters
[out]semPointer to the semaphore object.
[in]initial_countInitial value for the semaphore count.
Return values
0Success.
EINVALIndicates that sem is NULL or the value set for initial_count exceeds 65535.
Description
Platform Implementation
Win32 CreateSemaphore()
Linux sem_init()
FreeBSD sem_init()
OS X sem_open()
CAFE OSInitSemaphore()
CTR Semaphore::TryInitialize()

◆ nlib_semaphore_post()

nlib_semaphore_post ( nlib_semaphore sem,
int *  previous_count 
)

Increments the semaphore count by 1.

Parameters
[in]semPointer to the semaphore object.
[out]previous_countSemaphore count prior to release.
Return values
0Success.
EINVALIndicates that sem is NULL.
OtherThe semaphore count has reached the upper limit.
Description
Platform Implementation
Win32 ReleaseSemaphore()
Linux sem_post()
FreeBSD sem_post()
OS X sem_post()
CAFE OSSignalSemaphore()
CTR Semaphore::Release()

◆ nlib_semaphore_post_ex()

nlib_semaphore_post_ex ( nlib_semaphore sem,
int  release_count,
int *  previous_count 
)

Increments the semaphore count by the amount specified by releaseCount.

Parameters
[in]semPointer to the semaphore object.
[in]release_countNumber by which to increase the semaphore count.
[out]previous_countSemaphore count prior to release.
Return values
0Success.
EINVALIndicates that sem is NULL.
OtherThe semaphore count has reached the upper limit.
Description
Platform Implementation
Win32 ReleaseSemaphore()
Linux sem_post()
FreeBSD sem_post()
OS X sem_post()
CAFE OSSignalSemaphore()
CTR Semaphore::Release()
On the Linux, FreeBSD, and CAFE platforms, this operation is not atomic.

◆ nlib_semaphore_trywait()

nlib_semaphore_trywait ( nlib_semaphore sem)

Decrements the semaphore count by 1 if the count is not 0.

Parameters
[in]semPointer to the semaphore object.
Return values
0Success.
EAGAINThe semaphore count is 0.
EINVALIndicates that sem is NULL.
OtherFailed for some reason.
Description
Platform Implementation
Win32 WaitForSingleObject()
Linux sem_trywait() - If errno is EINTR, the function is executed again internally.
FreeBSD sem_trywait() - If errno is EINTR, the function is executed again internally.
OS X sem_trywait() - If errno is EINTR, the function is executed again internally.
CAFE OSTryWaitSemaphore()
CTR Semaphore::TryAcquire()

◆ nlib_semaphore_trywait_for()

nlib_semaphore_trywait_for ( nlib_semaphore sem,
nlib_duration  duration 
)

Decrements the semaphore count by 1 if the count is not 0. If 0, waits for the period specified by duration.

Parameters
[in]semPointer to the semaphore object.
[in]durationThe length of time for the timeout.
Return values
0Success.
ETIMEDOUTIndicates a timeout.
EINVALIndicates that sem is NULL.
OtherFailed for some reason.
Description
Platform Implementation
Win32 WaitForSingleObject()
Linux sem_timedwait() - If errno is EINTR, the function is executed again internally.
FreeBSD sem_timedwait() - If errno is EINTR, the function is executed again internally.
OS X nlib_semaphore_trywait(), nlib_sleep() - If errno is EINTR, the function is executed again internally.
CAFE OSTryWaitSemaphore()
CTR Semaphore::TryAcquire()
On the CAFE platform, tries again to get the semaphore after sleeping for 100 microseconds repeatedly.

◆ nlib_semaphore_wait()

nlib_semaphore_wait ( nlib_semaphore sem)

Waits until the semaphore count is no longer 0 and decrements the semaphore count by 1.

Parameters
[in]semPointer to the semaphore object.
Return values
0Success.
EINVALIndicates that sem is NULL.
OtherFailed for some reason.
Description
Platform Implementation
Win32 WaitForSingleObject()
Linux sem_wait() - If errno is EINTR, the function is executed again internally.
FreeBSD sem_wait() - If errno is EINTR, the function is executed again internally.
OS X sem_wait() - If errno is EINTR, the function is executed again internally.
CAFE OSWaitSemaphore()
CTR Semaphore::Acquire()

◆ nlib_skipws()

nlib_skipws ( size_t *  cnt_lf,
const char **  last_lf,
const char *  s,
size_t  n 
)

Searches a string made up of n characters and returns the pointer to the first character found that is not a white-space character.

Parameters
[in]cnt_lfStores the number of LF characters (0x0A) that were found.
[in]last_lfStores the pointer to the last LF characters (0x0A).
[in]sPointer to the string.
[in]nThe length of the target string.
Returns
The pointer to the first character that is not a white-space character. (If none found, returns s + n.)
Description
For this purpose, the white-space characters are HT (0x09), LF (0x0A), CR (0x0D), and SPC (0x20).
Platform Implementation
Win32 Implemented using SIMD.
Linux Implemented using SIMD.
FreeBSD Implemented using SIMD.
OS X Implemented using SIMD.
CAFE Implemented using the nlib_memchr_not function.
CTR Implemented using the nlib_memchr_not function.

◆ nlib_sleep()

nlib_sleep ( nlib_duration  t)

Sleeps for the duration of t.

Parameters
[in]tThe time to sleep.
Returns
Returns 0 on success.
Description
Platform Implementation
Win32 Sleep()
Linux nanosleep() - If errno is EINTR, the function is executed again internally.
FreeBSD nanosleep() - If errno is EINTR, the function is executed again internally.
OS X nanosleep() - If errno is EINTR, the function is executed again internally.
CAFE OSSleepNanoseconds()
CTR nn::os::Thread::Sleep()
Sample code
nlib_sleep(10000); // sleep for 1 msec

◆ nlib_spinlock_init()

static void nlib_spinlock_init ( nlib_spinlock lock)
inlinestatic

Initializes the spinlock.

Parameters
[in]lockSpinlock to be initialized.
Description
Platform Implementation
Win32 nlib independent implementation
Linux nlib independent implementation
FreeBSD nlib independent implementation
OS X Assigns 0
CAFE nlib independent implementation
CTR nlib independent implementation

Definition at line 1698 of file Platform.h.

◆ nlib_spinlock_lock()

static void nlib_spinlock_lock ( nlib_spinlock lock)
inlinestatic

Locks the spinlock. Behavior is undefined if a recursive lock is performed.

Parameters
[in]lockSpinlock to be locked.
Description
Platform Implementation
Win32 nlib independent implementation
Linux nlib independent implementation
FreeBSD nlib independent implementation
OS X OSSpinLockLock()
CAFE nlib independent implementation
CTR nlib independent implementation

Definition at line 1701 of file Platform.h.

◆ nlib_spinlock_trylock()

static errno_t nlib_spinlock_trylock ( nlib_spinlock lock)
inlinestatic

Locks the spinlock. Returns 0 if successful or EBUSY if fails.

Parameters
[in]lockSpinlock to be locked.
Return values
0Lock was successful.
EBUSYLock was unsuccessful.
Description
Platform Implementation
Win32 nlib independent implementation
Linux nlib independent implementation
FreeBSD nlib independent implementation
OS X OSSpinLockTry()
CAFE nlib independent implementation
CTR nlib independent implementation

Definition at line 1731 of file Platform.h.

◆ nlib_spinlock_unlock()

static void nlib_spinlock_unlock ( nlib_spinlock lock)
inlinestatic

Unlocks the spinlock.

Parameters
[in]lockSpinlock being locked.
Description
Platform Implementation
Win32 nlib independent implementation
Linux nlib independent implementation
FreeBSD nlib independent implementation
OS X OSSpinLockUnlock()
CAFE nlib independent implementation
CTR nlib independent implementation

Definition at line 1762 of file Platform.h.

◆ nlib_strchr()

nlib_strchr ( const char *  s,
int  c 
)

Searches for a character from the start of a string.

Parameters
[in]sThe string to search through.
[in]cThe character to search for.
Returns
Returns the pointer to the matching character, if found. If not found, returns NULL.
Description
Platform Implementation
Win32 Implemented using SIMD.
Linux Implemented using SIMD.
FreeBSD Implemented using SIMD.
OS X Implemented using SIMD.
CAFE Check in units of 32 bits.
CTR Check in units of 32 bits.

◆ nlib_strcplen()

nlib_strcplen ( size_t *  codepoint_count,
size_t *  supplementary_codepoint_count,
size_t *  len,
const nlib_utf8_t str 
)

Gets the number of code points contained in the string, the number of supplementary characters contained in the string, and the string length. If the function returns EILSEQ, a value, including the number of code points to the point that cannot be converted, is stored.

Parameters
[out]codepoint_countPointer that contains the number of code points.
[out]supplementary_codepoint_countPointer that contains the number of code points for supplementary characters (U+10000 - U+10FFFF).
[out]lenPointer that contains the string length.
[in]strString
Return values
0Success.
EINVALIndicates that str is NULL.
EILSEQIndicates that data that cannot be converted into a code point was detected.
The number of characters when the string is converted to UTF-32 will be *codepoint_count. Note that you can use the formula *codepoint_count + *supplementary_codepoint_count to calculate the number of characters when the string is converted to UTF-16.

◆ nlib_strcpy()

nlib_strcpy ( char *  s1,
size_t  s1max,
const char *  s2 
)

An implementation corresponding to N1078 strcpy_s.

Parameters
[in,out]s1The buffer to copy to.
[in]s1maxThe size (number of characters) of the buffer to copy to.
[in]s2The buffer to copy from.
Return values
0Success.
EINVALIndicates that s1 or s2 is NULL.
ERANGEThe buffer is not large enough.
Description
s1[0]=0 is set if the function fails and s1 is not NULL. The behavior is undefined if the buffers overlap.
Platform Implementation
Win32 nlib_strnlen() + nlib_memcpy()
Linux nlib_strnlen() + nlib_memcpy()
FreeBSD nlib_strnlen() + nlib_memcpy()
OS X nlib_strnlen() + nlib_memcpy()
CAFE nlib_strnlen() + nlib_memcpy()
CTR nlib_strnlen() + nlib_memcpy()

◆ nlib_strlen()

nlib_strlen ( const char *  s)

Internally calls strlen(). In some cases, it may operate as an independent implementation.

Parameters
[in]sPointer to the string.
Returns
The length of the string.
Description
Returns 0 if s is NULL.
Platform Implementation
Win32 Implemented using SIMD.
Linux Implemented using SIMD.
FreeBSD Implemented using SIMD.
OS X Implemented using SIMD.
CAFE Scan in units of words.
CTR Scan in units of words.
Examples:
exi/textparser/textparser.cpp.

◆ nlib_strncpy()

nlib_strncpy ( char *  s1,
size_t  s1max,
const char *  s2,
size_t  n 
)

An implementation corresponding to N1078 strncpy_s.

Parameters
[in,out]s1The buffer to copy to.
[in]s1maxThe size (number of characters) of the buffer to copy to.
[in]s2The buffer to copy from.
[in]nThe number of characters to copy.
Return values
0Success.
EINVALIndicates that s1 or s2 is NULL.
ERANGEThe buffer is not large enough.
Description
s1[0]=0 is set if the function fails and s1 is not NULL. The behavior is undefined if the buffers overlap.
Platform Implementation
Win32 nlib_strnlen() + nlib_memcpy()
Linux nlib_strnlen() + nlib_memcpy()
FreeBSD nlib_strnlen() + nlib_memcpy()
OS X nlib_strnlen() + nlib_memcpy()
CAFE nlib_strnlen() + nlib_memcpy()
CTR nlib_strnlen() + nlib_memcpy()

◆ nlib_strnlen()

nlib_strnlen ( const char *  s,
size_t  maxsize 
)

An implementation corresponding to N1078 strnlen_s.

Parameters
[in]sPointer to the string.
[in]maxsizeThe size of the string. (The maximum number for the return value.)
Returns
The length of the string.
Description
Returns 0 if s is NULL. Returns maxsize if the string is longer than maxsize.
Platform Implementation
Win32 Implemented using SIMD.
Linux Implemented using SIMD.
FreeBSD Implemented using SIMD.
OS X Implemented using SIMD.
CAFE Scan in units of words.
CTR Scan in units of words.

◆ nlib_strrchr()

nlib_strrchr ( const char *  s,
int  c 
)

Searches for a character from the end of a string.

Parameters
[in]sThe string to search through.
[in]cThe character to search for.
Returns
Returns the pointer to the matching character, if found. If not found, returns NULL.
Description
Platform Implementation
Win32 strrchr()
Linux Implemented using SIMD.
FreeBSD Implemented using SIMD.
OS X Implemented using SIMD.
CAFE nlib_strlen, plus check backwards in units of 32 bits.
CTR nlib_strlen, plus check backwards in units of 32 bits.

◆ nlib_strto_int32()

nlib_strto_int32 ( int32_t *  result,
const char *  nptr,
char **  endptr,
int  base 
)

Converts a string to the int32_t type.

Parameters
[out]resultThe number of read characters (not including null characters).
[in]nptrThe string to be converted.
[out]endptrThe pointer to the first character that cannot be converted is stored.
[in]baseA cardinal number (0, 8, 10, and 16 are supported at the minimum.)
Return values
0Success.
ERANGEThe result value is out of the range of int32_t. *result is already set.
EILSEQThe value was not read.
EINVALConversion with the given base is not supported.
Description
Operates in the same way as strtol() except the following:
  • errno does not need to be set to 0 in advance.
  • The value to be set is a value of the int32_t type.
  • If a null string is read, the function returns EILSEQ.
  • If the specified string starts with a white-space character, the function returns EILSEQ.
  • When endptr is NULL, if the string cannot be converted completely to its end, the function returns EILSEQ.
Examples:
exi/script/script.cpp, and exi/simple1/simple1.cpp.

◆ nlib_swapendian_16()

nlib_swapendian_16 ( uint16_t *  p,
size_t  count 
)

Swaps the endianness.

Parameters
[in,out]pThe region that the endian is swapped for.
[in]countThe amount of data.
Return values
0Success.
EINVALIndicates that p is NULL.
Description
Platform Implementation
Win32 Implemented using SIMD.
Linux Implemented using SIMD.
FreeBSD Implemented using SIMD.
OS X Implemented using SIMD.
CAFE Normal implementation.
CTR Normal implementation.

◆ nlib_swapendian_32()

nlib_swapendian_32 ( uint32_t *  p,
size_t  count 
)

Swaps the endianness.

Parameters
[in,out]pThe region that the endian is swapped for.
[in]countThe amount of data.
Return values
0Success.
EINVALIndicates that p is NULL.
Description
Platform Implementation
Win32 Implemented using SIMD.
Linux Implemented using SIMD.
FreeBSD Implemented using SIMD.
OS X Implemented using SIMD.
CAFE Normal implementation.
CTR Normal implementation.

◆ nlib_swapendian_64()

nlib_swapendian_64 ( uint64_t *  p,
size_t  count 
)

Swaps the endianness.

Parameters
[in,out]pThe region that the endian is swapped for.
[in]countThe amount of data.
Return values
0Success.
EINVALIndicates that p is NULL.
Description
Platform Implementation
Win32 Implemented using SIMD.
Linux Implemented using SIMD.
FreeBSD Implemented using SIMD.
OS X Implemented using SIMD.
CAFE Normal implementation.
CTR Normal implementation.

◆ nlib_thread_attr_destroy()

nlib_thread_attr_destroy ( nlib_thread_attr attr)

Destroys a thread-initialization object.

Parameters
[out]attrThe object to destroy.
Return values
0Success.
EINVALattr was set to NULL.

◆ nlib_thread_attr_getint()

nlib_thread_attr_getint ( const nlib_thread_attr attr,
int  key,
int *  value 
)

Gets the integer corresponding to the key of the thread attribute object.

Parameters
[in]attrThread attribute.
[in]keyA key.
[out]valueHolds the value corresponding to the key.
Return values
0Success.
EINVALInvalid argument value.
Description
Platform Implementation
Win32 nlib independent implementation
Linux pthread_attr_getdetachstate(), pthread_attr_getstacksize(), pthread_attr_getschedparam(), pthread_attr_getaffinity_np()
FreeBSD pthread_attr_getdetachstate(), pthread_attr_getstacksize(), pthread_attr_getschedparam(), pthread_attr_getaffinity_np()
OS X pthread_attr_getdetachstate(), pthread_attr_getstacksize(), pthread_attr_getschedparam()
CAFE nlib independent implementation
CTR nlib independent implementation

◆ nlib_thread_attr_getptr()

nlib_thread_attr_getptr ( const nlib_thread_attr attr,
int  key,
void **  value 
)

Gets the pointer corresponding to the key of the thread attribute object. As of now, returns EINVAL only.

Parameters
[in]attrThread attribute.
[in]keyA key.
[out]valueHolds the value corresponding to the key.
Return values
0Success.
EINVALInvalid argument value.

◆ nlib_thread_attr_getstack()

nlib_thread_attr_getstack ( const nlib_thread_attr attr,
void **  stack_addr,
size_t *  stack_size 
)

Obtains a stack setting for thread attribute objects.

Parameters
[in]attrThread attribute.
[out]stack_addrStack address.
[out]stack_sizeStack size.
Returns
Returns 0 on success. The error value depends on the platform.
Description
Platform Implementation
Win32 nlib independent implementation
Linux pthread_attr_getstack()
FreeBSD pthread_attr_getstack()
OS X pthread_attr_getstack()
CAFE nlib independent implementation
CTR nlib independent implementation

◆ nlib_thread_attr_init()

nlib_thread_attr_init ( nlib_thread_attr attr)

Initializes a thread attribute object and sets it to the default.

Parameters
[out]attrThe attribute being initialized.
Return values
0Success.
EINVALattr was set to NULL.

◆ nlib_thread_attr_setint()

nlib_thread_attr_setint ( nlib_thread_attr attr,
int  key,
int  value 
)

Sets an integer corresponding to the key of the thread attribute object.

Parameters
[out]attrThe thread attribute.
[in]keyA key.
[in]valueThe value being set.
Return values
0Success.
EINVALInvalid argument value.
Description
Key Description
NLIB_THREAD_ATTR_KEY_DETACHSTATE If non-zero, starts the thread in the detached state.
NLIB_THREAD_ATTR_KEY_STACKSIZE The size of the thread stack.
NLIB_THREAD_ATTR_KEY_PRIORITY Thread priority.
NLIB_THREAD_ATTR_KEY_PRIORITY Thread affinity mask.
NLIB_THREAD_ATTR_KEY_EXPLICIT_SCHED If non-zero, enables the NLIB_THREAD_ATTR_KEY_PRIORITY setting.
Platform Implementation
Win32 Detaches immediately after the thread is started, _beginthreadex(), sets immediately after the thread is started, sets immediately after the thread is started.
Linux pthread_attr_setdetachstate(), pthread_attr_setstacksize(), pthread_attr_setschedparam(), pthread_attr_setaffinity_np()
FreeBSD pthread_attr_setdetachstate(), pthread_attr_setstacksize(), pthread_attr_setschedparam(), pthread_attr_setaffinity_np()
OS X pthread_attr_setdetachstate(), pthread_attr_setstacksize(), pthread_attr_setschedparam(), sets immediately after the thread is started.
CAFE OSCreateThread(), OSCreateThread(), OSCreateThread(), OSCreateThread()
CTR Detaches immediately after the thread is started, nn::os::Thread::TryStartUsingAutoStack(), nn::os::Thread::TryStartUsingAutoStack(), none

◆ nlib_thread_attr_setptr()

nlib_thread_attr_setptr ( nlib_thread_attr attr,
int  key,
void *  value 
)

Sets a pointer corresponding to the key of the thread attribute object. As of now, returns EINVAL only.

Parameters
[out]attrThe thread attribute.
[in]keyA key.
[in]valueThe value being set.
Return values
0Success.
EINVALInvalid argument value.

◆ nlib_thread_attr_setstack()

nlib_thread_attr_setstack ( nlib_thread_attr attr,
void *  stack_addr,
size_t  stack_size 
)

Sets a stack setting for thread attribute objects.

Parameters
[out]attrThe thread attribute.
[in]stack_addrStack address.
[in]stack_sizeStack size.
Returns
Returns 0 on success. The error value depends on the platform.
Description
Platform Implementation
Win32 nlib independent implementation (The set value is ignored)
Linux pthread_attr_getstack()
FreeBSD pthread_attr_getstack()
OS X pthread_attr_getstack()
CAFE nlib independent implementation
CTR nlib independent implementation

◆ nlib_thread_cleanup_pop()

nlib_thread_cleanup_pop ( int  exec)

Deletes the handler at the top of the stack storing the cleanup handler.

Parameters
[in]execRuns a cleanup handler if not 0. Does not run the handler if 0.
Description
Platform Implementation
Win32 nlib independent implementation
Linux pthread_cleanup_pop()
FreeBSD pthread_cleanup_pop()
OS X pthread_cleanup_pop()
CAFE nlib independent implementation
CTR No implementation found (compiler error).

◆ nlib_thread_cleanup_push()

nlib_thread_cleanup_push ( void(*)(void *)  fn,
void *  arg 
)

Pushes fn to a dedicated stack.

Parameters
[in]fn
[in]arg
Description
Pushes the cleanup handler run when nlib_thread_exit() is executed to a dedicated stack. If nlib_thread_exit() (not nlib_thread_exit_cpp()) is called before nlib_thread_cleanup_pop() is executed, handlers are run one by one and the finalization of the thread is performed. Note that when leaving a thread through execution of a return statement, no cleanup handler will be run. In addition, whether a handler is run or not when using a C++ exception is undefined (dependent of the platform), and the behavior when calling nlib_thread_exit() or nlib_thred_exit_cpp() inside the cleanup handler is undefined.
Platform Implementation
Win32 nlib independent implementation
Linux pthread_cleanup_push()
FreeBSD pthread_cleanup_push()
OS X pthread_cleanup_push()
CAFE nlib independent implementation
CTR No implementation found (compiler error).

◆ nlib_thread_create()

nlib_thread_create ( nlib_thread thread,
const nlib_thread_attr attr,
nlib_thread_func  func,
void *  arg 
)

Creates and executes a new thread.

Parameters
[out]threadIf a thread has been created successfully, this parameter stores the data indicating that thread.
[in]attrIf NULL is specified, the default attribute is set.
[in]funcThe function to run on the new thread.
[in]argThe argument to pass to function func.
Return values
0Success.
EINVALIndicates that thread or func was NULL, or some other parameter was deemed invalid.
ENOMEMDynamic allocation of memory has failed.
EAGAINThread could not be started due to insufficient resources (too many threads, insufficient memory, etc.).
EACCESThread could not be started due to insufficient resources (too many threads, insufficient memory, etc.).
Description
The new thread executes the function func with the argument arg. By default, the thread is created as a joinable thread.
Examples:
exi/multithread/multithread.cpp, heap/cachedheap/cachedheap.cpp, heap/object_tracking/object_tracking.cpp, and msgpack/jsonrpc/jsonrpc.cpp.

◆ nlib_thread_detach()

nlib_thread_detach ( nlib_thread  thread)

Detaches an executing thread.

Parameters
[in]threadThe thread identifier.
Return values
0Success.
EINVALThe thread could not be found but will be detached.
ESRCHThe thread could not be found but will be detached.
Description
Platform Implementation
Win32 CloseHandle()
Linux pthread_detach()
FreeBSD pthread_detach()
OS X pthread_detach()
CAFE OSDetachThread()
CTR Thread::Detach()
Examples:
exi/multithread/multithread.cpp, and heap/cachedheap/cachedheap.cpp.

◆ nlib_thread_equal()

nlib_thread_equal ( nlib_thread  th1,
nlib_thread  th2 
)

Checks whether two threads point to the same thread.

Parameters
[in]th1A nlib_thread-type value to compare.
[in]th2A nlib_thread-type value to compare.
Returns
If th1 and th2 refer to the same thread, the function returns a non-zero value. Otherwise, it returns 0.

◆ nlib_thread_getconcurrency()

nlib_thread_getconcurrency ( unsigned int *  num_cpu)

Gets the number of hardware threads.

Parameters
[out]num_cpuSets the number of hardware threads.
Return values
0Success.
Description
Platform Implementation
Win32 GetSystemInfo(&sysinfo); sysinfo.dwNumberOfProcessors
Linux sysconf(_SC_NPROCESSORS_ONLN)
FreeBSD sysconf(_SC_NPROCESSORS_ONLN)
OS X sysconf(_SC_NPROCESSORS_ONLN)
CAFE OSGetCoreCount()
CTR 1

◆ nlib_thread_getcpu()

nlib_thread_getcpu ( int *  cpuid)

Gets the CPU on which the called thread is executing.

Parameters
[out]cpuidThe CPU number.
Returns
Returns 0 if there is no error. Returns EINVAL if cpuid is NULL.
Description
If an error occurs, sets *cpuid to 0 and returns an error.
Platform Implementation
Win32(VISTA)GetCurrentProcessorNumber()
Win32(Windows 7 and later)GetCurrentProcessorNumberEx()
Linux sched_getcpu(), (GetCurrentProcessorNumber() if cygwin)
FreeBSD Set 0 and return ENOTSUP.
OS X Set 0 and return ENOTSUP.
CAFE OSGetCoreId()
CTR nn::os::Thread::GetCurrentProcessorNumber()

◆ nlib_thread_getid()

nlib_thread_getid ( nlib_thread_id id)

Stores a unique integer value corresponding to the executing thread.

Parameters
[out]idStores the integer value corresponding to the thread.
Return values
0Success.
Description
Platform Implementation
Win32 GetCurrentThreadId()
Linux syscall(SYS_gettid), (GetCurrentThreadId() if cygwin)
FreeBSD thr_self()
OS X pthread_threadid_np()
CAFE OSGetCurrentThread()
CTR nn::os::Thread::GetCurrentId()
Examples:
exi/multithread/multithread.cpp, and misc/threading/callonce/callonce.cpp.

◆ nlib_thread_getname()

nlib_thread_getname ( nlib_thread  thread,
char *  name,
size_t  len 
)

Gets the thread name.

Parameters
[in]threadThe thread identifier.
[out]nameThe buffer that stores the thread name.
[in]lenThe length of the name buffer.
Returns
Returns 0 on success.
Description
Platform implementation
Win32 Returns ENOTSUP.
Linux pthread_getname_np(). If cygwin, returns ENOTSUP.
FreeBSD Returns ENOTSUP.
OS X pthread_getname_np()
CAFE OSGetThreadName()
CTR Returns ENOTSUP.

◆ nlib_thread_getpriority()

nlib_thread_getpriority ( nlib_thread  thread,
int *  priority 
)

Gets the current execution priority of the thread. The meaning of the numerical value is implementation-dependent.

Parameters
[in]threadThe thread identifier.
[out]priorityStores the execution priority.
Return values
0Success.
EINVALpriority was set to NULL.
ESRCHIndicates that thread is invalid. (In some cases, EINVAL is returned.)
Description
Platform Implementation
Win32 GetThreadPriority()
Linux pthread_getschedparam()
FreeBSD pthread_getschedparam()
OS X pthread_getschedparam()
CAFE OSGetThreadPriority()
CTR Thread::GetCurrentPriority()

◆ nlib_thread_join()

nlib_thread_join ( nlib_thread  thread)

Waits for the thread to terminate.

Parameters
[in]threadThe identifier for the thread to wait to terminate.
Return values
0Success.
EINVALThe thread could not be found but will be detached.
ESRCHThe thread could not be found but will be detached.
Description
Platform Implementation
Win32 WaitForSingleObject() + CloseHandle()
Linux pthread_join()
FreeBSD pthread_join()
OS X pthread_join()
CAFE OSJoinThread()
CTR Thread::Join()
Examples:
exi/multithread/multithread.cpp, heap/cachedheap/cachedheap.cpp, heap/object_tracking/object_tracking.cpp, and msgpack/jsonrpc/jsonrpc.cpp.

◆ nlib_thread_priority_default()

nlib_thread_priority_default ( int *  priority)

Gets the default numerical value that can be specified for the execution priority.

Parameters
[out]priorityThe execution priority.
Return values
0Success.
Description
Platform Implementation
Win32 THREAD_PRIORITY_NORMAL
Linux 0
FreeBSD 0
OS X 0
CAFE OS_PRIORITY_APP_DEFAULT
CTR 16

◆ nlib_thread_priority_max()

nlib_thread_priority_max ( int *  priority)

Gets the largest numerical value that can be specified for the execution priority.

Parameters
[out]priorityThe execution priority.
Return values
0Success.
Description
Platform Implementation
Win32 THREAD_BASE_PRIORITY_LOWRT
Linux sched_get_priority_max(SCHED_OTHER)
FreeBSD sched_get_priority_max(SCHED_OTHER)
OS X sched_get_priority_max(SCHED_OTHER)
CAFE 31
CTR 31

◆ nlib_thread_priority_min()

nlib_thread_priority_min ( int *  priority)

Gets the smallest numerical value that can be specified for the execution priority.

Parameters
[out]priorityThe execution priority.
Return values
0Success.
Description
Platform Implementation
Win32 THREAD_BASE_PRIORITY_IDLE
Linux sched_get_priority_min(SCHED_OTHER)
FreeBSD sched_get_priority_min(SCHED_OTHER)
OS X sched_get_priority_min(SCHED_OTHER)
CAFE 0
CTR 0

◆ nlib_thread_self()

nlib_thread_self ( nlib_thread thread)

Stores the nlib_thread value corresponding to the executing thread.

Parameters
[out]threadThe thread identifier.
Return values
0Success.
Description
Platform Implementation
Win32 GetCurrentThread()
Linux pthread_self()
FreeBSD pthread_self()
OS X pthread_self()
CAFE OSGetCurrentThread()
CTR Returns ENOTSUP.
Note that this function is not supported on the CTR platform, and for Win32 returns a pseudo-handle.

◆ nlib_thread_setaffinity()

nlib_thread_setaffinity ( nlib_thread  thread,
uint32_t  affinity 
)

Sets a processor affinity mask for the specified thread.

Parameters
[in]threadThe thread identifier.
[in]affinityThread affinity mask.
Returns
Returns 0 on success.
Description
For the Cygwin and Linux versions, thread must specify its own thread. Linux does not support getting any tid other than the thread's own tid (that is, the tid for any thread that is not pthread_t). The function returns EINVAL if another thread has been specified.
Platform Implementation
Win32 SetThreadAffinityMask()
Linux pthread_setaffinity_np(), (SetThreadAffinityMask() if cygwin)
FreeBSD pthread_setaffinity_np()
OS X thread_policy_set()
CAFE OSSuspendThread(), OSSetThreadAffinity(), and OSResumeThread(). 1, 2 and 4 correspond respectively to core 0, core 1 and core 2. Setting for a thread of its own is not allowed.
CTR Returns ENOTSUP.

◆ nlib_thread_setname()

nlib_thread_setname ( nlib_thread  thread,
const char *  name 
)

Attaches a name to the thread.

Parameters
[in]threadThe thread identifier.
[in]nameThread name.
Returns
Returns 0 on success.
Description
On some platforms, you can name only the thread now you are working with. In that case, if you attempt to name a different thread, the function returns ENOTSUP.
Platform Implementation
Win32 RaiseException(MS_VC_EXCEPTION, ....)
Linux pthread_setname_np(). If cygwin, returns ENOTSUP.
FreeBSD pthread_set_name_np()
OS X pthread_setname_np()
CAFE OSSetThreadName()
CTR Returns ENOTSUP.

◆ nlib_thread_setpriority()

nlib_thread_setpriority ( nlib_thread  thread,
int  priority 
)

Sets the execution priority of the thread. The meaning of the numerical value is implementation-dependent.

Parameters
[in]threadThe thread identifier.
[in]priorityThe execution priority to set.
Return values
0Success.
EINVALIndicates that priority was NULL or an invalid value.
ESRCHIndicates that thread is invalid. (In some cases, EINVAL is returned.)
OtherIndicates that the parameter could not be set for some reason, such as a lack of permission.
Description
Platform Implementation
Win32 SetThreadPriority()
Linux pthread_setschedparam()
FreeBSD pthread_setschedparam()
OS X pthread_setschedparam()
CAFE OSSetThreadPriority()
CTR Thread::ChangePriority()

◆ nlib_ticktime()

nlib_ticktime ( nlib_duration t)

Gets the elapsed time since the system was last started.

Parameters
[out]tPointer to where the elapsed time since the system started is stored.
Return values
0Success.
EINVALIndicates that t is NULL.
Description
Platform Implementation
Win32 QueryPerformanceCounter()
Linux clock_gettime(CLOCK_MONOTONIC, ...)
FreeBSD clock_gettime(CLOCK_MONOTONIC, ...)
OS X host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock), clock_get_time(cclock, &mts)
CAFE OSGetSystemTime()
CTR nn::os::Tick::GetSystemCurrent()

◆ nlib_timer_create()

nlib_timer_create ( nlib_timer timer,
nlib_timer_callback  callback,
void *  param,
uint32_t  flags 
)

Creates a timer.

Parameters
[out]timerStores the timer identifier.
[in]callbackThe callback function to run.
[in]paramThe argument to be passed to the callback function.
[in]flagsA value of 0 or the result given by ORring the following values.
Value Description
NLIB_TIMER_SHORTTERM_TASK Runs the callback function on the timer thread itself.
NLIB_TIMER_LONGTERM_TASK Suggests to the system that the callback function may need long time to complete its execution.
Return values
0Success.
EINVALTimer is NULL.
ENOMEMmemory allocation failed.
Others.Varies depending on the internal implementation.
Description
Creates a timer and stores its identifier in timer. Though the callback function is executed on a new thread or a worker thread from the thread pool by default, specifying NLIB_TIMER_SHORTTERM_TASK for flags allows it to be executed on the timer thread itself. As doing so causes execution of other callback functions will be delayed, apply it only for a callback function that can be completed within a short duration. Specify NLIB_TIMER_LONGTERM_TASK to suggest to the system that the callback function needs a long time to complete its execution.
Platform implementation
Win32 CreateTimerQueueTimer()
Linux an implementation specific to nlib
FreeBSD an implementation specific to nlib
OS X an implementation specific to nlib
CAFE an implementation specific to nlib
CTR an implementation specific to nlib

◆ nlib_timer_delete()

nlib_timer_delete ( nlib_timer  timer,
int  wait_completion,
nlib_timer_callback  completion_callback 
)

Deletes a timer.

Parameters
[in]timerThe identifier of the timer.
[in]wait_completionIf non-zero, blocks until all the callback functions of the timer have completed their execution.
[in]completion_callbackIf not NULL, called after all the callback functions of the timer have completed their execution.
Return values
0Success.
EBADFThe identifier of the timer is not valid.
Description
If wait_completion is set to a non-zero value, blocks until all the callback functions for the timer have completed their execution (Specify 0 to use the timer within the callback function). This operation allows the resources used by the callback functions to be securely freed. In addition, if a function is specified in completion_callback, that function is called after all the callback functions of the timer have completed their execution.
Description
Platform implementation
Win32 DeleteTimerQueueTimer()
Linux an implementation specific to nlib
FreeBSD an implementation specific to nlib
OS X an implementation specific to nlib
CAFE an implementation specific to nlib
CTR an implementation specific to nlib

◆ nlib_timer_gettime()

nlib_timer_gettime ( nlib_timer  timer,
nlib_timerspec curr_value 
)

Obtains the current timer settings.

Parameters
[in]timerThe identifier of the timer.
[out]curr_valueThe current settings are stored.
Return values
0Success.
EBADFThe identifier of the timer is not valid.
EINVALThe curr_value is NULL.

◆ nlib_timer_settime()

nlib_timer_settime ( nlib_timer  timer,
const nlib_timerspec new_value,
nlib_timerspec old_value 
)

Starts or suspends the timer.

Parameters
[in]timerThe identifier of the timer.
[in]new_valueA new setting
[out]old_valueIf not NULL, the previous setting is stored.
Return values
0Success.
EBADFThe identifier of the timer is not valid.
EINVALnew_value is NULL or the new value field value is a negative value.
Description
The nlib_timerspec structure is defined as described below:
struct nlib_timerspec_ {
nlib_duration due_time;
nlib_duration interval;
};
typedef struct nlib_timerspec_ nlib_timerspec;
due_time specifies the time that elapses before the initial startup of the timer and interval specifies the iteration interval of the startup after the initial one. Setting zero for both due_time and interval suspends the timer. Setting zero only for interval starts the timer just once and the startup never iterates. This function can be called from a callback function of the timer.
The counting of the running interval for a callback function starts when the function starts running. Therefore, note that multiple callback functions may simultaneously run if any of those functions needs long time to complete its execution. To ensure that no callback functions simultaneously run, call this function with interval set to zero and call this function again at the end of the callback function to set the next startup.
Platform implementation
Win32 ChangeTimerQueueTimer()
Linux an implementation specific to nlib
FreeBSD an implementation specific to nlib
OS X an implementation specific to nlib
CAFE an implementation specific to nlib
CTR an implementation specific to nlib

◆ nlib_tls_alloc()

nlib_tls_alloc ( nlib_tls tls,
nlib_tls_destructor  destr 
)

Allocates a new ID for the specified TLS slot.

Parameters
[out]tlsPointer to where the TLS slot ID is stored.
[in]destrThe destructor function to call when the thread ends.
Return values
0Success.
EINVALIndicates that tls is NULL.
EAGAINIndicates that there are insufficient resources to allocate a TLS slot, or that the number of TLS slots has reached the limit for the system.
Description
In the destr function, behavior is undefined if nlib_tls_alloc() is called.
Platform Implementation
Win32 TlsAlloc()+
Linux pthread_key_create()
FreeBSD pthread_key_create()
OS X pthread_key_create()
CAFE No SDK API called.
CTR nn::os::ThreadLocalStorage
Bug:
If you set a value by using lib_tls_setvalue() in a destructor function, two implementations are available: an implementation in which the destructor function is called multiple times and another implementation in which it is called once. Note that, in cygwin and CTR, the destructor function is called only once as of now. The condition described above may cause memory leaks.
Examples:
heap/gameheap/gameheap.cpp.

◆ nlib_tls_free()

nlib_tls_free ( nlib_tls  tls)

Frees the ID corresponding to the TLS slot.

Parameters
[in]tlsThe ID to free.
Return values
0Success.
EINVALIndicates that tls is not a valid ID.
Description
If the specified TLS slot is being used, the behavior when calling this destructor is not guaranteed.
Platform Implementation
Win32 TlsFree()
Linux pthread_key_delete()
FreeBSD pthread_key_delete()
OS X pthread_key_delete()
CAFE No SDK API called.
CTR ThreadLocalStorage::~ThreadLocalStorage()

◆ nlib_tls_getvalue()

nlib_tls_getvalue ( nlib_tls  tls,
void **  value 
)

Gets the value from a TLS slot.

Parameters
[in]tlsThe ID of the TLS slot.
[out]valueThe pointer for getting the stored value.
Return values
0Success.
EINVALIndicates that tls is not a valid ID.
Description
Platform Implementation
Win32 TlsGetValue()
Linux pthread_getspecific()
FreeBSD pthread_getspecific()
OS X pthread_getspecific()
CAFE OSGetThreadSpecific()
CTR ThreadLocalStorage::GetValue()
Examples:
heap/gameheap/gameheap.cpp.

◆ nlib_tls_setvalue()

nlib_tls_setvalue ( nlib_tls  tls,
const void *  value 
)

Stores a value in a TLS slot.

Parameters
[in]tlsThe ID of the TLS slot.
[in]valueThe value to set.
Return values
0Success.
EINVALIndicates that tls is not a valid ID.
Description
Platform Implementation
Win32 TlsSetValue()
Linux pthread_setspecific()
FreeBSD pthread_setspecific()
OS X pthread_setspecific()
CAFE OSSetThreadSpecific() + OSSetThreadCleanupCallback()
CTR ThreadLocalStorage::SetValue()
Examples:
heap/gameheap/gameheap.cpp.

◆ nlib_unlink()

nlib_unlink ( const char *  native_path)

Deletes a file.

Parameters
[in]native_pathThe path name (UTF-8).
Return values
0Success.
EINVALnative_path was set to NULL.
ENOENTNo native_path exists.
EISDIRnative_path was a directory.
OtherFailed for some reason.
Description
Platform Implementation
Win32 DeleteFileW()
Linux unlink()
FreeBSD unlink()
OS X unlink()
CAFE FSRemove()
CTR nn::fs::TryDeleteFile()

◆ nlib_utf16_to_utf32char()

nlib_utf16_to_utf32char ( nlib_utf32_t utf32,
nlib_utf16_t  upper,
nlib_utf16_t  lower 
)

Converts a single code point from UTF-16 into UTF-32.

Parameters
[out]utf32Stores a UTF-32 character.
[in]upperThe first 16 bits of UTF-16.
[in]lowerThe 16 bits subsequent to upper.
Return values
0Conversion was not possible.
1Only upper was converted to UTF-32.
2Indicates that upper and lower were combined and converted to UTF-32.

◆ nlib_utf16_to_utf8()

nlib_utf16_to_utf8 ( size_t *  utf8count,
nlib_utf8_t utf8,
size_t  buflen,
const nlib_utf16_t utf16 
)

Converts a UTF-16 string into a UTF-8 string.

Parameters
[out]utf8countStores the number of converted characters (the number of char, not including the null character).
[out]utf8The buffer for storing the converted string.
[in]buflenThe size of the utf8 buffer (the number of characters including the null character).
[in]utf16A UTF-16 string.
Return values
0No error occurred.
EINVALIndicates that either utf8 is NULL and buflen > 0, or utf16 is NULL.
ERANGEThe converted string was too big to fit, so it has been stored in truncated form.
EILSEQData that cannot be converted was detected.
Description
If the conversion is successful, the number of converted characters not including the null terminator (the number of char) is set in *utf8count (providing that utf8count is not NULL).
If utf8 is set to NULL and buflen is set to 0, the number of converted UTF-8 (which is not necessarily the number of code points) is set in utf8count.
If a character that is invalid as UTF-16 is detected, *utf8count is set to 0, utf8 is set to an empty string, and the function returns EILSEQ.

◆ nlib_utf16cplen()

nlib_utf16cplen ( size_t *  count,
const nlib_utf16_t str 
)
inlinestatic

Gets the number of code points in the string.

Parameters
[out]countPointer to where the number of code points is stored.
[in]strString.
Return values
0Success.
EINVALIndicates that count or str is NULL.
EILSEQSome data cannot be converted into a code point.

Definition at line 2301 of file Platform.h.

◆ nlib_utf16cplen_ex()

nlib_utf16cplen_ex ( size_t *  count,
size_t *  len,
const nlib_utf16_t str 
)
inlinestatic

Gets the number of code points in the string.

Parameters
[out]countPointer to where the number of code points is stored.
[out]lenPointer to where the length of str is stored.
[in]strString.
Return values
0Success.
EINVALIndicates that count or str is NULL.
EILSEQSome data cannot be converted into a code point.

Definition at line 2305 of file Platform.h.

◆ nlib_utf16cpy()

nlib_utf16cpy ( nlib_utf16_t s1,
size_t  s1max,
const nlib_utf16_t s2 
)
inlinestatic

The UTF-16 version of the nlib_strcpy function.

Parameters
[in,out]s1The buffer to copy to.
[in]s1maxThe size (number of characters) of the buffer to copy to.
[in]s2The buffer to copy from.
Return values
0Success.
EINVALIndicates that s1 or s2 is NULL.
ERANGEThe buffer is not large enough.
Description
s1[0]=0 is set if the function fails and s1 is not NULL. The behavior is undefined if the buffers overlap.
Platform Implementation
Win32 nlib_utf16nlen() + nlib_memcpy()
Linux nlib_utf16nlen() + nlib_memcpy()
FreeBSD nlib_utf16nlen() + nlib_memcpy()
OS X nlib_utf16nlen() + nlib_memcpy()
CAFE nlib_utf16nlen() + nlib_memcpy()
CTR nlib_utf16nlen() + nlib_memcpy()

Definition at line 2264 of file Platform.h.

◆ nlib_utf16len()

nlib_utf16len ( const nlib_utf16_t str)
inlinestatic

Counts the number of nlib_utf16_t-type characters, not including the null character.

Parameters
[in]strUTF-16 string.
Returns
Returns the number of characters (the number of nlib_utf16_t-type characters, not including the null character at the end).
Description
Platform Implementation
Win32 Implemented using SIMD.
Linux Implemented using SIMD.
FreeBSD Implemented using SIMD.
OS X Implemented using SIMD.
CAFE Expanded loop.
CTR Expanded loop.

Definition at line 2256 of file Platform.h.

◆ nlib_utf16ncpy()

nlib_utf16ncpy ( nlib_utf16_t s1,
size_t  s1max,
const nlib_utf16_t s2,
size_t  n 
)
inlinestatic

The UTF-16 version of the nlib_strcpy function.

Parameters
[in,out]s1The buffer to copy to.
[in]s1maxThe size (number of characters) of the buffer to copy to.
[in]s2The buffer to copy from.
[in]nThe number of characters to copy.
Return values
0Success.
EINVALIndicates that s1 or s2 is NULL.
ERANGEThe buffer is not large enough.
Description
s1[0]=0 is set if the function fails and s1 is not NULL. The behavior is undefined if the buffers overlap.
Platform Implementation
Win32 nlib_utf16nlen() + nlib_memcpy()
Linux nlib_utf16nlen() + nlib_memcpy()
FreeBSD nlib_utf16nlen() + nlib_memcpy()
OS X nlib_utf16nlen() + nlib_memcpy()
CAFE nlib_utf16nlen() + nlib_memcpy()
CTR nlib_utf16nlen() + nlib_memcpy()

Definition at line 2268 of file Platform.h.

◆ nlib_utf16nlen()

nlib_utf16nlen ( const nlib_utf16_t s,
size_t  maxsize 
)
inlinestatic

The UTF-16 version of the nlib_strnlen function.

Parameters
[in]sPointer to the string.
[in]maxsizeThe size of the string. (The maximum number for the return value.)
Returns
The length of the string.
Description
Returns 0 if s is NULL. If the string length is equal to or longer than maxsize, the function returns maxsize.
Platform Implementation
Win32 Implemented using SIMD.
Linux Implemented using SIMD.
FreeBSD Implemented using SIMD.
OS X Implemented using SIMD.
CAFE Expanded loop.
CTR Expanded loop.

Definition at line 2260 of file Platform.h.

◆ nlib_utf32_to_utf8()

nlib_utf32_to_utf8 ( size_t *  utf8count,
nlib_utf8_t utf8,
size_t  buflen,
const nlib_utf32_t utf32 
)

Converts a UTF-32 string into a UTF-8 string.

Parameters
[out]utf8countStores the number of converted characters (the number of char, not including the null character).
[out]utf8The buffer for storing the converted string.
[in]buflenThe size of the utf8 buffer (the number of characters including the null character).
[in]utf32A UTF-32 string.
Return values
0No error occurred.
EINVALEither utf8 is NULL and buflen > 0, or utf32 is NULL.
ERANGEThe converted string was too big to fit, so it has been stored in truncated form.
EILSEQData that cannot be converted was detected.
Description
If the conversion is successful, the number of converted characters not including the null terminator (the number of char) is set in *utf8count (providing that utf8count is not NULL).
If utf8 is set to NULL and buflen is set to 0, the number of converted UTF-8 is set in utf8count.
If a character that is invalid as UTF-32 is detected, *utf8count is set to 0, utf8 is set to an empty string, and the function returns EILSEQ.

◆ nlib_utf32char_to_utf16()

nlib_utf32char_to_utf16 ( nlib_utf16_t upper,
nlib_utf16_t lower,
nlib_utf32_t  utf32 
)

Converts a single UTF-32 character into UTF-16.

Parameters
[in]upperStores the first 16 bits of UTF-16.
[in]lowerStores the 16 bits subsequent to upper (if they are present).
[in]utf32UTF-32 for one character.
Return values
0Conversion was not possible.
1A result was stored for only upper.
2Results were stored for both upper and lower.

◆ nlib_utf32char_to_utf8()

nlib_utf32char_to_utf8 ( nlib_utf8_t(&)  utf8[4],
nlib_utf32_t  utf32 
)

Converts the UTF-32 for one character into UTF-8.

Parameters
[out]utf8Stores the converted UTF-8 string. This string must not be null-terminated.
[in]utf32UTF-32 for one character.
Return values
0Conversion was not possible.
1Only utf8[0] was set.
2Indicates that utf8[0] and utf8[1] were set.
3Indicates that utf8[0], utf8[1], and utf8[2] were set.
4Indicates that utf8[0], utf8[1], utf8[2], and utf8[3] were set.

◆ nlib_utf32cplen()

nlib_utf32cplen ( size_t *  count,
const nlib_utf32_t str 
)

Gets the number of code points in the string.

Parameters
[out]countPointer to where the number of code points is stored.
[in]strString.
Return values
0Success.
EINVALIndicates that count or str is NULL.
EILSEQSome data cannot be converted into a code point.

◆ nlib_utf32cpy()

nlib_utf32cpy ( nlib_utf32_t s1,
size_t  s1max,
const nlib_utf32_t s2 
)
inlinestatic

The UTF-32 version of the nlib_strcpy function.

Parameters
[in,out]s1The buffer to copy to.
[in]s1maxThe size (number of characters) of the buffer to copy to.
[in]s2The buffer to copy from.
Return values
0Success.
EINVALIndicates that s1 or s2 is NULL.
ERANGEThe buffer is not large enough.
Description
s1[0]=0 is set if the function fails and s1 is not NULL. The behavior is undefined if the buffers overlap.
Platform Implementation
Win32 nlib_utf32nlen() + nlib_memcpy()
Linux nlib_utf32nlen() + nlib_memcpy()
FreeBSD nlib_utf32nlen() + nlib_memcpy()
OS X nlib_utf32nlen() + nlib_memcpy()
CAFE nlib_utf32nlen() + nlib_memcpy()
CTR nlib_utf32nlen() + nlib_memcpy()

Definition at line 2289 of file Platform.h.

◆ nlib_utf32len()

nlib_utf32len ( const nlib_utf32_t str)
inlinestatic

Counts the number of nlib_utf32_t-type characters, not including the null character.

Parameters
[in]strUTF-32 string.
Returns
Returns the number of characters (the number of nlib_utf32_t-type characters, not including the null character at the end).

Definition at line 2281 of file Platform.h.

◆ nlib_utf32ncpy()

nlib_utf32ncpy ( nlib_utf32_t s1,
size_t  s1max,
const nlib_utf32_t s2,
size_t  n 
)
inlinestatic

The UTF-32 version of the nlib_strcpy function.

Parameters
[in,out]s1The buffer to copy to.
[in]s1maxThe size (number of characters) of the buffer to copy to.
[in]s2The buffer to copy from.
[in]nThe number of characters to copy.
Return values
0Success.
EINVALIndicates that s1 or s2 is NULL.
ERANGEThe buffer is not large enough.
Description
s1[0]=0 is set if the function fails and s1 is not NULL. The behavior is undefined if the buffers overlap.
Platform Implementation
Win32 nlib_utf32nlen() + nlib_memcpy()
Linux nlib_utf32nlen() + nlib_memcpy()
FreeBSD nlib_utf32nlen() + nlib_memcpy()
OS X nlib_utf32nlen() + nlib_memcpy()
CAFE nlib_utf32nlen() + nlib_memcpy()
CTR nlib_utf32nlen() + nlib_memcpy()

Definition at line 2293 of file Platform.h.

◆ nlib_utf32nlen()

nlib_utf32nlen ( const nlib_utf32_t s,
size_t  maxsize 
)
inlinestatic

The UTF-32 version of the nlib_strnlen function.

Parameters
[in]sPointer to the string.
[in]maxsizeThe size of the string. (The maximum number for the return value.)
Returns
The length of the string.
Description
Returns 0 if s is NULL. Returns maxsize if the string is longer than maxsize.

Definition at line 2285 of file Platform.h.

◆ nlib_utf8_to_utf16()

nlib_utf8_to_utf16 ( size_t *  utf16count,
nlib_utf16_t utf16,
size_t  buflen,
const nlib_utf8_t utf8 
)

Converts a UTF-8 string into a UTF-16 string. The UTF-16 string is null-terminated.

Parameters
[out]utf16countStores the number of converted characters (the number of nlib_utf16_t-type characters, not including the null character).
[out]utf16The buffer for storing the converted string.
[in]buflenThe size of the utf16 buffer (the number of characters including the null character).
[in]utf8A UTF-8 string.
Return values
0Success.
EINVALEither utf16 is NULL and buflen > 0, or utf8 is NULL.
ERANGEThe converted string was too big to fit, so it has been stored in truncated form.
EILSEQData that cannot be converted was detected.
Description
If the conversion is successful, the number of converted characters not including the null terminator (the number of nlib_utf16_t-type characters) is set in *utf16count (providing that utf16count is not NULL).
If utf16 is set to NULL and buflen is set to 0, the number of converted UTF-16 (which is not necessarily the number of code points) is set in utf16count.
If a character that is invalid as UTF-8 is detected, *utf16count is set to 0, utf16 is set to an empty string, and the function returns EILSEQ.

◆ nlib_utf8_to_utf32()

nlib_utf8_to_utf32 ( size_t *  utf32count,
nlib_utf32_t utf32,
size_t  buflen,
const nlib_utf8_t utf8 
)

Converts a UTF-8 string into a UTF-32 string.

Parameters
[out]utf32countStores the number of converted characters (the number of nlib_utf32_t-type characters, not including the null character).
[out]utf32The buffer for storing the converted string.
[out]buflenThe size of the utf32 buffer (the number of characters including the null character).
[in]utf8A UTF-8 string.
Return values
0No error occurred.
EINVALEither utf32 is NULL and buflen > 0, or utf8 is NULL.
ERANGEThe converted string was too big to fit, so it has been stored in truncated form.
EILSEQData that cannot be converted was detected.
Description
If the conversion is successful, the number of converted characters not including the null terminator (the number of nlib_utf32_t-type characters) is set in *utf32count (providing that utf32count is not NULL).
If utf32 is set to NULL and buflen is set to 0, the number of converted UTF-32 is set in utf32count.
If a character that is invalid as UTF-8 is detected, *utf32count is set to 0, utf32 is set to an empty string, and the function returns EILSEQ.

◆ nlib_utf8_to_utf32char()

nlib_utf8_to_utf32char ( nlib_utf32_t utf32,
const nlib_utf8_t utf8 
)

Converts UTF-8 into one character's worth of UTF-32.

Parameters
[out]utf32Stores the converted character.
[in]utf8A UTF-8 string.
Return values
0Conversion was not possible.
1Only utf8[0] was converted.
2Indicates that utf8[0] and utf8[1] were converted.
3Indicates that utf8[0], utf8[1], and utf8[2] were converted.
4Indicates that utf8[0], utf8[1], utf8[2], and utf8[3] were converted.
Examples:
succinct/kwlink/kwlink.cpp.

◆ nlib_utf8_to_wide()

nlib_utf8_to_wide ( size_t *  wccount,
wchar_t *  wcstr,
size_t  buflen,
const nlib_utf8_t utf8 
)

Converts a UTF-8 string into a UTF-16/UTF-32 string.

Parameters
[out]wccountStores the number of converted characters (the number of wchar_t, not including the null character).
[out]wcstrThe buffer for storing the converted string.
[in]buflenThe size of the wcstr buffer (the number of characters including the null character).
[in]utf8A UTF-8 string.
Returns
Returns 0 on success.
Description
Calls either nlib_utf8_to_utf16 or nlib_utf8_to_utf32, depending on whether wchar_t is 16 bits or 32 bits.

◆ nlib_virtual_alloc()

nlib_virtual_alloc ( void **  ptr,
size_t  size 
)

Allocates virtual memory address space.

Parameters
[out]ptrThe pointer to where the starting address of the allocated virtual memory address space gets written.
[in]sizeThe size (in bytes) of the virtual memory address space to allocate.
Returns
Returns 0 on success.
Description
Platform Implementation
Win32 VirtualAlloc(NULL, size, MEM_RESERVE, PAGE_READWRITE);
Linux mmap(NULL, size, PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
FreeBSD mmap(NULL, size, PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
OS X mmap(NULL, size, PROT_NONE, MAP_ANON | MAP_PRIVATE, -1, 0);
CAFE MEMAllocFromDefaultHeapEx(size, OSGetPageSize())
CTR Construction of MemoryBlock (can allocate up to eight regions).

◆ nlib_virtual_free()

nlib_virtual_free ( void *  ptr,
size_t  size 
)

Frees the allocated virtual memory address space.

Parameters
[in]ptrThe value given to the nlib_virtual_alloc function.
[in]sizeThe value given to the nlib_virtual_alloc function.
Returns
Returns 0 on success.
Description
The behavior is undefined if ptr and size differ from the values given to the nlib_virtual_alloc function.
Platform Implementation
Win32 VirtualFree(ptr, 0, MEM_RELEASE);
Linux munmap(ptr, size)
FreeBSD munmap(ptr, size)
OS X munmap(ptr, size)
CAFE MEMFreeToDefaultHeap(ptr)
CTR Destruction of MemoryBlock.

◆ nlib_vsnprintf()

nlib_vsnprintf ( size_t *  count,
char *  buf,
size_t  size,
const char *  fmt,
va_list  args 
)

A safer form of vsnprintf, with some differences from standard vsnprintf behavior.

Parameters
[out]countThe number of written characters (not including the null character).
[in]bufThe buffer where the output is written.
[in]sizeThe size of the buffer (the number of characters including the null character).
[in]fmtThe format settings.
[in]argsAn argument list.
Return values
0Success.
ERANGEThe output cannot fit in the buffer.
EINVALIndicates that count is NULL.
Description
This function is safer to use because it separates out the number of characters in which error values are written. In addition, it unifies the many differences in return values and errno settings of the vsnprintf function that vary depending on the implementation.
If the function returns ERANGE, the number of characters that would have been written is set in count, and a null-terminated string that fills the buffer is stored in buf.
There are also these other similar functions: nlib_snprintf, nlib_vdprintf, nlib_dprintf, and nlib_printf.
In addition, versions have been implemented that allow you to omit the size parameter for C++ where arrays are used in buf.
Platform Implementation
Win32 _vsnprintf_s_l + _vscprintf_l
Linux vsnprintf
FreeBSD vsnprintf
OS X vsnprintf
CAFE vsnprintf
CTR vsnprintf

◆ nlib_vsnwprintf()

nlib_vsnwprintf ( size_t *  count,
wchar_t *  buf,
size_t  size,
const wchar_t *  fmt,
va_list  args 
)

A safer form of vswprintf, with some differences from standard vswprintf behavior.

Parameters
[out]countThe number of written characters (not including the null character).
[in]bufThe buffer where the output is written.
[in]sizeThe size of the buffer (the number of characters including the null character).
[in]fmtThe format settings.
[in]argsAn argument list.
Return values
0Success.
ERANGEThe output cannot fit in the buffer.
EINVALIndicates that count is NULL.
Description
This function is safer to use because it separates out the number of characters in which error values are written. In addition, it unifies the many differences in return values and errno settings of the vswprintf function that vary depending on the implementation.
If the function returns ERANGE, the number of characters that would have been written is set in count, and a null-terminated string that fills the buffer is stored in buf.
There are also these other similar functions: nlib_snwprintf, nlib_vdwprintf, nlib_dwprintf, and nlib_wprintf.
In addition, versions have been implemented that allow you to omit the size parameter for C++ where arrays are used in buf.
Platform Implementation
Win32 _vsnwprintf_s_l + _vscwprintf_l
Linux vswprintf + nlib_vsnwprintf_fallback()
FreeBSD nlib_vsnwprintf_fallback()
OS X nlib_vsnwprintf_fallback()
CAFE vswprintf + nlib_vsnwprintf_fallback()
CTR vswprintf + nlib_vsnwprintf_fallback()

◆ nlib_wcscplen()

nlib_wcscplen ( size_t *  count,
const wchar_t *  str 
)

Gets the number of code points in the string.

Parameters
[out]countPointer to where the number of code points is stored.
[in]strString.
Return values
0Success.
EINVALIndicates that count or str is NULL.
EILSEQSome data cannot be converted into a code point.

◆ nlib_wcscpy()

nlib_wcscpy ( wchar_t *  s1,
size_t  s1max,
const wchar_t *  s2 
)

An implementation corresponding to N1078 wcscpy_s.

Parameters
[in,out]s1The buffer to copy to.
[in]s1maxThe size (number of characters) of the buffer to copy to.
[in]s2The buffer to copy from.
Return values
0Success.
EINVALIndicates that s1 or s2 is NULL.
ERANGEThe buffer is not large enough.
Description
s1[0]=0 is set if the function fails and s1 is not NULL. The behavior is undefined if the buffers overlap.
Platform Implementation
Win32 nlib_wcsnlen() + nlib_memcpy()
Linux nlib_wcsnlen() + nlib_memcpy()
FreeBSD nlib_wcsnlen() + nlib_memcpy()
OS X nlib_wcsnlen() + nlib_memcpy()
CAFE nlib_wcsnlen() + nlib_memcpy()
CTR nlib_wcsnlen() + nlib_memcpy()

◆ nlib_wcslen()

nlib_wcslen ( const wchar_t *  s)

Makes a call to thewcslen function. In some cases, it may operate as an independent implementation.

Parameters
[in]sPointer to the string.
Returns
The length of the string.
Description
Returns 0 if s is NULL.

◆ nlib_wcsncpy()

nlib_wcsncpy ( wchar_t *  s1,
size_t  s1max,
const wchar_t *  s2,
size_t  n 
)

An implementation corresponding to N1078 wcsncpy_s.

Parameters
[in,out]s1The buffer to copy to.
[in]s1maxThe size (number of characters) of the buffer to copy to.
[in]s2The buffer to copy from.
[in]nThe number of characters to copy.
Return values
0Success.
EINVALIndicates that s1 or s2 is NULL.
ERANGEThe buffer is not large enough.
Description
s1[0]=0 is set if the function fails and s1 is not NULL. The behavior is undefined if the buffers overlap.
Platform Implementation
Win32 nlib_wcsnlen() + nlib_memcpy()
Linux nlib_wcsnlen() + nlib_memcpy()
FreeBSD nlib_wcsnlen() + nlib_memcpy()
OS X nlib_wcsnlen() + nlib_memcpy()
CAFE nlib_wcsnlen() + nlib_memcpy()
CTR nlib_wcsnlen() + nlib_memcpy()

◆ nlib_wcsnlen()

nlib_wcsnlen ( const wchar_t *  s,
size_t  maxsize 
)

An implementation corresponding to N1078 wcsnlen_s.

Parameters
[in]sPointer to the string.
[in]maxsizeThe size of the string. (The maximum number for the return value.)
Returns
The length of the string.
Description
Returns 0 if s is NULL. Returns maxsize if the string is longer than maxsize.
Platform Implementation
Win32 nlib_utf16nlen()
Linux nlib_utf32nlen()
FreeBSD nlib_utf32nlen()
OS X nlib_utf32nlen()
CAFE nlib_utf16nlen()
CTR nlib_utf16nlen()

◆ nlib_wide_to_utf8()

nlib_wide_to_utf8 ( size_t *  utf8count,
nlib_utf8_t utf8,
size_t  buflen,
const wchar_t *  wcstr 
)

Converts a UTF-16/UTF-32 string into a UTF-8 string.

Parameters
[out]utf8countStores the number of converted characters (the number of char, not including the null character).
[out]utf8The buffer for storing the converted string.
[in]buflenThe size of the utf8 buffer (the number of characters including the null character).
[in]wcstrA UTF-16/UTF-32 string.
Returns
Returns 0 on success.
Description
Calls either nlib_utf16_to_utf8 or nlib_utf32_to_utf8, depending on whether wchar_t is 16 bits or 32 bits.

◆ nlib_write_stderr()

nlib_write_stderr ( size_t *  result,
const void *  buf,
size_t  count 
)

Writes a string to standard error output.

Parameters
[out]resultThe number of characters written.
[in]bufPointer to a UTF-8 string (without a NULL terminator).
[in]countThe number of characters.
Return values
0Success.
Description
Platform Implementation
Win32 MultiByteToWideChar() + GetStdHandle(STD_ERROR_HANDLE) + WriteConsoleW()
Linux write()
FreeBSD write()
OS X write()
CAFE OSConsoleWrite()
CTR nn::dbg::detail::PutString()

◆ nlib_write_stdout()

nlib_write_stdout ( size_t *  result,
const void *  buf,
size_t  count 
)

Writes a string to standard output.

Parameters
[out]resultThe number of characters written.
[in]bufPointer to a UTF-8 string (without a NULL terminator).
[in]countThe number of characters.
Return values
0Success.
Description
Platform Implementation
Win32 MultiByteToWideChar() + GetStdHandle(STD_OUTPUT_HANDLE) + WriteConsoleW()
Linux write() - If errno is EINTR, the function is executed again internally.
FreeBSD write() - If errno is EINTR, the function is executed again internally.
OS X write() - If errno is EINTR, the function is executed again internally.
CAFE OSConsoleWrite()
CTR nn::dbg::detail::PutString()

Variable Documentation

◆ flag

nlib_mq_attr::flag

Settings to be used when creating a message queue.

Description
Value Description
NLIB_MQ_BLOCK When reading an empty queue or writing into a full queue, blocks and waits.
NLIB_MQ_NONBLOCKReturns an error (EAGAIN) when it would normally blocks.
NLIB_MQ_LOCKFREECreates a lock-free queue. Returns an error (EAGAIN) when it would normally blocks.

Definition at line 1176 of file Platform.h.