| 1 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 |
|
| 5 |
#ifndef intl_components_FormatBuffer_h |
| 6 |
#define intl_components_FormatBuffer_h |
| 7 |
|
| 8 |
/** |
| 9 |
* This file contains public adaptors for the mozilla::intl Buffer template |
| 10 |
* argument. Adaptors that can automatically be deduced are kept as private |
| 11 |
* in ICU4CGlue.h. There is also the SpiderMonkey specific adaptor |
| 12 |
* js::intl::FormatBuffer in js/src/builtin/intl/FormatBuffer.h. |
| 13 |
*/ |
| 14 |
|
| 15 |
#include "nsTString.h" |
| 16 |
|
| 17 |
namespace mozilla::intl { |
| 18 |
|
| 19 |
/** |
| 20 |
* mozilla::intl APIs require sizeable buffers. This class abstracts over |
| 21 |
* the nsTSubstring. |
| 22 |
*/ |
| 23 |
template <typename T> |
| 24 |
class nsTStringToBufferAdapter { |
| 25 |
public: |
| 26 |
using CharType = T; |
| 27 |
|
| 28 |
// Do not allow copy or move. Move could be added in the future if needed. |
| 29 |
nsTStringToBufferAdapter(const nsTStringToBufferAdapter&) = delete; |
| 30 |
nsTStringToBufferAdapter& operator=(const nsTStringToBufferAdapter&) = delete; |
| 31 |
|
| 32 |
explicit nsTStringToBufferAdapter(nsTSubstring<CharType>& aString) |
| 33 |
: mString(aString) {} |
| 34 |
|
| 35 |
/** |
| 36 |
* Ensures the buffer has enough space to accommodate |size| elements. |
| 37 |
*/ |
| 38 |
[[nodiscard]] bool reserve(size_t size) { |
| 39 |
return mString.SetLength(size, fallible); |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* Returns the raw data inside the buffer. |
| 44 |
*/ |
| 45 |
CharType* data() { return mString.BeginWriting(); } |
| 46 |
|
| 47 |
/** |
| 48 |
* Returns the count of elements written into the buffer. |
| 49 |
*/ |
| 50 |
size_t length() const { return mString.Length(); } |
| 51 |
|
| 52 |
/** |
| 53 |
* Returns the buffer's overall capacity. |
| 54 |
*/ |
| 55 |
size_t capacity() const { |
| 56 |
// nsString's Capacity() method is protected, so just return the length. |
| 57 |
return mString.Length(); |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* Resizes the buffer to the given amount of written elements. |
| 62 |
*/ |
| 63 |
void written(size_t amount) { |
| 64 |
MOZ_ASSERT(amount <= mString.Length()); |
| 65 |
// This sets |mString|'s internal size so that it matches how much was |
| 66 |
// written. This is necessary because the write happens across FFI |
| 67 |
// boundaries. |
| 68 |
mString.SetLength(amount); |
| 69 |
} |
| 70 |
|
| 71 |
private: |
| 72 |
nsTSubstring<CharType>& mString; |
| 73 |
}; |
| 74 |
|
| 75 |
} // namespace mozilla::intl |
| 76 |
|
| 77 |
#endif /* intl_components_FormatBuffer_h */ |