From 6bf0a5cb5034a7e684dcc3500e841785237ce2dd Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 7 Apr 2024 19:32:43 +0200 Subject: Adding upstream version 1:115.7.0. Signed-off-by: Daniel Baumann --- xpcom/ds/ArenaAllocatorExtensions.h | 76 +++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 xpcom/ds/ArenaAllocatorExtensions.h (limited to 'xpcom/ds/ArenaAllocatorExtensions.h') diff --git a/xpcom/ds/ArenaAllocatorExtensions.h b/xpcom/ds/ArenaAllocatorExtensions.h new file mode 100644 index 0000000000..60819381d5 --- /dev/null +++ b/xpcom/ds/ArenaAllocatorExtensions.h @@ -0,0 +1,76 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef mozilla_ArenaAllocatorExtensions_h +#define mozilla_ArenaAllocatorExtensions_h + +#include "mozilla/ArenaAllocator.h" +#include "mozilla/CheckedInt.h" +#include "nsAString.h" + +/** + * Extensions to the ArenaAllocator class. + */ +namespace mozilla { + +namespace detail { + +template +T* DuplicateString(const T* aSrc, const CheckedInt& aLen, + ArenaAllocator& aArena); + +} // namespace detail + +/** + * Makes an arena allocated null-terminated copy of the source string. The + * source string must be null-terminated. + * + * @param aSrc String to copy. + * @param aArena The arena to allocate the string copy out of. + * @return An arena allocated null-terminated string. + */ +template +T* ArenaStrdup(const T* aStr, ArenaAllocator& aArena) { + return detail::DuplicateString(aStr, nsCharTraits::length(aStr), aArena); +} + +/** + * Makes an arena allocated null-terminated copy of the source string. + * + * @param aSrc String to copy. + * @param aArena The arena to allocate the string copy out of. + * @return An arena allocated null-terminated string. + */ +template +T* ArenaStrdup(const detail::nsTStringRepr& aStr, + ArenaAllocator& aArena) { + return detail::DuplicateString(aStr.BeginReading(), aStr.Length(), aArena); +} + +/** + * Copies the source string and adds a null terminator. Source string does not + * have to be null terminated. + */ +template +T* detail::DuplicateString(const T* aSrc, const CheckedInt& aLen, + ArenaAllocator& aArena) { + const auto byteLen = (aLen + 1) * sizeof(T); + if (!byteLen.isValid()) { + return nullptr; + } + + T* p = static_cast(aArena.Allocate(byteLen.value(), mozilla::fallible)); + if (p) { + memcpy(p, aSrc, byteLen.value() - sizeof(T)); + p[aLen.value()] = T(0); + } + + return p; +} + +} // namespace mozilla + +#endif // mozilla_ArenaAllocatorExtensions_h -- cgit v1.2.3