1
0
Fork 0

Adding upstream version 7.0.20-dfsg.

Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
This commit is contained in:
Daniel Baumann 2025-06-22 09:56:04 +02:00
parent d0c7daf57c
commit df1bda4fe9
Signed by: daniel.baumann
GPG key ID: BCC918A2ABD66424
26643 changed files with 10005219 additions and 0 deletions

View file

216
include/iprt/cpp/autores.h Normal file
View file

@ -0,0 +1,216 @@
/** @file
* IPRT - C++ Resource Management.
*/
/*
* Copyright (C) 2008-2023 Oracle and/or its affiliates.
*
* This file is part of VirtualBox base platform packages, as
* available from https://www.virtualbox.org.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, in version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses>.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
* in the VirtualBox distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*
* SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
*/
#ifndef IPRT_INCLUDED_cpp_autores_h
#define IPRT_INCLUDED_cpp_autores_h
#ifndef RT_WITHOUT_PRAGMA_ONCE
# pragma once
#endif
#include <iprt/types.h>
#include <iprt/assert.h>
#include <iprt/cpp/utils.h>
/** @defgroup grp_rt_cpp_autores C++ Resource Management
* @ingroup grp_rt_cpp
* @{
*/
/**
* A callable class template which returns the correct value against which an
* IPRT type must be compared to see if it is invalid.
*
* @warning This template *must* be specialised for the types it is to work with.
*/
template <class T>
inline T RTAutoResNil(void)
{
AssertFatalMsgFailed(("Unspecialized template!\n"));
return (T)0;
}
/** Specialisation of RTAutoResNil for RTFILE */
template <>
inline RTFILE RTAutoResNil(void)
{
return NIL_RTFILE;
}
/**
* A function template which calls the correct destructor for an IPRT type.
*
* @warning This template *must* be specialised for the types it is to work with.
*/
template <class T>
inline void RTAutoResDestruct(T a_h)
{
AssertFatalMsgFailed(("Unspecialized template!\n"));
NOREF(a_h);
}
/**
* An auto pointer-type class for resources which take a C-style destructor
* (RTMemFree() or equivalent).
*
* The idea of this class is to manage resources which the current code is
* responsible for freeing. By wrapping the resource in an RTCAutoRes, you
* ensure that the resource will be freed when you leave the scope in which
* the RTCAutoRes is defined, unless you explicitly release the resource.
*
* A typical use case is when a function is allocating a number of resources.
* If any single allocation fails then all other resources must be freed. If
* all allocations succeed, then the resources should be returned to the
* caller. By placing all allocated resources in RTCAutoRes containers, you
* ensure that they will be freed on failure, and only have to take care of
* releasing them when you return them.
*
* @param T The type of the resource.
* @param Destruct The function to be used to free the resource.
* This parameter must be supplied if there is no
* specialisation of RTAutoDestruct available for @a T.
* @param NilRes The function returning the NIL value for T. Required.
* This parameter must be supplied if there is no
* specialisation of RTAutoResNil available for @a T.
*
* @note The class can not be initialised directly using assignment, due
* to the lack of a copy constructor. This is intentional.
*/
template <class T, void Destruct(T) = RTAutoResDestruct<T>, T NilRes(void) = RTAutoResNil<T> >
class RTCAutoRes
: public RTCNonCopyable
{
protected:
/** The resource handle. */
T m_hRes;
public:
/**
* Constructor
*
* @param a_hRes The handle to resource to manage. Defaults to NIL.
*/
RTCAutoRes(T a_hRes = NilRes())
: m_hRes(a_hRes)
{
}
/**
* Destructor.
*
* This destroys any resource currently managed by the object.
*/
~RTCAutoRes()
{
if (m_hRes != NilRes())
Destruct(m_hRes);
}
/**
* Assignment from a value.
*
* This destroys any resource currently managed by the object
* before taking on the new one.
*
* @param a_hRes The handle to the new resource.
*/
RTCAutoRes &operator=(T a_hRes)
{
if (m_hRes != NilRes())
Destruct(m_hRes);
m_hRes = a_hRes;
return *this;
}
/**
* Checks if the resource handle is NIL or not.
*/
bool operator!()
{
return m_hRes == NilRes();
}
/**
* Give up ownership the current resource, handing it to the caller.
*
* @returns The current resource handle.
*
* @note Nothing happens to the resource when the object goes out of scope.
*/
T release(void)
{
T Tmp = m_hRes;
m_hRes = NilRes();
return Tmp;
}
/**
* Deletes the current resources.
*
* @param a_hRes Handle to a new resource to manage. Defaults to NIL.
*/
void reset(T a_hRes = NilRes())
{
if (a_hRes != m_hRes)
{
if (m_hRes != NilRes())
Destruct(m_hRes);
m_hRes = a_hRes;
}
}
/**
* Get the raw resource handle.
*
* Typically used passing the handle to some IPRT function while
* the object remains in scope.
*
* @returns The raw resource handle.
*/
T get(void)
{
return m_hRes;
}
};
/** @} */
/* include after template definition */
#include <iprt/mem.h>
#endif /* !IPRT_INCLUDED_cpp_autores_h */

View file

@ -0,0 +1,118 @@
/** @file
* IPRT - C++ Base Exceptions.
*/
/*
* Copyright (C) 2006-2023 Oracle and/or its affiliates.
*
* This file is part of VirtualBox base platform packages, as
* available from https://www.virtualbox.org.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, in version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses>.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
* in the VirtualBox distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*
* SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
*/
#ifndef IPRT_INCLUDED_cpp_exception_h
#define IPRT_INCLUDED_cpp_exception_h
#ifndef RT_WITHOUT_PRAGMA_ONCE
# pragma once
#endif
#include <iprt/cpp/ministring.h>
#include <exception>
#if RT_MSC_PREREQ(RT_MSC_VER_VC140)
# pragma warning(push)
# pragma warning(disable:4275) /* non dll-interface class 'std::exception' used as base for dll-interface class 'RTCError' */
#endif
/** @defgroup grp_rt_cpp_exceptions C++ Exceptions
* @ingroup grp_rt_cpp
* @{
*/
/**
* Base exception class for IPRT, derived from std::exception.
* The XML exceptions are based on this.
*/
class RT_DECL_CLASS RTCError
: public std::exception
{
public:
RTCError(const char *pszMessage)
: m_strMsg(pszMessage)
{
}
RTCError(const RTCString &a_rstrMessage)
: m_strMsg(a_rstrMessage)
{
}
RTCError(const RTCError &a_rSrc)
: std::exception(a_rSrc),
m_strMsg(a_rSrc.what())
{
}
virtual ~RTCError() throw()
{
}
void operator=(const RTCError &a_rSrc)
{
m_strMsg = a_rSrc.what();
}
void setWhat(const char *a_pszMessage)
{
m_strMsg = a_pszMessage;
}
virtual const char *what() const throw()
{
return m_strMsg.c_str();
}
private:
/**
* Hidden default constructor making sure that the extended one above is
* always used.
*/
RTCError();
protected:
/** The exception message. */
RTCString m_strMsg;
};
/** @} */
#if RT_MSC_PREREQ(RT_MSC_VER_VC140)
# pragma warning(pop)
#endif
#endif /* !IPRT_INCLUDED_cpp_exception_h */

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,218 @@
/** @file
* IPRT - Hardened AVL tree slab allocator.
*/
/*
* Copyright (C) 2022-2023 Oracle and/or its affiliates.
*
* This file is part of VirtualBox base platform packages, as
* available from https://www.virtualbox.org.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, in version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses>.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
* in the VirtualBox distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*
* SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
*/
#ifndef IPRT_INCLUDED_cpp_hardavlslaballocator_h
#define IPRT_INCLUDED_cpp_hardavlslaballocator_h
#ifndef RT_WITHOUT_PRAGMA_ONCE
# pragma once
#endif
#include <iprt/asm.h>
#include <iprt/assert.h>
#include <iprt/err.h>
#include <iprt/string.h>
/** @addtogroup grp_rt_cpp_hardavl
* @{
*/
/**
* Slab allocator for the hardened AVL tree.
*/
template<typename NodeType>
struct RTCHardAvlTreeSlabAllocator
{
/** Pointer to an array of nodes. */
NodeType *m_paNodes;
/** Node allocation bitmap: 1 = free, 0 = allocated. */
uint64_t *m_pbmAlloc;
/** Max number of nodes in m_paNodes and valid bits in m_pbmAlloc. */
uint32_t m_cNodes;
/** Pointer error counter. */
uint32_t m_cErrors;
/** Allocation hint. */
uint32_t m_idxAllocHint;
uint32_t m_uPadding;
enum
{
kNilIndex = 0,
kErr_IndexOutOfBound = -1,
kErr_PointerOutOfBound = -2,
kErr_MisalignedPointer = -3,
kErr_NodeIsFree = -4,
kErr_Last = kErr_NodeIsFree
};
RTCHardAvlTreeSlabAllocator() RT_NOEXCEPT
: m_paNodes(NULL)
, m_pbmAlloc(NULL)
, m_cNodes(0)
, m_cErrors(0)
, m_idxAllocHint(0)
, m_uPadding(0)
{}
inline void initSlabAllocator(uint32_t a_cNodes, NodeType *a_paNodes, uint64_t *a_pbmAlloc) RT_NOEXCEPT
{
m_cNodes = a_cNodes;
m_paNodes = a_paNodes;
m_pbmAlloc = a_pbmAlloc;
/* Initialize the allocation bit. */
RT_BZERO(a_pbmAlloc, (a_cNodes + 63) / 64 * 8);
ASMBitSetRange(a_pbmAlloc, 0, a_cNodes);
}
inline NodeType *ptrFromInt(uint32_t a_idxNode1) RT_NOEXCEPT
{
if (a_idxNode1 == (uint32_t)kNilIndex)
return NULL;
AssertMsgReturnStmt(a_idxNode1 <= m_cNodes, ("a_idxNode1=%#x m_cNodes=%#x\n", a_idxNode1, m_cNodes),
m_cErrors++, (NodeType *)(intptr_t)kErr_IndexOutOfBound);
AssertMsgReturnStmt(ASMBitTest(m_pbmAlloc, a_idxNode1 - 1) == false, ("a_idxNode1=%#x\n", a_idxNode1),
m_cErrors++, (NodeType *)(intptr_t)kErr_NodeIsFree);
return &m_paNodes[a_idxNode1 - 1];
}
static inline bool isPtrRetOkay(NodeType *a_pNode) RT_NOEXCEPT
{
return (uintptr_t)a_pNode < (uintptr_t)kErr_Last;
}
static inline int ptrErrToStatus(NodeType *a_pNode) RT_NOEXCEPT
{
return (int)(intptr_t)a_pNode - (VERR_HARDAVL_INDEX_OUT_OF_BOUNDS - kErr_IndexOutOfBound);
}
inline uint32_t ptrToInt(NodeType *a_pNode) RT_NOEXCEPT
{
if (a_pNode == NULL)
return 0;
uintptr_t const offNode = (uintptr_t)a_pNode - (uintptr_t)m_paNodes;
uintptr_t const idxNode0 = offNode / sizeof(m_paNodes[0]);
AssertMsgReturnStmt((offNode % sizeof(m_paNodes[0])) == 0,
("pNode=%p / offNode=%#zx vs m_paNodes=%p L %#x, each %#x bytes\n",
a_pNode, offNode, m_paNodes, m_cNodes, sizeof(m_paNodes[0])),
m_cErrors++, (uint32_t)kErr_MisalignedPointer);
AssertMsgReturnStmt(idxNode0 < m_cNodes,
("pNode=%p vs m_paNodes=%p L %#x\n", a_pNode, m_paNodes, m_cNodes),
m_cErrors++, (uint32_t)kErr_PointerOutOfBound);
AssertMsgReturnStmt(ASMBitTest(m_pbmAlloc, idxNode0) == false, ("a_pNode=%p idxNode0=%#x\n", a_pNode, idxNode0),
m_cErrors++, (uint32_t)kErr_NodeIsFree);
return idxNode0 + 1;
}
static inline bool isIdxRetOkay(uint32_t a_idxNode) RT_NOEXCEPT
{
return a_idxNode < (uint32_t)kErr_Last;
}
static inline int idxErrToStatus(uint32_t a_idxNode) RT_NOEXCEPT
{
return (int)a_idxNode - (VERR_HARDAVL_INDEX_OUT_OF_BOUNDS - kErr_IndexOutOfBound);
}
inline bool isIntValid(uint32_t a_idxNode1) RT_NOEXCEPT
{
return a_idxNode1 <= m_cNodes;
}
inline int freeNode(NodeType *a_pNode) RT_NOEXCEPT
{
uint32_t idxNode1 = ptrToInt(a_pNode);
if (idxNode1 == (uint32_t)kNilIndex)
return 0;
if (idxNode1 < (uint32_t)kErr_Last)
{
AssertMsgReturnStmt(ASMAtomicBitTestAndSet(m_pbmAlloc, idxNode1 - 1) == false,
("a_pNode=%p idxNode1=%#x\n", a_pNode, idxNode1),
m_cErrors++, kErr_NodeIsFree);
return 0;
}
return (int)idxNode1;
}
inline NodeType *allocateNode(void) RT_NOEXCEPT
{
/*
* Use the hint first, then scan the whole bitmap.
* Note! We don't expect concurrent allocation calls, so no need to repeat.
*/
uint32_t const idxHint = m_idxAllocHint;
uint32_t idxNode0;
if ( idxHint >= m_cNodes
|| (int32_t)(idxNode0 = (uint32_t)ASMBitNextSet(m_pbmAlloc, m_cNodes, idxHint)) < 0)
idxNode0 = (uint32_t)ASMBitFirstSet(m_pbmAlloc, m_cNodes);
if ((int32_t)idxNode0 >= 0)
{
if (ASMAtomicBitTestAndClear(m_pbmAlloc, idxNode0) == true)
{
m_idxAllocHint = idxNode0;
return &m_paNodes[idxNode0];
}
AssertMsgFailed(("idxNode0=%#x\n", idxNode0));
m_cErrors++;
}
return NULL;
}
};
/**
* Placeholder structure for ring-3 slab allocator.
*/
typedef struct RTCHardAvlTreeSlabAllocatorR3_T
{
/** Pointer to an array of nodes. */
RTR3PTR m_paNodes;
/** Node allocation bitmap: 1 = free, 0 = allocated. */
RTR3PTR m_pbmAlloc;
/** Max number of nodes in m_paNodes and valid bits in m_pbmAlloc. */
uint32_t m_cNodes;
/** Pointer error counter. */
uint32_t m_cErrors;
/** Allocation hint. */
uint32_t m_idxAllocHint;
uint32_t m_uPadding;
} RTCHardAvlTreeSlabAllocatorR3_T;
AssertCompileSize(RTCHardAvlTreeSlabAllocatorR3_T,
sizeof(RTCHardAvlTreeSlabAllocator<RTUINT128U>) - (sizeof(void *) - sizeof(RTR3PTR)) * 2);
/** @} */
#endif /* !IPRT_INCLUDED_cpp_hardavlslaballocator_h */

1143
include/iprt/cpp/list.h Normal file

File diff suppressed because it is too large Load diff

179
include/iprt/cpp/lock.h Normal file
View file

@ -0,0 +1,179 @@
/** @file
* IPRT - Classes for Scope-based Locking.
*/
/*
* Copyright (C) 2007-2023 Oracle and/or its affiliates.
*
* This file is part of VirtualBox base platform packages, as
* available from https://www.virtualbox.org.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, in version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses>.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
* in the VirtualBox distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*
* SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
*/
#ifndef IPRT_INCLUDED_cpp_lock_h
#define IPRT_INCLUDED_cpp_lock_h
#ifndef RT_WITHOUT_PRAGMA_ONCE
# pragma once
#endif
#include <iprt/critsect.h>
#ifdef RT_LOCK_STRICT
# include <iprt/lockvalidator.h>
#endif
RT_C_DECLS_BEGIN
/** @defgroup grp_rt_cpp_lock C++ Scope-based Locking
* @ingroup grp_rt_cpp
* @{
*/
class RTCLock;
/**
* The mutex lock.
*
* This is used as an object data member if the intention is to lock
* a single object. This can also be used statically, initialized in
* a global variable, for class wide purposes.
*
* This is best used together with RTCLock.
*/
class RTCLockMtx
{
friend class RTCLock;
private:
RTCRITSECT mMtx;
public:
RTCLockMtx()
{
#ifdef RT_LOCK_STRICT_ORDER
RTCritSectInitEx(&mMtx, 0 /*fFlags*/,
RTLockValidatorClassCreateUnique(RT_SRC_POS, NULL),
RTLOCKVAL_SUB_CLASS_NONE, NULL);
#else
RTCritSectInit(&mMtx);
#endif
}
/** Use to when creating locks that belongs in the same "class". */
RTCLockMtx(RT_SRC_POS_DECL, uint32_t uSubClass = RTLOCKVAL_SUB_CLASS_NONE)
{
#ifdef RT_LOCK_STRICT_ORDER
RTCritSectInitEx(&mMtx, 0 /*fFlags*/,
RTLockValidatorClassForSrcPos(RT_SRC_POS_ARGS, NULL),
uSubClass, NULL);
#else
NOREF(uSubClass);
RTCritSectInit(&mMtx);
RT_SRC_POS_NOREF();
#endif
}
~RTCLockMtx()
{
RTCritSectDelete(&mMtx);
}
/* lock() and unlock() are private so that only friend RTCLock can access
them. */
private:
inline void lock()
{
RTCritSectEnter(&mMtx);
}
inline void unlock()
{
RTCritSectLeave(&mMtx);
}
};
/**
* The stack object for automatic locking and unlocking.
*
* This is a helper class for automatic locks, to simplify requesting a
* RTCLockMtx and to not forget releasing it. To request a RTCLockMtx, simply
* create an instance of RTCLock on the stack and pass the mutex to it:
*
* @code
extern RTCLockMtx gMtx; // wherever this is
...
if (...)
{
RTCLock lock(gMtx);
... // do stuff
// when lock goes out of scope, destructor releases the mutex
}
@endcode
*
* You can also explicitly release the mutex by calling RTCLock::release().
* This might be helpful if the lock doesn't go out of scope early enough
* for your mutex to be released.
*/
class RTCLock
{
private:
/** Reference to the lock we're holding. */
RTCLockMtx &m_rMtx;
/** Whether we're currently holding the lock of if it was already
* explictily released by the release() method. */
bool m_fLocked;
public:
RTCLock(RTCLockMtx &a_rMtx)
: m_rMtx(a_rMtx)
{
m_rMtx.lock();
m_fLocked = true;
}
~RTCLock()
{
if (m_fLocked)
m_rMtx.unlock();
}
inline void release()
{
if (m_fLocked)
{
m_rMtx.unlock();
m_fLocked = false;
}
}
};
/** @} */
RT_C_DECLS_END
#endif /* !IPRT_INCLUDED_cpp_lock_h */

125
include/iprt/cpp/meta.h Normal file
View file

@ -0,0 +1,125 @@
/** @file
* IPRT - C++ Meta programming.
*/
/*
* Copyright (C) 2011-2023 Oracle and/or its affiliates.
*
* This file is part of VirtualBox base platform packages, as
* available from https://www.virtualbox.org.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, in version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses>.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
* in the VirtualBox distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*
* SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
*/
#ifndef IPRT_INCLUDED_cpp_meta_h
#define IPRT_INCLUDED_cpp_meta_h
#ifndef RT_WITHOUT_PRAGMA_ONCE
# pragma once
#endif
#include <iprt/types.h>
/** @defgroup grp_rt_cpp_meta C++ Meta programming utilities
* @ingroup grp_rt_cpp
* @{
*/
/**
* Check for a condition on compile time and dependent of the result TrueResult
* or FalseResult will be defined.
*
* @param Condition Condition to check.
* @param TrueResult Result when condition is true.
* @param FalseResult Result when condition is false
*/
template <bool Condition, typename TrueResult, typename FalseResult>
struct RTCIf;
/**
* Check for a condition on compile time and dependent of the result TrueResult
* or FalseResult will be defined.
*
* True specialization of RTCIf.
*
* @param TrueResult Result when condition is true.
* @param FalseResult Result when condition is false
*/
template <typename TrueResult, typename FalseResult>
struct RTCIf<true, TrueResult, FalseResult>
{
typedef TrueResult result;
};
/**
* Check for a condition on compile time and dependent of the result TrueResult
* or FalseResult will be defined.
*
* False specialization of RTCIf.
*
* @param TrueResult Result when condition is true.
* @param FalseResult Result when condition is false
*/
template <typename TrueResult, typename FalseResult>
struct RTCIf<false, TrueResult, FalseResult>
{
typedef FalseResult result;
};
/**
* Check if @a T is a pointer or not at compile time and dependent of the
* result TrueResult or FalseResult will be defined.
*
* False version of RTCIfPtr.
*
* @param Condition Condition to check.
* @param TrueResult Result when condition is true.
* @param FalseResult Result when condition is false
*/
template <class T, typename TrueResult, typename FalseResult>
struct RTCIfPtr
{
typedef FalseResult result;
};
/**
* Check if @a T is a pointer or not at compile time and dependent of the
* result TrueResult or FalseResult will be defined.
*
* True specialization of RTCIfPtr.
*
* @param Condition Condition to check.
* @param TrueResult Result when condition is true.
* @param FalseResult Result when condition is false
*/
template <class T, typename TrueResult, typename FalseResult>
struct RTCIfPtr<T*, TrueResult, FalseResult>
{
typedef TrueResult result;
};
/** @} */
#endif /* !IPRT_INCLUDED_cpp_meta_h */

File diff suppressed because it is too large Load diff

185
include/iprt/cpp/mtlist.h Normal file
View file

@ -0,0 +1,185 @@
/** @file
* IPRT - Generic thread-safe list Class.
*/
/*
* Copyright (C) 2011-2023 Oracle and/or its affiliates.
*
* This file is part of VirtualBox base platform packages, as
* available from https://www.virtualbox.org.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, in version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses>.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
* in the VirtualBox distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*
* SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
*/
#ifndef IPRT_INCLUDED_cpp_mtlist_h
#define IPRT_INCLUDED_cpp_mtlist_h
#ifndef RT_WITHOUT_PRAGMA_ONCE
# pragma once
#endif
#include <iprt/cpp/list.h>
#include <iprt/semaphore.h>
/** @addtogroup grp_rt_cpp_list
* @{
*/
/**
* A guard class for thread-safe read/write access.
*/
template <>
class RTCListGuard<true>
{
public:
RTCListGuard() : m_hRWSem(NIL_RTSEMRW)
{
#if defined(RT_LOCK_STRICT_ORDER) && defined(IN_RING3)
RTLOCKVALCLASS hClass;
int rc = RTLockValidatorClassCreate(&hClass, true /*fAutodidact*/, RT_SRC_POS, "RTCListGuard");
AssertStmt(RT_SUCCESS(rc), hClass = NIL_RTLOCKVALCLASS);
rc = RTSemRWCreateEx(&m_hRWSem, 0 /*fFlags*/, hClass, RTLOCKVAL_SUB_CLASS_NONE, NULL /*pszNameFmt*/);
AssertRC(rc);
#else
int rc = RTSemRWCreateEx(&m_hRWSem, 0 /*fFlags*/, NIL_RTLOCKVALCLASS, 0, NULL);
AssertRC(rc);
#endif
}
~RTCListGuard()
{
RTSemRWDestroy(m_hRWSem);
m_hRWSem = NIL_RTSEMRW;
}
inline void enterRead() const { int rc = RTSemRWRequestRead(m_hRWSem, RT_INDEFINITE_WAIT); AssertRC(rc); }
inline void leaveRead() const { int rc = RTSemRWReleaseRead(m_hRWSem); AssertRC(rc); }
inline void enterWrite() { int rc = RTSemRWRequestWrite(m_hRWSem, RT_INDEFINITE_WAIT); AssertRC(rc); }
inline void leaveWrite() { int rc = RTSemRWReleaseWrite(m_hRWSem); AssertRC(rc); }
/* Define our own new and delete. */
RTMEMEF_NEW_AND_DELETE_OPERATORS();
private:
mutable RTSEMRW m_hRWSem;
};
/**
* @brief Generic thread-safe list class.
*
* RTCMTList is a thread-safe implementation of the list class. It uses a
* read/write semaphore to serialize the access to the items. Several readers
* can simultaneous access different or the same item. If one thread is writing
* to an item, the other accessors are blocked until the write has finished.
*
* Although the access is guarded, the user has to make sure the list content
* is consistent when iterating over the list or doing any other kind of access
* which makes assumptions about the list content. For a finer control of access
* restrictions, use your own locking mechanism and the standard list
* implementation.
*
* @see RTCListBase
*/
template <class T, typename ITYPE = typename RTCIf<(sizeof(T) > sizeof(void*)), T*, T>::result>
class RTCMTList : public RTCListBase<T, ITYPE, true>
{
/* Traits */
typedef RTCListBase<T, ITYPE, true> BASE;
public:
/**
* Creates a new list.
*
* This preallocates @a cCapacity elements within the list.
*
* @param cCapacity The initial capacity the list has.
* @throws std::bad_alloc
*/
RTCMTList(size_t cCapacity = BASE::kDefaultCapacity)
: BASE(cCapacity) {}
/* Define our own new and delete. */
RTMEMEF_NEW_AND_DELETE_OPERATORS();
};
/**
* Specialized thread-safe list class for using the native type list for
* unsigned 64-bit values even on a 32-bit host.
*
* @see RTCListBase
*/
template <>
class RTCMTList<uint64_t>: public RTCListBase<uint64_t, uint64_t, true>
{
/* Traits */
typedef RTCListBase<uint64_t, uint64_t, true> BASE;
public:
/**
* Creates a new list.
*
* This preallocates @a cCapacity elements within the list.
*
* @param cCapacity The initial capacity the list has.
* @throws std::bad_alloc
*/
RTCMTList(size_t cCapacity = BASE::kDefaultCapacity)
: BASE(cCapacity) {}
/* Define our own new and delete. */
RTMEMEF_NEW_AND_DELETE_OPERATORS();
};
/**
* Specialized thread-safe list class for using the native type list for
* signed 64-bit values even on a 32-bit host.
*
* @see RTCListBase
*/
template <>
class RTCMTList<int64_t>: public RTCListBase<int64_t, int64_t, true>
{
/* Traits */
typedef RTCListBase<int64_t, int64_t, true> BASE;
public:
/**
* Creates a new list.
*
* This preallocates @a cCapacity elements within the list.
*
* @param cCapacity The initial capacity the list has.
* @throws std::bad_alloc
*/
RTCMTList(size_t cCapacity = BASE::kDefaultCapacity)
: BASE(cCapacity) {}
/* Define our own new and delete. */
RTMEMEF_NEW_AND_DELETE_OPERATORS();
};
/** @} */
#endif /* !IPRT_INCLUDED_cpp_mtlist_h */

249
include/iprt/cpp/path.h Normal file
View file

@ -0,0 +1,249 @@
/** @file
* IPRT - C++ path utilities.
*/
/*
* Copyright (C) 2017-2023 Oracle and/or its affiliates.
*
* This file is part of VirtualBox base platform packages, as
* available from https://www.virtualbox.org.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, in version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses>.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
* in the VirtualBox distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*
* SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
*/
#ifndef IPRT_INCLUDED_cpp_path_h
#define IPRT_INCLUDED_cpp_path_h
#ifndef RT_WITHOUT_PRAGMA_ONCE
# pragma once
#endif
#include <iprt/assert.h>
#include <iprt/errcore.h>
#include <iprt/path.h>
#include <iprt/cpp/ministring.h>
/** @defgroup grp_rt_cpp_path C++ Path Utilities
* @ingroup grp_rt_cpp
* @{
*/
/**
* RTPathAbs() wrapper for working directly on a RTCString instance.
*
* @returns IPRT status code.
* @param rStrAbs Reference to the destination string.
* @param pszRelative The relative source string.
*/
DECLINLINE(int) RTPathAbsCxx(RTCString &rStrAbs, const char *pszRelative)
{
Assert(rStrAbs.c_str() != pszRelative);
int rc = rStrAbs.reserveNoThrow(RTPATH_MAX);
if (RT_SUCCESS(rc))
{
unsigned cTries = 8;
for (;;)
{
char *pszDst = rStrAbs.mutableRaw();
size_t cbCap = rStrAbs.capacity();
rc = RTPathAbsEx(NULL, pszRelative, RTPATH_STR_F_STYLE_HOST, pszDst, &cbCap);
if (RT_SUCCESS(rc))
break;
*pszDst = '\0';
if (rc != VERR_BUFFER_OVERFLOW)
break;
if (--cTries == 0)
break;
rc = rStrAbs.reserveNoThrow(RT_MIN(RT_ALIGN_Z(cbCap, 64), RTPATH_MAX));
if (RT_FAILURE(rc))
break;
}
rStrAbs.jolt();
}
return rc;
}
/**
* RTPathAbs() wrapper for working directly on a RTCString instance.
*
* @returns IPRT status code.
* @param rStrAbs Reference to the destination string.
* @param rStrRelative Reference to the relative source string.
*/
DECLINLINE(int) RTPathAbsCxx(RTCString &rStrAbs, RTCString const &rStrRelative)
{
return RTPathAbsCxx(rStrAbs, rStrRelative.c_str());
}
/**
* RTPathAbsEx() wrapper for working directly on a RTCString instance.
*
* @returns IPRT status code.
* @param rStrAbs Reference to the destination string.
* @param pszBase The base path, optional.
* @param pszRelative The relative source string.
* @param fFlags RTPATH_STR_F_STYLE_XXX and RTPATHABS_F_XXX flags.
*/
DECLINLINE(int) RTPathAbsExCxx(RTCString &rStrAbs, const char *pszBase, const char *pszRelative, uint32_t fFlags = RTPATH_STR_F_STYLE_HOST)
{
Assert(rStrAbs.c_str() != pszRelative);
int rc = rStrAbs.reserveNoThrow(RTPATH_MAX);
if (RT_SUCCESS(rc))
{
unsigned cTries = 8;
for (;;)
{
char *pszDst = rStrAbs.mutableRaw();
size_t cbCap = rStrAbs.capacity();
rc = RTPathAbsEx(pszBase, pszRelative, fFlags, pszDst, &cbCap);
if (RT_SUCCESS(rc))
break;
*pszDst = '\0';
if (rc != VERR_BUFFER_OVERFLOW)
break;
if (--cTries == 0)
break;
rc = rStrAbs.reserveNoThrow(RT_MIN(RT_ALIGN_Z(cbCap, 64), RTPATH_MAX));
if (RT_FAILURE(rc))
break;
}
rStrAbs.jolt();
}
return rc;
}
DECLINLINE(int) RTPathAbsExCxx(RTCString &rStrAbs, RTCString const &rStrBase, RTCString const &rStrRelative, uint32_t fFlags = RTPATH_STR_F_STYLE_HOST)
{
return RTPathAbsExCxx(rStrAbs, rStrBase.c_str(), rStrRelative.c_str(), fFlags);
}
DECLINLINE(int) RTPathAbsExCxx(RTCString &rStrAbs, const char *pszBase, RTCString const &rStrRelative, uint32_t fFlags = RTPATH_STR_F_STYLE_HOST)
{
return RTPathAbsExCxx(rStrAbs, pszBase, rStrRelative.c_str(), fFlags);
}
DECLINLINE(int) RTPathAbsExCxx(RTCString &rStrAbs, RTCString const &rStrBase, const char *pszRelative, uint32_t fFlags = RTPATH_STR_F_STYLE_HOST)
{
return RTPathAbsExCxx(rStrAbs, rStrBase.c_str(), pszRelative, fFlags);
}
/**
* RTPathAppPrivateNoArch() wrapper for working directly on a RTCString instance.
*
* @returns IPRT status code.
* @param rStrDst Reference to the destination string.
*/
DECLINLINE(int) RTPathAppPrivateNoArchCxx(RTCString &rStrDst)
{
int rc = rStrDst.reserveNoThrow(RTPATH_MAX);
if (RT_SUCCESS(rc))
{
char *pszDst = rStrDst.mutableRaw();
rc = RTPathAppPrivateNoArch(pszDst, rStrDst.capacity());
if (RT_FAILURE(rc))
*pszDst = '\0';
rStrDst.jolt();
}
return rc;
}
/**
* RTPathAppend() wrapper for working directly on a RTCString instance.
*
* @returns IPRT status code.
* @param rStrDst Reference to the destination string.
* @param pszAppend One or more components to append to the path already
* present in @a rStrDst.
*/
DECLINLINE(int) RTPathAppendCxx(RTCString &rStrDst, const char *pszAppend)
{
Assert(rStrDst.c_str() != pszAppend);
size_t cbEstimate = rStrDst.length() + 1 + strlen(pszAppend) + 1;
int rc;
if (rStrDst.capacity() >= cbEstimate)
rc = VINF_SUCCESS;
else
rc = rStrDst.reserveNoThrow(RT_ALIGN_Z(cbEstimate, 8));
if (RT_SUCCESS(rc))
{
rc = RTPathAppend(rStrDst.mutableRaw(), rStrDst.capacity(), pszAppend);
if (rc == VERR_BUFFER_OVERFLOW)
{
rc = rStrDst.reserveNoThrow(RTPATH_MAX);
if (RT_SUCCESS(rc))
rc = RTPathAppend(rStrDst.mutableRaw(), rStrDst.capacity(), pszAppend);
}
rStrDst.jolt();
}
return rc;
}
/**
* RTPathAppend() wrapper for working directly on a RTCString instance.
*
* @returns IPRT status code.
* @param rStrDst Reference to the destination string.
* @param rStrAppend One or more components to append to the path already
* present in @a rStrDst.
*/
DECLINLINE(int) RTPathAppendCxx(RTCString &rStrDst, RTCString const &rStrAppend)
{
Assert(&rStrDst != &rStrAppend);
size_t cbEstimate = rStrDst.length() + 1 + rStrAppend.length() + 1;
int rc;
if (rStrDst.capacity() >= cbEstimate)
rc = VINF_SUCCESS;
else
rc = rStrDst.reserveNoThrow(RT_ALIGN_Z(cbEstimate, 8));
if (RT_SUCCESS(rc))
{
rc = RTPathAppend(rStrDst.mutableRaw(), rStrDst.capacity(), rStrAppend.c_str());
if (rc == VERR_BUFFER_OVERFLOW)
{
rc = rStrDst.reserveNoThrow(RTPATH_MAX);
if (RT_SUCCESS(rc))
rc = RTPathAppend(rStrDst.mutableRaw(), rStrDst.capacity(), rStrAppend.c_str());
}
rStrDst.jolt();
}
return rc;
}
/** @} */
#endif /* !IPRT_INCLUDED_cpp_path_h */

View file

@ -0,0 +1,139 @@
/** @file
* IPRT - C++ Representational State Transfer (REST) Any Object Class.
*/
/*
* Copyright (C) 2008-2023 Oracle and/or its affiliates.
*
* This file is part of VirtualBox base platform packages, as
* available from https://www.virtualbox.org.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, in version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses>.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
* in the VirtualBox distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*
* SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
*/
#ifndef IPRT_INCLUDED_cpp_restanyobject_h
#define IPRT_INCLUDED_cpp_restanyobject_h
#ifndef RT_WITHOUT_PRAGMA_ONCE
# pragma once
#endif
#include <iprt/cpp/restbase.h>
#include <iprt/cpp/restarray.h>
#include <iprt/cpp/reststringmap.h>
/** @defgroup grp_rt_cpp_restanyobj C++ Representational State Transfer (REST) Any Object Class.
* @ingroup grp_rt_cpp
* @{
*/
/**
* Wrapper object that can represent any kind of basic REST object.
*
* This class is the result of a couple of design choices made in our REST
* data model. If could have been avoided if we used pointers all over
* the place and didn't rely entirely on the object specific implementations
* of deserializeFromJson and fromString to do the deserializing or everything.
*
* The assumption, though, was that most of the data we're dealing with has a
* known structure and maps to fixed types. So, the data model was optimized
* for that rather than flexiblity here.
*/
class RT_DECL_CLASS RTCRestAnyObject : public RTCRestObjectBase
{
public:
/** Default constructor. */
RTCRestAnyObject() RT_NOEXCEPT;
/** Destructor. */
virtual ~RTCRestAnyObject();
/** Copy constructor. */
RTCRestAnyObject(RTCRestAnyObject const &a_rThat);
/** Copy assignment operator. */
RTCRestAnyObject &operator=(RTCRestAnyObject const &a_rThat);
/** Safe copy assignment method. */
int assignCopy(RTCRestAnyObject const &a_rThat) RT_NOEXCEPT;
/** Safe copy assignment method, boolean variant. */
int assignCopy(RTCRestBool const &a_rThat) RT_NOEXCEPT;
/** Safe copy assignment method, int64_t variant. */
int assignCopy(RTCRestInt64 const &a_rThat) RT_NOEXCEPT;
/** Safe copy assignment method, int32_t variant. */
int assignCopy(RTCRestInt32 const &a_rThat) RT_NOEXCEPT;
/** Safe copy assignment method, int16_t variant. */
int assignCopy(RTCRestInt16 const &a_rThat) RT_NOEXCEPT;
/** Safe copy assignment method, double variant. */
int assignCopy(RTCRestDouble const &a_rThat) RT_NOEXCEPT;
/** Safe copy assignment method, string variant. */
int assignCopy(RTCRestString const &a_rThat) RT_NOEXCEPT;
/** Safe copy assignment method, array variant. */
int assignCopy(RTCRestArray<RTCRestAnyObject> const &a_rThat) RT_NOEXCEPT;
/** Safe copy assignment method, string map variant. */
int assignCopy(RTCRestStringMap<RTCRestAnyObject> const &a_rThat) RT_NOEXCEPT;
/** Safe value assignment method, boolean variant. */
int assignValue(bool a_fValue) RT_NOEXCEPT;
/** Safe value assignment method, int64_t variant. */
int assignValue(int64_t a_iValue) RT_NOEXCEPT;
/** Safe value assignment method, int32_t variant. */
int assignValue(int32_t a_iValue) RT_NOEXCEPT;
/** Safe value assignment method, int16_t variant. */
int assignValue(int16_t a_iValue) RT_NOEXCEPT;
/** Safe value assignment method, double variant. */
int assignValue(double a_iValue) RT_NOEXCEPT;
/** Safe value assignment method, string variant. */
int assignValue(RTCString const &a_rValue) RT_NOEXCEPT;
/** Safe value assignment method, C-string variant. */
int assignValue(const char *a_pszValue) RT_NOEXCEPT;
/** Make a clone of this object. */
inline RTCRestAnyObject *clone() const RT_NOEXCEPT { return (RTCRestAnyObject *)baseClone(); }
/* Overridden methods: */
virtual RTCRestObjectBase *baseClone() const RT_NOEXCEPT RT_OVERRIDE;
virtual int setNull(void) RT_NOEXCEPT RT_OVERRIDE;
virtual int resetToDefault() RT_NOEXCEPT RT_OVERRIDE;
virtual RTCRestOutputBase &serializeAsJson(RTCRestOutputBase &a_rDst) const RT_NOEXCEPT RT_OVERRIDE;
virtual int deserializeFromJson(RTCRestJsonCursor const &a_rCursor) RT_NOEXCEPT RT_OVERRIDE;
virtual int toString(RTCString *a_pDst, uint32_t a_fFlags = kCollectionFormat_Unspecified) const RT_NOEXCEPT RT_OVERRIDE;
virtual int fromString(RTCString const &a_rValue, const char *a_pszName, PRTERRINFO a_pErrInfo = NULL,
uint32_t a_fFlags = kCollectionFormat_Unspecified) RT_NOEXCEPT RT_OVERRIDE;
virtual kTypeClass typeClass(void) const RT_NOEXCEPT RT_OVERRIDE;
virtual const char *typeName(void) const RT_NOEXCEPT RT_OVERRIDE;
/** Factory method. */
static DECLCALLBACK(RTCRestObjectBase *) createInstance(void) RT_NOEXCEPT;
/** Deserialization w/ instantiation. */
static FNDESERIALIZEINSTANCEFROMJSON deserializeInstanceFromJson;
protected:
/** The data. */
RTCRestObjectBase *m_pData;
};
/** @} */
#endif /* !IPRT_INCLUDED_cpp_restanyobject_h */

View file

@ -0,0 +1,463 @@
/** @file
* IPRT - C++ Representational State Transfer (REST) Array Template Class.
*/
/*
* Copyright (C) 2008-2023 Oracle and/or its affiliates.
*
* This file is part of VirtualBox base platform packages, as
* available from https://www.virtualbox.org.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, in version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses>.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
* in the VirtualBox distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*
* SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
*/
#ifndef IPRT_INCLUDED_cpp_restarray_h
#define IPRT_INCLUDED_cpp_restarray_h
#ifndef RT_WITHOUT_PRAGMA_ONCE
# pragma once
#endif
#include <iprt/cpp/restbase.h>
/** @defgroup grp_rt_cpp_restarray C++ Representational State Transfer (REST) Array Template Class.
* @ingroup grp_rt_cpp
* @{
*/
/**
* Abstract base class for the RTCRestArray template.
*/
class RT_DECL_CLASS RTCRestArrayBase : public RTCRestObjectBase
{
public:
/** Default destructor. */
RTCRestArrayBase() RT_NOEXCEPT;
/** Destructor. */
virtual ~RTCRestArrayBase();
/* Overridden methods: */
virtual RTCRestObjectBase *baseClone() const RT_NOEXCEPT RT_OVERRIDE;
virtual int resetToDefault() RT_NOEXCEPT RT_OVERRIDE;
virtual RTCRestOutputBase &serializeAsJson(RTCRestOutputBase &a_rDst) const RT_NOEXCEPT RT_OVERRIDE;
virtual int deserializeFromJson(RTCRestJsonCursor const &a_rCursor) RT_NOEXCEPT RT_OVERRIDE;
virtual int toString(RTCString *a_pDst, uint32_t a_fFlags = kCollectionFormat_Unspecified) const RT_NOEXCEPT RT_OVERRIDE;
virtual int fromString(RTCString const &a_rValue, const char *a_pszName, PRTERRINFO a_pErrInfo = NULL,
uint32_t a_fFlags = kCollectionFormat_Unspecified) RT_NOEXCEPT RT_OVERRIDE;
virtual kTypeClass typeClass(void) const RT_NOEXCEPT RT_OVERRIDE;
virtual const char *typeName(void) const RT_NOEXCEPT RT_OVERRIDE;
/**
* Clear the content of the map.
*/
void clear() RT_NOEXCEPT;
/**
* Check if an list contains any items.
*
* @return True if there is more than zero items, false otherwise.
*/
inline bool isEmpty() const RT_NOEXCEPT
{
return m_cElements == 0;
}
/**
* Gets the number of entries in the map.
*/
inline size_t size() const RT_NOEXCEPT
{
return m_cElements;
}
/**
* Returns the base object pointer at a given index.
*
* @returns The base object at @a a_idx, NULL if out of range.
* @param a_idx The array index.
*/
inline RTCRestObjectBase *atBase(size_t a_idx) RT_NOEXCEPT
{
if (a_idx < m_cElements)
return m_papElements[a_idx];
return NULL;
}
/**
* Returns the const base object pointer at a given index.
*
* @returns The base object at @a a_idx, NULL if out of range.
* @param a_idx The array index.
*/
inline RTCRestObjectBase const *atBase(size_t a_idx) const RT_NOEXCEPT
{
if (a_idx < m_cElements)
return m_papElements[a_idx];
return NULL;
}
/**
* Removes the element at @a a_idx.
* @returns true if @a a_idx is valid, false if out of range.
* @param a_idx The index of the element to remove.
* The value ~(size_t)0 is an alias for the final element.
*/
bool removeAt(size_t a_idx) RT_NOEXCEPT;
/**
* Makes sure the array can hold at the given number of entries.
*
* @returns VINF_SUCCESS or VERR_NO_MEMORY.
* @param a_cEnsureCapacity The number of elements to ensure capacity to hold.
*/
int ensureCapacity(size_t a_cEnsureCapacity) RT_NOEXCEPT;
protected:
/** The array. */
RTCRestObjectBase **m_papElements;
/** Number of elements in the array. */
size_t m_cElements;
/** The number of elements m_papElements can hold.
* The difference between m_cCapacity and m_cElements are all NULLs. */
size_t m_cCapacity;
/**
* Helper for creating a clone.
*
* @returns Pointer to new array on success, NULL if out of memory.
*/
virtual RTCRestArrayBase *createClone(void) const RT_NOEXCEPT = 0;
/**
* Wrapper around the value constructor.
*
* @returns Pointer to new value object on success, NULL if out of memory.
*/
virtual RTCRestObjectBase *createValue(void) RT_NOEXCEPT = 0;
/**
* For accessing the static deserializeInstanceFromJson() method of the value.
*/
virtual int deserializeValueInstanceFromJson(RTCRestJsonCursor const &a_rCursor, RTCRestObjectBase **a_ppInstance) RT_NOEXCEPT = 0;
/**
* Worker for the copy assignment method and copyArrayWorkerMayThrow().
*
* This will use createEntryCopy to do the copying.
*
* @returns VINF_SUCCESS on success, VERR_NO_MEMORY or VERR_NO_STR_MEMORY on failure.
* @param a_rThat The array to copy. Caller makes 100% sure the it has
* the same type as the destination.
*/
int copyArrayWorkerNoThrow(RTCRestArrayBase const &a_rThat) RT_NOEXCEPT;
/**
* Wrapper around copyArrayWorkerNoThrow for the copy constructor and the
* assignment operator.
*/
void copyArrayWorkerMayThrow(RTCRestArrayBase const &a_rThat);
/**
* Worker for performing inserts.
*
* @returns VINF_SUCCESS or VWRN_ALREADY_EXISTS on success.
* VERR_ALREADY_EXISTS, VERR_NO_MEMORY or VERR_NO_STR_MEMORY on failure.
* @param a_idx Where to insert it. The value ~(size_t)0 is an alias for m_cElements.
* @param a_pValue The value to insert. Ownership is transferred to the map on success.
* @param a_fReplace Whether to replace existing entry rather than insert.
*/
int insertWorker(size_t a_idx, RTCRestObjectBase *a_pValue, bool a_fReplace) RT_NOEXCEPT;
/**
* Worker for performing inserts.
*
* @returns VINF_SUCCESS or VWRN_ALREADY_EXISTS on success.
* VERR_ALREADY_EXISTS, VERR_NO_MEMORY or VERR_NO_STR_MEMORY on failure.
* @param a_idx Where to insert it. The value ~(size_t)0 is an alias for m_cElements.
* @param a_rValue The value to copy into the map.
* @param a_fReplace Whether to replace existing key-value pair with matching key.
*/
int insertCopyWorker(size_t a_idx, RTCRestObjectBase const &a_rValue, bool a_fReplace) RT_NOEXCEPT;
private:
/** Copy constructor on this class should never be used. */
RTCRestArrayBase(RTCRestArrayBase const &a_rThat);
/** Copy assignment operator on this class should never be used. */
RTCRestArrayBase &operator=(RTCRestArrayBase const &a_rThat);
};
/**
* Limited array class.
*/
template<class ElementType> class RTCRestArray : public RTCRestArrayBase
{
public:
/** Default constructor - empty array. */
RTCRestArray() RT_NOEXCEPT
: RTCRestArrayBase()
{
}
/** Destructor. */
~RTCRestArray()
{
}
/** Copy constructor. */
RTCRestArray(RTCRestArray const &a_rThat)
: RTCRestArrayBase()
{
copyArrayWorkerMayThrow(a_rThat);
}
/** Copy assignment operator. */
inline RTCRestArray &operator=(RTCRestArray const &a_rThat)
{
copyArrayWorkerMayThrow(a_rThat);
return *this;
}
/** Safe copy assignment method. */
inline int assignCopy(RTCRestArray const &a_rThat) RT_NOEXCEPT
{
return copyArrayWorkerNoThrow(a_rThat);
}
/** Make a clone of this object. */
inline RTCRestArray *clone() const RT_NOEXCEPT
{
return (RTCRestArray *)baseClone();
}
/** Factory method. */
static DECLCALLBACK(RTCRestObjectBase *) createInstance(void) RT_NOEXCEPT
{
return new (std::nothrow) RTCRestArray<ElementType>();
}
/** Factory method for elements. */
static DECLCALLBACK(RTCRestObjectBase *) createElementInstance(void) RT_NOEXCEPT
{
return new (std::nothrow) ElementType();
}
/** @copydoc RTCRestObjectBase::FNDESERIALIZEINSTANCEFROMJSON */
static DECLCALLBACK(int) deserializeInstanceFromJson(RTCRestJsonCursor const &a_rCursor, RTCRestObjectBase **a_ppInstance) RT_NOEXCEPT
{
*a_ppInstance = new (std::nothrow) RTCRestArray<ElementType>();
if (*a_ppInstance)
return (*a_ppInstance)->deserializeFromJson(a_rCursor);
return a_rCursor.m_pPrimary->addError(a_rCursor, VERR_NO_MEMORY, "Out of memory");
}
/**
* Insert the given object at the specified index.
*
* @returns VINF_SUCCESS on success.
* VERR_INVALID_POINTER, VERR_NO_MEMORY, VERR_NO_STR_MEMORY or VERR_OUT_OF_RANGE on failure.
* @param a_idx The insertion index. ~(size_t)0 is an alias for the end.
* @param a_pThat The object to insert. The array takes ownership of the object on success.
*/
inline int insert(size_t a_idx, ElementType *a_pThat) RT_NOEXCEPT
{
return insertWorker(a_idx, a_pThat, false /*a_fReplace*/);
}
/**
* Insert a copy of the object at the specified index.
*
* @returns VINF_SUCCESS on success.
* VERR_NO_MEMORY, VERR_NO_STR_MEMORY or VERR_OUT_OF_RANGE on failure.
* @param a_idx The insertion index. ~(size_t)0 is an alias for the end.
* @param a_rThat The object to insert a copy of.
*/
inline int insertCopy(size_t a_idx, ElementType const &a_rThat) RT_NOEXCEPT
{
return insertCopyWorker(a_idx, a_rThat, false /*a_fReplace*/);
}
/**
* Appends the given object to the array.
*
* @returns VINF_SUCCESS on success.
* VERR_INVALID_POINTER, VERR_NO_MEMORY, VERR_NO_STR_MEMORY or VERR_OUT_OF_RANGE on failure.
* @param a_pThat The object to insert. The array takes ownership of the object on success.
*/
inline int append(ElementType *a_pThat) RT_NOEXCEPT
{
return insertWorker(~(size_t)0, a_pThat, false /*a_fReplace*/);
}
/**
* Appends a copy of the object at the specified index.
*
* @returns VINF_SUCCESS on success.
* VERR_NO_MEMORY, VERR_NO_STR_MEMORY or VERR_OUT_OF_RANGE on failure.
* @param a_rThat The object to insert a copy of.
*/
inline int appendCopy(ElementType const &a_rThat) RT_NOEXCEPT
{
return insertCopyWorker(~(size_t)0, a_rThat, false /*a_fReplace*/);
}
/**
* Prepends the given object to the array.
*
* @returns VINF_SUCCESS on success.
* VERR_INVALID_POINTER, VERR_NO_MEMORY, VERR_NO_STR_MEMORY or VERR_OUT_OF_RANGE on failure.
* @param a_pThat The object to insert. The array takes ownership of the object on success.
*/
inline int prepend(ElementType *a_pThat) RT_NOEXCEPT
{
return insertWorker(0, a_pThat, false /*a_fReplace*/);
}
/**
* Prepends a copy of the object at the specified index.
*
* @returns VINF_SUCCESS on success.
* VERR_NO_MEMORY, VERR_NO_STR_MEMORY or VERR_OUT_OF_RANGE on failure.
* @param a_rThat The object to insert a copy of.
*/
inline int prependCopy(ElementType const &a_rThat) RT_NOEXCEPT
{
return insertCopyWorker(0, a_rThat, false /*a_fReplace*/);
}
/**
* Insert the given object at the specified index.
*
* @returns VINF_SUCCESS on success.
* VERR_INVALID_POINTER, VERR_NO_MEMORY, VERR_NO_STR_MEMORY or VERR_OUT_OF_RANGE on failure.
* @param a_idx The index of the existing object to replace.
* @param a_pThat The replacement object. The array takes ownership of the object on success.
*/
inline int replace(size_t a_idx, ElementType *a_pThat) RT_NOEXCEPT
{
return insertWorker(a_idx, a_pThat, true /*a_fReplace*/);
}
/**
* Insert a copy of the object at the specified index.
*
* @returns VINF_SUCCESS on success.
* VERR_NO_MEMORY, VERR_NO_STR_MEMORY or VERR_OUT_OF_RANGE on failure.
* @param a_idx The index of the existing object to replace.
* @param a_rThat The object to insert a copy of.
*/
inline int replaceCopy(size_t a_idx, ElementType const &a_rThat) RT_NOEXCEPT
{
return insertCopyWorker(a_idx, a_rThat, true /*a_fReplace*/);
}
/**
* Returns the object at a given index.
*
* @returns The object at @a a_idx, NULL if out of range.
* @param a_idx The array index.
*/
inline ElementType *at(size_t a_idx) RT_NOEXCEPT
{
if (a_idx < m_cElements)
return (ElementType *)m_papElements[a_idx];
return NULL;
}
/**
* Returns the object at a given index, const variant.
*
* @returns The object at @a a_idx, NULL if out of range.
* @param a_idx The array index.
*/
inline ElementType const *at(size_t a_idx) const RT_NOEXCEPT
{
if (a_idx < m_cElements)
return (ElementType const *)m_papElements[a_idx];
return NULL;
}
/**
* Returns the first object in the array.
* @returns The first object, NULL if empty.
*/
inline ElementType *first() RT_NOEXCEPT
{
return at(0);
}
/**
* Returns the first object in the array, const variant.
* @returns The first object, NULL if empty.
*/
inline ElementType const *first() const RT_NOEXCEPT
{
return at(0);
}
/**
* Returns the last object in the array.
* @returns The last object, NULL if empty.
*/
inline ElementType *last() RT_NOEXCEPT
{
return at(m_cElements - 1);
}
/**
* Returns the last object in the array, const variant.
* @returns The last object, NULL if empty.
*/
inline ElementType const *last() const RT_NOEXCEPT
{
return at(m_cElements - 1);
}
protected:
virtual RTCRestArrayBase *createClone(void) const RT_NOEXCEPT RT_OVERRIDE
{
return new (std::nothrow) RTCRestArray();
}
virtual RTCRestObjectBase *createValue(void) RT_NOEXCEPT RT_OVERRIDE
{
return new (std::nothrow) ElementType();
}
virtual int deserializeValueInstanceFromJson(RTCRestJsonCursor const &a_rCursor, RTCRestObjectBase **a_ppInstance) RT_NOEXCEPT RT_OVERRIDE
{
return ElementType::deserializeInstanceFromJson(a_rCursor, a_ppInstance);
}
};
/** @} */
#endif /* !IPRT_INCLUDED_cpp_restarray_h */

1106
include/iprt/cpp/restbase.h Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,824 @@
/** @file
* IPRT - C++ Representational State Transfer (REST) Client Classes.
*/
/*
* Copyright (C) 2008-2023 Oracle and/or its affiliates.
*
* This file is part of VirtualBox base platform packages, as
* available from https://www.virtualbox.org.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, in version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses>.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
* in the VirtualBox distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*
* SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
*/
#ifndef IPRT_INCLUDED_cpp_restclient_h
#define IPRT_INCLUDED_cpp_restclient_h
#ifndef RT_WITHOUT_PRAGMA_ONCE
# pragma once
#endif
#include <iprt/http.h>
#include <iprt/cpp/restbase.h>
#include <iprt/cpp/reststringmap.h>
/** @defgroup grp_rt_cpp_restclient C++ Representational State Transfer (REST) Client Classes.
* @ingroup grp_rt_cpp
* @{
*/
/**
* Specialization of RTCRestBinary for use with body parameters in a client.
*
* This enables registering data callbacks for provinding data to upload.
*/
class RT_DECL_CLASS RTCRestBinaryParameter : public RTCRestBinary
{
public:
/** Default constructor. */
RTCRestBinaryParameter() RT_NOEXCEPT;
/** Safe copy assignment method. */
virtual int assignCopy(RTCRestBinaryParameter const &a_rThat) RT_NOEXCEPT;
/** Safe copy assignment method.
* @note Resets callbacks and ASSUMES that @a a_cbData is the content length. */
virtual int assignCopy(RTCRestBinary const &a_rThat) RT_NOEXCEPT RT_OVERRIDE;
/** Safe copy assignment method.
* @note Resets callbacks and ASSUMES that @a a_cbData is the content length. */
virtual int assignCopy(void const *a_pvData, size_t a_cbData) RT_NOEXCEPT RT_OVERRIDE;
/**
* Use the specified data buffer directly.
* @note Resets callbacks and ASSUMES that @a a_cbData is the content length. */
virtual int assignReadOnly(void const *a_pvData, size_t a_cbData) RT_NOEXCEPT RT_OVERRIDE;
/**
* Use the specified data buffer directly.
* @note This will assert and work like assignReadOnly. */
virtual int assignWriteable(void *a_pvBuf, size_t a_cbBuf) RT_NOEXCEPT RT_OVERRIDE;
/** Make a clone of this object. */
inline RTCRestBinaryParameter *clone() const RT_NOEXCEPT { return (RTCRestBinaryParameter *)baseClone(); }
/* Overridden methods: */
virtual RTCRestObjectBase *baseClone() const RT_NOEXCEPT RT_OVERRIDE;
virtual int resetToDefault() RT_NOEXCEPT RT_OVERRIDE;
virtual const char *typeName(void) const RT_NOEXCEPT RT_OVERRIDE;
/** Factory method. */
static DECLCALLBACK(RTCRestObjectBase *) createInstance(void) RT_NOEXCEPT;
/**
* Retrieves the callback data.
*/
inline void *getCallbackData() const RT_NOEXCEPT { return m_pvCallbackData; }
/**
* Sets the content-type for an upload.
*
* @returns VINF_SUCCESS or VERR_NO_STR_MEMORY.
* @param a_pszContentType The content type to set.
* If NULL, no content type is set.
*/
int setContentType(const char *a_pszContentType) RT_NOEXCEPT;
/**
* Gets the content type that was set.
*/
inline RTCString const &getContentType() const RT_NOEXCEPT { return m_strContentType; }
/**
* Gets the content-length value (UINT64_MAX if not available).
*/
inline uint64_t getContentLength() const RT_NOEXCEPT { return m_cbContentLength; }
/**
* Callback for producing bytes to upload.
*
* @returns IPRT status code.
* @param a_pThis The related string object.
* @param a_pvDst Where to put the bytes.
* @param a_cbDst Max number of bytes to produce.
* @param a_offContent The byte offset corresponding to the start of @a a_pvDst.
* @param a_pcbActual Where to return the number of bytes actually produced.
*
* @remarks Use getCallbackData to get the user data.
*
* @note The @a a_offContent parameter does not imply random access or anthing
* like that, it is just a convenience provided by the caller. The value
* is the sum of the previously returned @a *pcbActual values.
*/
typedef DECLCALLBACKTYPE(int, FNPRODUCER,(RTCRestBinaryParameter *a_pThis, void *a_pvDst, size_t a_cbDst,
uint64_t a_offContent, size_t *a_pcbActual)) /*RT_NOEXCEPT*/;
/** Pointer to a byte producer callback. */
typedef FNPRODUCER *PFNPRODUCER;
/**
* Sets the producer callback.
*
* @param a_pfnProducer The callback function for producing data.
* @param a_pvCallbackData Data the can be retrieved from the callback
* using getCallbackData().
* @param a_cbContentLength The amount of data that will be uploaded and
* to be set as the value of the content-length
* header field. Pass UINT64_MAX if not known.
*
* @note This will drop any buffer previously registered using setUploadData().
*/
void setProducerCallback(PFNPRODUCER a_pfnProducer, void *a_pvCallbackData = NULL, uint64_t a_cbContentLength = UINT64_MAX) RT_NOEXCEPT;
/**
* Preprares transmission via the @a a_hHttp client instance.
*
* @returns IPRT status code.
* @param a_hHttp The HTTP client instance.
* @internal
*/
virtual int xmitPrepare(RTHTTP a_hHttp) const RT_NOEXCEPT;
/**
* For completing and/or undoing setup from xmitPrepare.
*
* @param a_hHttp The HTTP client instance.
* @internal
*/
virtual void xmitComplete(RTHTTP a_hHttp) const RT_NOEXCEPT;
protected:
/** Number of bytes corresponding to content-length.
* UINT64_MAX if not known. Used both for unploads and downloads. */
uint64_t m_cbContentLength;
/** The content type if set (upload only). */
RTCString m_strContentType;
/** Pointer to user-registered producer callback function (upload only). */
PFNPRODUCER m_pfnProducer;
/** User argument for both callbacks (both). */
void *m_pvCallbackData;
/** @copydoc FNRTHTTPUPLOADCALLBACK */
static DECLCALLBACK(int) xmitHttpCallback(RTHTTP hHttp, void *pvBuf, size_t cbBuf, uint64_t offContent,
size_t *pcbActual, void *pvUser) RT_NOEXCEPT;
private:
/* No copy constructor or copy assignment: */
RTCRestBinaryParameter(RTCRestBinaryParameter const &a_rThat);
RTCRestBinaryParameter &operator=(RTCRestBinaryParameter const &a_rThat);
};
/**
* Specialization of RTCRestBinary for use with responses in a client.
*
* This enables registering data callbacks for consuming downloaded data.
*/
class RT_DECL_CLASS RTCRestBinaryResponse : public RTCRestBinary
{
public:
/** Default constructor. */
RTCRestBinaryResponse() RT_NOEXCEPT;
/** Safe copy assignment method. */
virtual int assignCopy(RTCRestBinaryResponse const &a_rThat) RT_NOEXCEPT;
/** Safe copy assignment method. */
virtual int assignCopy(RTCRestBinary const &a_rThat) RT_NOEXCEPT RT_OVERRIDE;
/** Safe copy assignment method.
* @note This will assert and fail as it makes no sense for a download. */
virtual int assignCopy(void const *a_pvData, size_t a_cbData) RT_NOEXCEPT RT_OVERRIDE;
/**
* Use the specified data buffer directly.
* @note This will assert and fail as it makes no sense for a download.
*/
virtual int assignReadOnly(void const *a_pvData, size_t a_cbData) RT_NOEXCEPT RT_OVERRIDE;
/**
* Use the specified data buffer directly.
* @note This will drop any previously registered producer callback and user data.
*/
virtual int assignWriteable(void *a_pvBuf, size_t a_cbBuf) RT_NOEXCEPT RT_OVERRIDE;
/** Make a clone of this object. */
inline RTCRestBinaryResponse *clone() const RT_NOEXCEPT { return (RTCRestBinaryResponse *)baseClone(); }
/* Overridden methods: */
virtual RTCRestObjectBase *baseClone() const RT_NOEXCEPT RT_OVERRIDE;
virtual int resetToDefault() RT_NOEXCEPT RT_OVERRIDE;
virtual const char *typeName(void) const RT_NOEXCEPT RT_OVERRIDE;
/** Factory method. */
static DECLCALLBACK(RTCRestObjectBase *) createInstance(void) RT_NOEXCEPT;
/**
* Retrieves the callback data.
*/
inline void *getCallbackData() const RT_NOEXCEPT { return m_pvCallbackData; }
/**
* Sets the max size to download to memory.
*
* This also indicates the intention to download to a memory buffer, so it
* will drop any previously registered consumer callback and its user data.
*
* @param a_cbMaxDownload Maximum number of bytes to download to memory.
* If 0, a default is selected (currently 32MiB for
* 32-bit hosts and 128MiB for 64-bit).
*/
void setMaxDownloadSize(size_t a_cbMaxDownload) RT_NOEXCEPT;
/**
* Gets the content-length value (UINT64_MAX if not available).
*/
inline uint64_t getContentLength() const RT_NOEXCEPT { return m_cbContentLength; }
/**
* Callback for consuming downloaded bytes.
*
* @returns IPRT status code.
* @param a_pThis The related string object.
* @param a_pvSrc Buffer containing the bytes.
* @param a_cbSrc The number of bytes in the buffer.
* @param a_uHttpStatus The HTTP status code.
* @param a_offContent The byte offset corresponding to the start of @a a_pvSrc.
* @param a_cbContent The content length field value, UINT64_MAX if not available.
*
* @remarks Use getCallbackData to get the user data.
*
* @note The @a a_offContent parameter does not imply random access or anthing
* like that, it is just a convenience provided by the caller. The value
* is the sum of the previous @a a_cbSrc values.
*/
typedef DECLCALLBACKTYPE(int, FNCONSUMER,(RTCRestBinaryResponse *a_pThis, const void *a_pvSrc, size_t a_cbSrc,
uint32_t a_uHttpStatus, uint64_t a_offContent, uint64_t a_cbContent)) /*RT_NOEXCEPT*/;
/** Pointer to a byte consumer callback. */
typedef FNCONSUMER *PFNCONSUMER;
/**
* Sets the consumer callback.
*
* @param a_pfnConsumer The callback function for consuming downloaded data.
* NULL if data should be stored in m_pbData (the default).
* @param a_pvCallbackData Data the can be retrieved from the callback
* using getCallbackData().
*/
void setConsumerCallback(PFNCONSUMER a_pfnConsumer, void *a_pvCallbackData = NULL) RT_NOEXCEPT;
/**
* Preprares for receiving via the @a a_hHttp client instance.
*
* @returns IPRT status code.
* @param a_hHttp The HTTP client instance.
* @param a_fCallbackFlags The HTTP callback flags (status code spec).
* @internal
*/
virtual int receivePrepare(RTHTTP a_hHttp, uint32_t a_fCallbackFlags) RT_NOEXCEPT;
/**
* For completing and/or undoing setup from receivePrepare.
*
* @param a_hHttp The HTTP client instance.
* @internal
*/
virtual void receiveComplete(RTHTTP a_hHttp) RT_NOEXCEPT;
protected:
/** Number of bytes corresponding to content-length.
* UINT64_MAX if not known. Used both for unploads and downloads. */
uint64_t m_cbContentLength;
/** Number of bytes downloaded thus far. */
uint64_t m_cbDownloaded;
/** Pointer to user-registered consumer callback function (download only). */
PFNCONSUMER m_pfnConsumer;
/** User argument for both callbacks (both). */
void *m_pvCallbackData;
/** Maximum data to download to memory (download only). */
size_t m_cbMaxDownload;
/** @copydoc FNRTHTTPDOWNLOADCALLBACK */
static DECLCALLBACK(int) receiveHttpCallback(RTHTTP hHttp, void const *pvBuf, size_t cbBuf, uint32_t uHttpStatus,
uint64_t offContent, uint64_t cbContent, void *pvUser) RT_NOEXCEPT;
private:
/* No copy constructor or copy assignment: */
RTCRestBinaryResponse(RTCRestBinaryResponse const &a_rThat);
RTCRestBinaryResponse &operator=(RTCRestBinaryResponse const &a_rThat);
};
/**
* Base class for REST client requests.
*
* This encapsulates parameters and helps transform them into a HTTP request.
*
* Parameters can be transfered in a number of places:
* - Path part of the URL.
* - Query part of the URL.
* - HTTP header fields.
* - FORM body.
* - JSON body.
* - XML body.
* - ...
*
* They can be require or optional. The latter may have default values. In
* swagger 3 they can also be nullable, which means the null-indicator cannot
* be used for tracking optional parameters.
*/
class RT_DECL_CLASS RTCRestClientRequestBase
{
public:
RTCRestClientRequestBase() RT_NOEXCEPT;
virtual ~RTCRestClientRequestBase();
RTCRestClientRequestBase(RTCRestClientRequestBase const &a_rThat) RT_NOEXCEPT;
RTCRestClientRequestBase &operator=(RTCRestClientRequestBase const &a_rThat) RT_NOEXCEPT;
/**
* Reset all members to default values.
* @returns IPRT status code.
*/
virtual int resetToDefault() RT_NOEXCEPT = 0;
/**
* Getter for the operation name. Provided by the generated
* subclasses so that base class code may use it for more
* informative logs.
*/
virtual const char *getOperationName() const RT_NOEXCEPT = 0;
/**
* Prepares the HTTP handle for transmitting this request.
*
* @returns IPRT status code.
* @param a_pStrPath Where to set path parameters. Will be appended to the base path.
* @param a_pStrQuery Where to set query parameters.
* @param a_hHttp Where to set header parameters and such.
* @param a_pStrBody Where to set body parameters.
*/
virtual int xmitPrepare(RTCString *a_pStrPath, RTCString *a_pStrQuery, RTHTTP a_hHttp, RTCString *a_pStrBody) const RT_NOEXCEPT = 0;
/**
* Always called after the request has been transmitted.
*
* @param a_rcStatus Negative numbers are IPRT errors, positive are HTTP status codes.
* @param a_hHttp The HTTP handle the request was performed on.
*/
virtual void xmitComplete(int a_rcStatus, RTHTTP a_hHttp) const RT_NOEXCEPT = 0;
/**
* Checks if there are were any assignment errors.
*/
inline bool hasAssignmentErrors() const RT_NOEXCEPT { return m_fErrorSet != 0; }
protected:
/** Set of fields that have been explicitly assigned a value. */
uint64_t m_fIsSet;
/** Set of fields where value assigning failed. */
uint64_t m_fErrorSet;
/** Path parameter descriptor. */
typedef struct
{
const char *pszName; /**< The name string to replace (including {}). */
size_t cchName; /**< Length of pszName. */
uint32_t fFlags; /**< The toString flags. */
uint8_t iBitNo; /**< The parameter bit number. */
} PATHPARAMDESC;
/** Path parameter state. */
typedef struct
{
RTCRestObjectBase const *pObj; /**< Pointer to the parameter object. */
size_t offName; /**< Maintained by worker. */
} PATHPARAMSTATE;
/**
* Do path parameters.
*
* @returns IPRT status code
* @param a_pStrPath The destination path.
* @param a_pszPathTemplate The path template string.
* @param a_cchPathTemplate The length of the path template string.
* @param a_paPathParams The path parameter descriptors (static).
* @param a_paPathParamStates The path parameter objects and states.
* @param a_cPathParams Number of path parameters.
*/
int doPathParameters(RTCString *a_pStrPath, const char *a_pszPathTemplate, size_t a_cchPathTemplate,
PATHPARAMDESC const *a_paPathParams, PATHPARAMSTATE *a_paPathParamStates, size_t a_cPathParams) const RT_NOEXCEPT;
/** Query parameter descriptor. */
typedef struct
{
const char *pszName; /**< The parameter name. */
uint32_t fFlags; /**< The toString flags. */
bool fRequired; /**< Required or not. */
uint8_t iBitNo; /**< The parameter bit number. */
} QUERYPARAMDESC;
/**
* Do query parameters.
*
* @returns IPRT status code
* @param a_pStrQuery The destination string.
* @param a_paQueryParams The query parameter descriptors.
* @param a_papQueryParamObjs The query parameter objects, parallel to @a a_paQueryParams.
* @param a_cQueryParams Number of query parameters.
*/
int doQueryParameters(RTCString *a_pStrQuery, QUERYPARAMDESC const *a_paQueryParams,
RTCRestObjectBase const **a_papQueryParamObjs, size_t a_cQueryParams) const RT_NOEXCEPT;
/** Header parameter descriptor. */
typedef struct
{
const char *pszName; /**< The parameter name. */
uint32_t fFlags; /**< The toString flags. */
bool fRequired; /**< Required or not. */
uint8_t iBitNo; /**< The parameter bit number. */
bool fMapCollection; /**< Collect headers starting with pszName into a map. */
} HEADERPARAMDESC;
/**
* Do header parameters.
*
* @returns IPRT status code
* @param a_hHttp Where to set header parameters.
* @param a_paHeaderParams The header parameter descriptors.
* @param a_papHeaderParamObjs The header parameter objects, parallel to @a a_paHeaderParams.
* @param a_cHeaderParams Number of header parameters.
*/
int doHeaderParameters(RTHTTP a_hHttp, HEADERPARAMDESC const *a_paHeaderParams,
RTCRestObjectBase const **a_papHeaderParamObjs, size_t a_cHeaderParams) const RT_NOEXCEPT;
};
/**
* Base class for REST client responses.
*/
class RT_DECL_CLASS RTCRestClientResponseBase
{
public:
/** Default constructor. */
RTCRestClientResponseBase() RT_NOEXCEPT;
/** Destructor. */
virtual ~RTCRestClientResponseBase();
/** Copy constructor. */
RTCRestClientResponseBase(RTCRestClientResponseBase const &a_rThat);
/** Copy assignment operator. */
RTCRestClientResponseBase &operator=(RTCRestClientResponseBase const &a_rThat);
/**
* Resets the object state.
*/
virtual void reset(void) RT_NOEXCEPT;
/**
* Getter for the operation name. Provided by the generated
* subclasses so that base class code may use it for more
* informative logs.
*/
virtual const char *getOperationName() const RT_NOEXCEPT = 0;
/**
* Prepares the HTTP handle for receiving the response.
*
* This may install callbacks and such like.
*
* When overridden, the parent class must always be called.
*
* @returns IPRT status code.
* @param a_hHttp The HTTP handle to prepare for receiving.
*/
virtual int receivePrepare(RTHTTP a_hHttp) RT_NOEXCEPT;
/**
* Called when the HTTP request has been completely received.
*
* @param a_rcStatus Negative numbers are IPRT errors, positive are HTTP status codes.
* @param a_hHttp The HTTP handle the request was performed on.
* This can be NIL_RTHTTP should something fail early, in
* which case it is possible receivePrepare() wasn't called.
*
* @note Called before consumeBody() but after consumeHeader().
*/
virtual void receiveComplete(int a_rcStatus, RTHTTP a_hHttp) RT_NOEXCEPT;
/**
* Callback that consumes HTTP body data from the server.
*
* @param a_pchData Body data.
* @param a_cbData Amount of body data.
*
* @note Called after consumeHeader().
*/
virtual void consumeBody(const char *a_pchData, size_t a_cbData) RT_NOEXCEPT;
/**
* Called after status, headers and body all have been presented.
*/
virtual void receiveFinal() RT_NOEXCEPT;
/**
* Getter for m_rcStatus.
* @returns Negative numbers are IPRT errors, positive are HTTP status codes.
*/
inline int getStatus() const RT_NOEXCEPT { return m_rcStatus; }
/**
* Getter for m_rcHttp.
* @returns HTTP status code or VERR_NOT_AVAILABLE.
*/
inline int getHttpStatus() const RT_NOEXCEPT { return m_rcHttp; }
/**
* Getter for m_pErrInfo.
*/
inline PCRTERRINFO getErrInfo(void) const RT_NOEXCEPT { return m_pErrInfo; }
/**
* Getter for m_strContentType.
*/
inline RTCString const &getContentType(void) const RT_NOEXCEPT { return m_strContentType; }
protected:
/** Negative numbers are IPRT errors, positive are HTTP status codes. */
int m_rcStatus;
/** The HTTP status code, VERR_NOT_AVAILABLE if not set. */
int m_rcHttp;
/** Error information. */
PRTERRINFO m_pErrInfo;
/** The value of the Content-Type header field. */
RTCString m_strContentType;
PRTERRINFO getErrInfoInternal(void) RT_NOEXCEPT;
void deleteErrInfo(void) RT_NOEXCEPT;
void copyErrInfo(PCRTERRINFO pErrInfo) RT_NOEXCEPT;
/**
* Reports an error (or warning if a_rc non-negative).
*
* @returns a_rc
* @param a_rc The status code to report and return. The first
* error status is assigned to m_rcStatus, subsequent
* ones as well as informational statuses are not
* recorded by m_rcStatus.
* @param a_pszFormat The message format string.
* @param ... Message arguments.
*/
int addError(int a_rc, const char *a_pszFormat, ...) RT_NOEXCEPT;
/**
* Deserializes a header field value.
*
* @returns IPRT status code.
* @param a_pObj The object to deserialize into.
* @param a_pchValue Pointer to the value (not zero terminated).
* Not necessarily valid UTF-8!
* @param a_cchValue The value length.
* @param a_fFlags Flags to pass to fromString().
* @param a_pszErrorTag The error tag (field name).
*/
int deserializeHeader(RTCRestObjectBase *a_pObj, const char *a_pchValue, size_t a_cchValue,
uint32_t a_fFlags, const char *a_pszErrorTag) RT_NOEXCEPT;
/**
* Deserializes a header field value.
*
* @returns IPRT status code.
* @param a_pMap The string map object to deserialize into.
* @param a_pchField Pointer to the map field name. (Caller dropped the prefix.)
* Not necessarily valid UTF-8!
* @param a_cchField Length of field name.
* @param a_pchValue Pointer to the value (not zero terminated).
* Not necessarily valid UTF-8!
* @param a_cchValue The value length.
* @param a_fFlags Flags to pass to fromString().
* @param a_pszErrorTag The error tag (field name).
*/
int deserializeHeaderIntoMap(RTCRestStringMapBase *a_pMap, const char *a_pchField, size_t a_cchField,
const char *a_pchValue, size_t a_cchValue, uint32_t a_fFlags, const char *a_pszErrorTag) RT_NOEXCEPT;
/**
* Helper that does the deserializing of the response body
* via deserializeBodyFromJsonCursor().
*
* @param a_pchData The body blob.
* @param a_cbData The size of the body blob.
* @param a_pszBodyName The name of the body parameter.
*/
void deserializeBody(const char *a_pchData, size_t a_cbData, const char *a_pszBodyName) RT_NOEXCEPT;
/**
* Called by deserializeBody to do the actual body deserialization.
*
* @param a_rCursor The JSON cursor.
*/
virtual void deserializeBodyFromJsonCursor(RTCRestJsonCursor const &a_rCursor) RT_NOEXCEPT;
/**
* Primary json cursor for parsing bodies.
*/
class PrimaryJsonCursorForBody : public RTCRestJsonPrimaryCursor
{
public:
RTCRestClientResponseBase *m_pThat; /**< Pointer to response object. */
PrimaryJsonCursorForBody(RTJSONVAL hValue, const char *pszName, RTCRestClientResponseBase *a_pThat) RT_NOEXCEPT;
virtual int addError(RTCRestJsonCursor const &a_rCursor, int a_rc, const char *a_pszFormat, ...) RT_NOEXCEPT RT_OVERRIDE;
virtual int unknownField(RTCRestJsonCursor const &a_rCursor) RT_NOEXCEPT RT_OVERRIDE;
};
/**
* Consumes a header.
*
* Child classes can override this to pick up their header fields, but must
* always call the parent class.
*
* @returns IPRT status code.
* @param a_uMatchWord Match word constructed by RTHTTP_MAKE_HDR_MATCH_WORD
* @param a_pchField The field name (not zero terminated).
* Not necessarily valid UTF-8!
* @param a_cchField The length of the field.
* @param a_pchValue The field value (not zero terminated).
* @param a_cchValue The length of the value.
*/
virtual int consumeHeader(uint32_t a_uMatchWord, const char *a_pchField, size_t a_cchField,
const char *a_pchValue, size_t a_cchValue) RT_NOEXCEPT;
private:
/** Callback for use with RTHttpSetHeaderCallback. */
static DECLCALLBACK(int) receiveHttpHeaderCallback(RTHTTP hHttp, uint32_t uMatchWord, const char *pchField, size_t cchField,
const char *pchValue, size_t cchValue, void *pvUser) RT_NOEXCEPT;
};
/**
* Base class for REST client responses.
*/
class RT_DECL_CLASS RTCRestClientApiBase
{
public:
RTCRestClientApiBase() RT_NOEXCEPT;
virtual ~RTCRestClientApiBase();
/** @name Host and Base path (URL) handling.
* @{ */
/**
* Gets the server URL.
*/
const char *getServerUrl(void) const RT_NOEXCEPT;
/**
* Sets the whole server URL.
* @returns IPRT status code.
* @param a_pszUrl The new server URL. NULL/empty to reset to default.
*/
int setServerUrl(const char *a_pszUrl) RT_NOEXCEPT;
/**
* Sets the scheme part of the the server URL.
* @returns IPRT status code.
* @param a_pszScheme The new scheme. Does not accept NULL or empty string.
*/
int setServerScheme(const char *a_pszScheme) RT_NOEXCEPT;
/**
* Sets the authority (hostname + port) part of the the server URL.
* @returns IPRT status code.
* @param a_pszAuthority The new authority. Does not accept NULL or empty string.
*/
int setServerAuthority(const char *a_pszAuthority) RT_NOEXCEPT;
/**
* Sets the base path part of the the server URL.
* @returns IPRT status code.
* @param a_pszBasePath The new base path. Does not accept NULL or empty string.
*/
int setServerBasePath(const char *a_pszBasePath) RT_NOEXCEPT;
/**
* Gets the default server URL as specified in the specs.
* @returns Server URL.
*/
virtual const char *getDefaultServerUrl() const RT_NOEXCEPT = 0;
/**
* Gets the default server base path as specified in the specs.
* @returns Host string (start of URL).
*/
virtual const char *getDefaultServerBasePath() const RT_NOEXCEPT = 0;
/** @} */
/**
* Sets the CA file to use for HTTPS.
*/
int setCAFile(const char *pcszCAFile) RT_NOEXCEPT;
/** @overload */
int setCAFile(const RTCString &strCAFile) RT_NOEXCEPT;
/** Flags to doCall. */
enum
{
kDoCall_OciReqSignExcludeBody = 1, /**< Exclude the body when doing OCI request signing. */
kDoCall_RequireBody = 2 /**< The body is required. */
};
protected:
/** Handle to the HTTP connection object. */
RTHTTP m_hHttp;
/** The server URL to use. If empty use the default. */
RTCString m_strServerUrl;
/** The CA file to use. If empty use the default. */
RTCString m_strCAFile;
/* Make non-copyable (RTCNonCopyable causes warnings): */
RTCRestClientApiBase(RTCRestClientApiBase const &);
RTCRestClientApiBase *operator=(RTCRestClientApiBase const &);
/**
* Re-initializes the HTTP instance.
*
* @returns IPRT status code.
*/
virtual int reinitHttpInstance() RT_NOEXCEPT;
/**
* Hook that's called when doCall has fully assembled the request.
*
* Can be used for request signing and similar final steps.
*
* @returns IPRT status code.
* @param a_hHttp The HTTP client instance.
* @param a_rStrFullUrl The full URL.
* @param a_enmHttpMethod The HTTP request method.
* @param a_rStrXmitBody The body text.
* @param a_fFlags kDoCall_XXX.
*/
virtual int xmitReady(RTHTTP a_hHttp, RTCString const &a_rStrFullUrl, RTHTTPMETHOD a_enmHttpMethod,
RTCString const &a_rStrXmitBody, uint32_t a_fFlags) RT_NOEXCEPT;
/**
* Implements stuff for making an API call.
*
* @returns a_pResponse->getStatus()
* @param a_rRequest Reference to the request object.
* @param a_enmHttpMethod The HTTP request method.
* @param a_pResponse Pointer to the response object.
* @param a_pszMethod The method name, for logging purposes.
* @param a_fFlags kDoCall_XXX.
*/
virtual int doCall(RTCRestClientRequestBase const &a_rRequest, RTHTTPMETHOD a_enmHttpMethod,
RTCRestClientResponseBase *a_pResponse, const char *a_pszMethod, uint32_t a_fFlags) RT_NOEXCEPT;
/**
* Implements OCI style request signing.
*
* @returns IPRT status code.
* @param a_hHttp The HTTP client instance.
* @param a_rStrFullUrl The full URL.
* @param a_enmHttpMethod The HTTP request method.
* @param a_rStrXmitBody The body text.
* @param a_fFlags kDoCall_XXX.
* @param a_hKey The key to use for signing.
* @param a_rStrKeyId The key ID.
*
* @remarks The signing scheme is covered by a series of drafts RFC, the latest being:
* https://tools.ietf.org/html/draft-cavage-http-signatures-10
*/
int ociSignRequest(RTHTTP a_hHttp, RTCString const &a_rStrFullUrl, RTHTTPMETHOD a_enmHttpMethod,
RTCString const &a_rStrXmitBody, uint32_t a_fFlags, RTCRKEY a_hKey, RTCString const &a_rStrKeyId) RT_NOEXCEPT;
/**
* Worker for the server URL modifiers.
*
* @returns IPRT status code.
* @param a_pszServerUrl The current server URL (for comparing).
* @param a_offDst The offset of the component in the current server URL.
* @param a_cchDst The current component length.
* @param a_pszSrc The new URL component value.
* @param a_cchSrc The length of the new component.
*/
int setServerUrlPart(const char *a_pszServerUrl, size_t a_offDst, size_t a_cchDst, const char *a_pszSrc, size_t a_cchSrc) RT_NOEXCEPT;
};
/** @} */
#endif /* !IPRT_INCLUDED_cpp_restclient_h */

View file

@ -0,0 +1,280 @@
/** @file
* IPRT - C++ Representational State Transfer (REST) Output Classes.
*/
/*
* Copyright (C) 2008-2023 Oracle and/or its affiliates.
*
* This file is part of VirtualBox base platform packages, as
* available from https://www.virtualbox.org.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, in version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses>.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
* in the VirtualBox distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*
* SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
*/
#ifndef IPRT_INCLUDED_cpp_restoutput_h
#define IPRT_INCLUDED_cpp_restoutput_h
#ifndef RT_WITHOUT_PRAGMA_ONCE
# pragma once
#endif
#include <iprt/cdefs.h>
#include <iprt/types.h>
#include <iprt/stdarg.h>
#include <iprt/cpp/ministring.h>
/** @defgroup grp_rt_cpp_restoutput C++ Representational State Transfer (REST) Output Classes.
* @ingroup grp_rt_cpp
* @{
*/
/**
* Abstract base class for serializing data objects.
*/
class RT_DECL_CLASS RTCRestOutputBase
{
public:
RTCRestOutputBase() RT_NOEXCEPT;
virtual ~RTCRestOutputBase();
/**
* Raw output function.
*
* @returns Number of bytes outputted.
* @param a_pchString The string to output (not necessarily terminated).
* @param a_cchToWrite The length of the string
*/
virtual size_t output(const char *a_pchString, size_t a_cchToWrite) RT_NOEXCEPT = 0;
/**
* RTStrPrintf like function (see @ref pg_rt_str_format).
*
* @returns Number of bytes outputted.
* @param pszFormat The format string.
* @param ... Argument specfied in @a pszFormat.
*/
inline size_t printf(const char *pszFormat, ...) RT_NOEXCEPT RT_IPRT_FORMAT_ATTR(2, 3)
{
va_list va;
va_start(va, pszFormat);
size_t cchWritten = this->vprintf(pszFormat, va);
va_end(va);
return cchWritten;
}
/**
* RTStrPrintfV like function (see @ref pg_rt_str_format).
*
* @returns Number of bytes outputted.
* @param pszFormat The format string.
* @param va Argument specfied in @a pszFormat.
*/
size_t vprintf(const char *pszFormat, va_list va) RT_NOEXCEPT RT_IPRT_FORMAT_ATTR(2, 0);
/**
* Begins an array.
* @returns Previous output state. Pass to endArray() when done.
*/
virtual uint32_t beginArray() RT_NOEXCEPT;
/**
* Ends an array.
* @param a_uOldState Previous output state (returned by beginArray()).
*/
virtual void endArray(uint32_t a_uOldState) RT_NOEXCEPT;
/**
* Begins an object.
* @returns Previous output state. Pass to endObject() when done.
*/
virtual uint32_t beginObject() RT_NOEXCEPT;
/**
* Ends an array.
* @param a_uOldState Previous output state (returned by beginObject()).
*/
virtual void endObject(uint32_t a_uOldState) RT_NOEXCEPT;
/**
* Outputs a value separator.
* This is called before a value, not after.
*/
virtual void valueSeparator() RT_NOEXCEPT;
/**
* Outputs a value separator, name and name separator.
*/
virtual void valueSeparatorAndName(const char *a_pszName, size_t a_cchName) RT_NOEXCEPT;
/** Outputs a null-value. */
void nullValue() RT_NOEXCEPT;
protected:
/** The current indentation level (bits 15:0) and separator state (bit 31). */
uint32_t m_uState;
/** @callback_method_impl{FNRTSTROUTPUT} */
static DECLCALLBACK(size_t) printfOutputCallback(void *pvArg, const char *pachChars, size_t cbChars) RT_NOEXCEPT;
};
/**
* Abstract base class for pretty output.
*/
class RT_DECL_CLASS RTCRestOutputPrettyBase : public RTCRestOutputBase
{
public:
RTCRestOutputPrettyBase() RT_NOEXCEPT;
virtual ~RTCRestOutputPrettyBase();
/**
* Begins an array.
* @returns Previous output state. Pass to endArray() when done.
*/
virtual uint32_t beginArray() RT_NOEXCEPT RT_OVERRIDE;
/**
* Ends an array.
* @param a_uOldState Previous output state (returned by beginArray()).
*/
virtual void endArray(uint32_t a_uOldState) RT_NOEXCEPT RT_OVERRIDE;
/**
* Begins an object.
* @returns Previous output state. Pass to endObject() when done.
*/
virtual uint32_t beginObject() RT_NOEXCEPT RT_OVERRIDE;
/**
* Ends an array.
* @param a_uOldState Previous output state (returned by beginObject()).
*/
virtual void endObject(uint32_t a_uOldState) RT_NOEXCEPT RT_OVERRIDE;
/**
* Outputs a value separator.
* This is called before a value, not after.
*/
virtual void valueSeparator() RT_NOEXCEPT RT_OVERRIDE;
/**
* Outputs a value separator, name and name separator.
*/
virtual void valueSeparatorAndName(const char *a_pszName, size_t a_cchName) RT_NOEXCEPT RT_OVERRIDE;
protected:
/** Helper for outputting the correct amount of indentation. */
void outputIndentation() RT_NOEXCEPT;
};
/**
* Serialize to a string object.
*/
class RT_DECL_CLASS RTCRestOutputToString : public RTCRestOutputBase
{
public:
/**
* Creates an instance that appends to @a a_pDst.
* @param a_pDst Pointer to the destination string object.
* NULL is not accepted and will assert.
* @param a_fAppend Whether to append to the current string value, or
* nuke the string content before starting the output.
*/
RTCRestOutputToString(RTCString *a_pDst, bool a_fAppend = false) RT_NOEXCEPT;
virtual ~RTCRestOutputToString();
virtual size_t output(const char *a_pchString, size_t a_cchToWrite) RT_NOEXCEPT RT_OVERRIDE;
/**
* Finalizes the output and releases the string object to the caller.
*
* @returns The released string object. NULL if we ran out of memory or if
* called already.
*
* @remark This sets m_pDst to NULL and the object cannot be use for any
* more output afterwards.
*/
virtual RTCString *finalize() RT_NOEXCEPT;
protected:
/** Pointer to the destination string. NULL after finalize(). */
RTCString *m_pDst;
/** Set if we ran out of memory and should ignore subsequent calls. */
bool m_fOutOfMemory;
/* Make non-copyable (RTCNonCopyable causes warnings): */
RTCRestOutputToString(RTCRestOutputToString const &);
RTCRestOutputToString *operator=(RTCRestOutputToString const &);
};
/**
* Serialize pretty JSON to a string object.
*/
class RT_DECL_CLASS RTCRestOutputPrettyToString : public RTCRestOutputPrettyBase
{
public:
/**
* Creates an instance that appends to @a a_pDst.
* @param a_pDst Pointer to the destination string object.
* NULL is not accepted and will assert.
* @param a_fAppend Whether to append to the current string value, or
* nuke the string content before starting the output.
*/
RTCRestOutputPrettyToString(RTCString *a_pDst, bool a_fAppend = false) RT_NOEXCEPT;
virtual ~RTCRestOutputPrettyToString();
virtual size_t output(const char *a_pchString, size_t a_cchToWrite) RT_NOEXCEPT RT_OVERRIDE;
/**
* Finalizes the output and releases the string object to the caller.
*
* @returns The released string object. NULL if we ran out of memory or if
* called already.
*
* @remark This sets m_pDst to NULL and the object cannot be use for any
* more output afterwards.
*/
virtual RTCString *finalize() RT_NOEXCEPT;
protected:
/** Pointer to the destination string. NULL after finalize(). */
RTCString *m_pDst;
/** Set if we ran out of memory and should ignore subsequent calls. */
bool m_fOutOfMemory;
/* Make non-copyable (RTCNonCopyable causes warnings): */
RTCRestOutputPrettyToString(RTCRestOutputToString const &);
RTCRestOutputPrettyToString *operator=(RTCRestOutputToString const &);
};
/** @} */
#endif /* !IPRT_INCLUDED_cpp_restoutput_h */

View file

@ -0,0 +1,499 @@
/** @file
* IPRT - C++ Representational State Transfer (REST) String Map Template.
*/
/*
* Copyright (C) 2008-2023 Oracle and/or its affiliates.
*
* This file is part of VirtualBox base platform packages, as
* available from https://www.virtualbox.org.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, in version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses>.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
* in the VirtualBox distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*
* SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
*/
#ifndef IPRT_INCLUDED_cpp_reststringmap_h
#define IPRT_INCLUDED_cpp_reststringmap_h
#ifndef RT_WITHOUT_PRAGMA_ONCE
# pragma once
#endif
#include <iprt/list.h>
#include <iprt/string.h>
#include <iprt/cpp/restbase.h>
/** @defgroup grp_rt_cpp_reststingmap C++ Representational State Transfer (REST) String Map Template
* @ingroup grp_rt_cpp
* @{
*/
/**
* Abstract base class for the RTCRestStringMap template.
*/
class RT_DECL_CLASS RTCRestStringMapBase : public RTCRestObjectBase
{
public:
/** Default destructor. */
RTCRestStringMapBase() RT_NOEXCEPT;
/** Copy constructor. */
RTCRestStringMapBase(RTCRestStringMapBase const &a_rThat);
/** Destructor. */
virtual ~RTCRestStringMapBase();
/** Copy assignment operator. */
RTCRestStringMapBase &operator=(RTCRestStringMapBase const &a_rThat);
/* Overridden methods: */
virtual RTCRestObjectBase *baseClone() const RT_NOEXCEPT RT_OVERRIDE;
virtual int resetToDefault() RT_NOEXCEPT RT_OVERRIDE;
virtual RTCRestOutputBase &serializeAsJson(RTCRestOutputBase &a_rDst) const RT_NOEXCEPT RT_OVERRIDE;
virtual int deserializeFromJson(RTCRestJsonCursor const &a_rCursor) RT_NOEXCEPT RT_OVERRIDE;
// later?
//virtual int toString(RTCString *a_pDst, uint32_t a_fFlags = kCollectionFormat_Unspecified) const RT_NOEXCEPT RT_OVERRIDE;
//virtual int fromString(RTCString const &a_rValue, const char *a_pszName, PRTERRINFO a_pErrInfo = NULL,
// uint32_t a_fFlags = kCollectionFormat_Unspecified) RT_NOEXCEPT RT_OVERRIDE;
virtual kTypeClass typeClass(void) const RT_NOEXCEPT RT_OVERRIDE;
virtual const char *typeName(void) const RT_NOEXCEPT RT_OVERRIDE;
/**
* Clear the content of the map.
*/
void clear() RT_NOEXCEPT;
/**
* Checks if the map is empty.
*/
inline bool isEmpty() const RT_NOEXCEPT { return m_cEntries == 0; }
/**
* Gets the number of entries in the map.
*/
size_t size() const RT_NOEXCEPT;
/**
* Checks if the map contains the given key.
* @returns true if key found, false if not.
* @param a_pszKey The key to check fo.
*/
bool containsKey(const char *a_pszKey) const RT_NOEXCEPT;
/**
* Checks if the map contains the given key.
* @returns true if key found, false if not.
* @param a_rStrKey The key to check fo.
*/
bool containsKey(RTCString const &a_rStrKey) const RT_NOEXCEPT;
/**
* Remove any key-value pair with the given key.
* @returns true if anything was removed, false if not found.
* @param a_pszKey The key to remove.
*/
bool remove(const char *a_pszKey) RT_NOEXCEPT;
/**
* Remove any key-value pair with the given key.
* @returns true if anything was removed, false if not found.
* @param a_rStrKey The key to remove.
*/
bool remove(RTCString const &a_rStrKey) RT_NOEXCEPT;
/**
* Creates a new value and inserts it under the given key, returning the new value.
*
* @returns VINF_SUCCESS or VWRN_ALREADY_EXISTS on success.
* VERR_ALREADY_EXISTS, VERR_NO_MEMORY or VERR_NO_STR_MEMORY on failure.
* @param a_ppValue Where to return the pointer to the value.
* @param a_pszKey The key to put it under.
* @param a_cchKey The length of the key. Default is the entire string.
* @param a_fReplace Whether to replace or fail on key collision.
*/
int putNewValue(RTCRestObjectBase **a_ppValue, const char *a_pszKey, size_t a_cchKey = RTSTR_MAX, bool a_fReplace = false) RT_NOEXCEPT;
/**
* Creates a new value and inserts it under the given key, returning the new value.
*
* @returns VINF_SUCCESS or VWRN_ALREADY_EXISTS on success.
* VERR_ALREADY_EXISTS, VERR_NO_MEMORY or VERR_NO_STR_MEMORY on failure.
* @param a_ppValue Where to return the pointer to the value.
* @param a_rStrKey The key to put it under.
* @param a_fReplace Whether to replace or fail on key collision.
*/
int putNewValue(RTCRestObjectBase **a_ppValue, RTCString const &a_rStrKey, bool a_fReplace = false) RT_NOEXCEPT;
protected:
/** Map entry. */
typedef struct MapEntry
{
/** String space core. */
RTSTRSPACECORE Core;
/** List node for enumeration. */
RTLISTNODE ListEntry;
/** The key.
* @remarks Core.pszString points to the value of this object. So, consider it const. */
RTCString strKey;
/** The value. */
RTCRestObjectBase *pValue;
} MapEntry;
/** The map tree. */
RTSTRSPACE m_Map;
/** The enumeration list head (MapEntry). */
RTLISTANCHOR m_ListHead;
/** Number of map entries. */
size_t m_cEntries;
public:
/** @name Map Iteration
* @{ */
/** Const iterator. */
class ConstIterator
{
private:
MapEntry *m_pCur;
ConstIterator() RT_NOEXCEPT;
protected:
ConstIterator(MapEntry *a_pEntry) RT_NOEXCEPT : m_pCur(a_pEntry) { }
public:
ConstIterator(ConstIterator const &a_rThat) RT_NOEXCEPT : m_pCur(a_rThat.m_pCur) { }
/** Gets the key string. */
inline RTCString const &getKey() RT_NOEXCEPT { return m_pCur->strKey; }
/** Gets poitner to the value object. */
inline RTCRestObjectBase const *getValue() RT_NOEXCEPT { return m_pCur->pValue; }
/** Advance to the next map entry. */
inline ConstIterator &operator++() RT_NOEXCEPT
{
m_pCur = RTListNodeGetNextCpp(&m_pCur->ListEntry, MapEntry, ListEntry);
return *this;
}
/** Advance to the previous map entry. */
inline ConstIterator &operator--() RT_NOEXCEPT
{
m_pCur = RTListNodeGetPrevCpp(&m_pCur->ListEntry, MapEntry, ListEntry);
return *this;
}
/** Compare equal. */
inline bool operator==(ConstIterator const &a_rThat) RT_NOEXCEPT { return m_pCur == a_rThat.m_pCur; }
/** Compare not equal. */
inline bool operator!=(ConstIterator const &a_rThat) RT_NOEXCEPT { return m_pCur != a_rThat.m_pCur; }
/* Map class must be friend so it can use the MapEntry constructor. */
friend class RTCRestStringMapBase;
};
/** Returns iterator for the first map entry (unless it's empty and it's also the end). */
inline ConstIterator begin() const RT_NOEXCEPT
{
if (!RTListIsEmpty(&m_ListHead))
return ConstIterator(RTListNodeGetNextCpp(&m_ListHead, MapEntry, ListEntry));
return end();
}
/** Returns iterator for the last map entry (unless it's empty and it's also the end). */
inline ConstIterator last() const RT_NOEXCEPT
{
if (!RTListIsEmpty(&m_ListHead))
return ConstIterator(RTListNodeGetPrevCpp(&m_ListHead, MapEntry, ListEntry));
return end();
}
/** Returns the end iterator. This does not ever refer to an actual map entry. */
inline ConstIterator end() const RT_NOEXCEPT
{
return ConstIterator(RT_FROM_CPP_MEMBER(&m_ListHead, MapEntry, ListEntry));
}
/** @} */
protected:
/**
* Helper for creating a clone.
*
* @returns Pointer to new map object on success, NULL if out of memory.
*/
virtual RTCRestStringMapBase *createClone(void) const RT_NOEXCEPT = 0;
/**
* Wrapper around the value constructor.
*
* @returns Pointer to new value object on success, NULL if out of memory.
*/
virtual RTCRestObjectBase *createValue(void) RT_NOEXCEPT = 0;
/**
* For accessing the static deserializeInstanceFromJson() method of the value.
*/
virtual int deserializeValueInstanceFromJson(RTCRestJsonCursor const &a_rCursor, RTCRestObjectBase **a_ppInstance) RT_NOEXCEPT = 0;
/**
* Worker for the copy assignment method and copyMapWorkerMayThrow.
*
* This will use createEntryCopy to do the copying.
*
* @returns VINF_SUCCESS on success, VERR_NO_MEMORY or VERR_NO_STR_MEMORY on failure.
* @param a_rThat The map to copy. Caller makes 100% sure the it has
* the same type as the destination.
*/
int copyMapWorkerNoThrow(RTCRestStringMapBase const &a_rThat) RT_NOEXCEPT;
/**
* Wrapper around copyMapWorkerNoThrow() that throws allocation errors, making
* it suitable for copy constructors and assignment operators.
*/
void copyMapWorkerMayThrow(RTCRestStringMapBase const &a_rThat);
/**
* Worker for performing inserts.
*
* @returns VINF_SUCCESS or VWRN_ALREADY_EXISTS on success.
* VERR_ALREADY_EXISTS, VERR_NO_MEMORY or VERR_NO_STR_MEMORY on failure.
* @param a_pszKey The key.
* @param a_pValue The value to insert. Ownership is transferred to the map on success.
* @param a_fReplace Whether to replace existing key-value pair with matching key.
* @param a_cchKey The key length, the whole string by default.
*/
int putWorker(const char *a_pszKey, RTCRestObjectBase *a_pValue, bool a_fReplace, size_t a_cchKey = RTSTR_MAX) RT_NOEXCEPT;
/**
* Worker for performing inserts.
*
* @returns VINF_SUCCESS or VWRN_ALREADY_EXISTS on success.
* VERR_ALREADY_EXISTS, VERR_NO_MEMORY or VERR_NO_STR_MEMORY on failure.
* @param a_pszKey The key.
* @param a_rValue The value to copy into the map.
* @param a_fReplace Whether to replace existing key-value pair with matching key.
* @param a_cchKey The key length, the whole string by default.
*/
int putCopyWorker(const char *a_pszKey, RTCRestObjectBase const &a_rValue, bool a_fReplace, size_t a_cchKey = RTSTR_MAX) RT_NOEXCEPT;
/**
* Worker for getting the value corresponding to the given key.
*
* @returns Pointer to the value object if found, NULL if key not in the map.
* @param a_pszKey The key which value to look up.
*/
RTCRestObjectBase *getWorker(const char *a_pszKey) RT_NOEXCEPT;
/**
* Worker for getting the value corresponding to the given key, const variant.
*
* @returns Pointer to the value object if found, NULL if key not in the map.
* @param a_pszKey The key which value to look up.
*/
RTCRestObjectBase const *getWorker(const char *a_pszKey) const RT_NOEXCEPT;
private:
static DECLCALLBACK(int) stringSpaceDestructorCallback(PRTSTRSPACECORE pStr, void *pvUser) RT_NOEXCEPT;
};
/**
* Limited map class.
*/
template<class ValueType> class RTCRestStringMap : public RTCRestStringMapBase
{
public:
/** Default constructor, creates emtpy map. */
RTCRestStringMap() RT_NOEXCEPT
: RTCRestStringMapBase()
{}
/** Copy constructor. */
RTCRestStringMap(RTCRestStringMap const &a_rThat)
: RTCRestStringMapBase()
{
copyMapWorkerMayThrow(a_rThat);
}
/** Destructor. */
virtual ~RTCRestStringMap()
{
/* nothing to do here. */
}
/** Copy assignment operator. */
RTCRestStringMap &operator=(RTCRestStringMap const &a_rThat)
{
copyMapWorkerMayThrow(a_rThat);
return *this;
}
/** Safe copy assignment method. */
int assignCopy(RTCRestStringMap const &a_rThat) RT_NOEXCEPT
{
return copyMapWorkerNoThrow(a_rThat);
}
/** Make a clone of this object. */
inline RTCRestStringMap *clone() const RT_NOEXCEPT
{
return (RTCRestStringMap *)baseClone();
}
/** Factory method. */
static DECLCALLBACK(RTCRestObjectBase *) createInstance(void) RT_NOEXCEPT
{
return new (std::nothrow) RTCRestStringMap<ValueType>();
}
/** Factory method for values. */
static DECLCALLBACK(RTCRestObjectBase *) createValueInstance(void) RT_NOEXCEPT
{
return new (std::nothrow) ValueType();
}
/** @copydoc RTCRestObjectBase::FNDESERIALIZEINSTANCEFROMJSON */
static DECLCALLBACK(int) deserializeInstanceFromJson(RTCRestJsonCursor const &a_rCursor, RTCRestObjectBase **a_ppInstance) RT_NOEXCEPT
{
*a_ppInstance = new (std::nothrow) RTCRestStringMap<ValueType>();
if (*a_ppInstance)
return (*a_ppInstance)->deserializeFromJson(a_rCursor);
return a_rCursor.m_pPrimary->addError(a_rCursor, VERR_NO_MEMORY, "Out of memory");
}
/**
* Inserts the given object into the map.
*
* @returns VINF_SUCCESS or VWRN_ALREADY_EXISTS on success.
* VERR_ALREADY_EXISTS, VERR_NO_MEMORY or VERR_NO_STR_MEMORY on failure.
* @param a_pszKey The key.
* @param a_pValue The value to insert. Ownership is transferred to the map on success.
* @param a_fReplace Whether to replace existing key-value pair with matching key.
*/
inline int put(const char *a_pszKey, ValueType *a_pValue, bool a_fReplace = false) RT_NOEXCEPT
{
return putWorker(a_pszKey, a_pValue, a_fReplace);
}
/**
* Inserts the given object into the map.
*
* @returns VINF_SUCCESS or VWRN_ALREADY_EXISTS on success.
* VERR_ALREADY_EXISTS, VERR_NO_MEMORY or VERR_NO_STR_MEMORY on failure.
* @param a_rStrKey The key.
* @param a_pValue The value to insert. Ownership is transferred to the map on success.
* @param a_fReplace Whether to replace existing key-value pair with matching key.
*/
inline int put(RTCString const &a_rStrKey, ValueType *a_pValue, bool a_fReplace = false) RT_NOEXCEPT
{
return putWorker(a_rStrKey.c_str(), a_pValue, a_fReplace, a_rStrKey.length());
}
/**
* Inserts a copy of the given object into the map.
*
* @returns VINF_SUCCESS or VWRN_ALREADY_EXISTS on success.
* VERR_ALREADY_EXISTS, VERR_NO_MEMORY or VERR_NO_STR_MEMORY on failure.
* @param a_pszKey The key.
* @param a_rValue The value to insert a copy of.
* @param a_fReplace Whether to replace existing key-value pair with matching key.
*/
inline int putCopy(const char *a_pszKey, const ValueType &a_rValue, bool a_fReplace = false) RT_NOEXCEPT
{
return putCopyWorker(a_pszKey, a_rValue, a_fReplace);
}
/**
* Inserts a copy of the given object into the map.
*
* @returns VINF_SUCCESS or VWRN_ALREADY_EXISTS on success.
* VERR_ALREADY_EXISTS, VERR_NO_MEMORY or VERR_NO_STR_MEMORY on failure.
* @param a_rStrKey The key.
* @param a_rValue The value to insert a copy of.
* @param a_fReplace Whether to replace existing key-value pair with matching key.
*/
inline int putCopy(RTCString const &a_rStrKey, const ValueType &a_rValue, bool a_fReplace = false) RT_NOEXCEPT
{
return putCopyWorker(a_rStrKey.c_str(), a_rValue, a_fReplace, a_rStrKey.length());
}
/**
* Gets the value corresponding to the given key.
*
* @returns Pointer to the value object if found, NULL if key not in the map.
* @param a_pszKey The key which value to look up.
*/
inline ValueType *get(const char *a_pszKey) RT_NOEXCEPT
{
return (ValueType *)getWorker(a_pszKey);
}
/**
* Gets the value corresponding to the given key.
*
* @returns Pointer to the value object if found, NULL if key not in the map.
* @param a_rStrKey The key which value to look up.
*/
inline ValueType *get(RTCString const &a_rStrKey) RT_NOEXCEPT
{
return (ValueType *)getWorker(a_rStrKey.c_str());
}
/**
* Gets the const value corresponding to the given key.
*
* @returns Pointer to the value object if found, NULL if key not in the map.
* @param a_pszKey The key which value to look up.
*/
inline ValueType const *get(const char *a_pszKey) const RT_NOEXCEPT
{
return (ValueType const *)getWorker(a_pszKey);
}
/**
* Gets the const value corresponding to the given key.
*
* @returns Pointer to the value object if found, NULL if key not in the map.
* @param a_rStrKey The key which value to look up.
*/
inline ValueType const *get(RTCString const &a_rStrKey) const RT_NOEXCEPT
{
return (ValueType const *)getWorker(a_rStrKey.c_str());
}
/** @todo enumerator*/
protected:
virtual RTCRestStringMapBase *createClone(void) const RT_NOEXCEPT RT_OVERRIDE
{
return new (std::nothrow) RTCRestStringMap();
}
virtual RTCRestObjectBase *createValue(void) RT_NOEXCEPT RT_OVERRIDE
{
return new (std::nothrow) ValueType();
}
virtual int deserializeValueInstanceFromJson(RTCRestJsonCursor const &a_rCursor, RTCRestObjectBase **a_ppInstance) RT_NOEXCEPT RT_OVERRIDE
{
return ValueType::deserializeInstanceFromJson(a_rCursor, a_ppInstance);
}
};
/** @} */
#endif /* !IPRT_INCLUDED_cpp_reststringmap_h */

149
include/iprt/cpp/utils.h Normal file
View file

@ -0,0 +1,149 @@
/** @file
* IPRT - C++ Utilities (useful templates, defines and such).
*/
/*
* Copyright (C) 2006-2023 Oracle and/or its affiliates.
*
* This file is part of VirtualBox base platform packages, as
* available from https://www.virtualbox.org.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, in version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses>.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
* in the VirtualBox distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*
* SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
*/
#ifndef IPRT_INCLUDED_cpp_utils_h
#define IPRT_INCLUDED_cpp_utils_h
#ifndef RT_WITHOUT_PRAGMA_ONCE
# pragma once
#endif
#include <iprt/types.h>
/** @defgroup grp_rt_cpp IPRT C++ APIs */
/** @defgroup grp_rt_cpp_util C++ Utilities
* @ingroup grp_rt_cpp
* @{
*/
#define DPTR(CLASS) CLASS##Private *d = static_cast<CLASS##Private *>(d_ptr)
#define QPTR(CLASS) CLASS *q = static_cast<CLASS *>(q_ptr)
/**
* A simple class used to prevent copying and assignment.
*
* Inherit from this class in order to prevent automatic generation
* of the copy constructor and assignment operator in your class.
*/
class RTCNonCopyable
{
protected:
RTCNonCopyable() {}
~RTCNonCopyable() {}
private:
RTCNonCopyable(RTCNonCopyable const &);
RTCNonCopyable &operator=(RTCNonCopyable const &);
};
/**
* Shortcut to |const_cast<C &>()| that automatically derives the correct
* type (class) for the const_cast template's argument from its own argument.
*
* Can be used to temporarily cancel the |const| modifier on the left-hand side
* of assignment expressions, like this:
* @code
* const Class That;
* ...
* unconst(That) = SomeValue;
* @endcode
*
* @todo What to do about the prefix here?
*/
template <class C>
inline C &unconst(const C &that)
{
return const_cast<C &>(that);
}
/**
* Shortcut to |const_cast<C *>()| that automatically derives the correct
* type (class) for the const_cast template's argument from its own argument.
*
* Can be used to temporarily cancel the |const| modifier on the left-hand side
* of assignment expressions, like this:
* @code
* const Class *pThat;
* ...
* unconst(pThat) = SomeValue;
* @endcode
*
* @todo What to do about the prefix here?
*/
template <class C>
inline C *unconst(const C *that)
{
return const_cast<C *>(that);
}
/**
* Macro for generating a non-const getter version from a const getter.
*
* @param a_RetType The getter return type.
* @param a_Class The class name.
* @param a_Getter The getter name.
* @param a_ArgDecls The argument declaration for the getter method.
* @param a_ArgList The argument list for the call.
*/
#define RT_CPP_GETTER_UNCONST(a_RetType, a_Class, a_Getter, a_ArgDecls, a_ArgList) \
a_RetType a_Getter a_ArgDecls \
{ \
return static_cast< a_Class const *>(this)-> a_Getter a_ArgList; \
}
/**
* Macro for generating a non-const getter version from a const getter,
* unconsting the return value as well.
*
* @param a_RetType The getter return type.
* @param a_Class The class name.
* @param a_Getter The getter name.
* @param a_ArgDecls The argument declaration for the getter method.
* @param a_ArgList The argument list for the call.
*/
#define RT_CPP_GETTER_UNCONST_RET(a_RetType, a_Class, a_Getter, a_ArgDecls, a_ArgList) \
a_RetType a_Getter a_ArgDecls \
{ \
return const_cast<a_RetType>(static_cast< a_Class const *>(this)-> a_Getter a_ArgList); \
}
/** @} */
#endif /* !IPRT_INCLUDED_cpp_utils_h */

1252
include/iprt/cpp/xml.h Normal file

File diff suppressed because it is too large Load diff