| 21 | } |
| 22 | |
| 23 | template<typename TChar> class String { |
| 24 | private: |
| 25 | static const TChar NullChar = 0; |
| 26 | |
| 27 | // Small string optimization (using stack memory for small strings): |
| 28 | static constexpr unsigned char SSO_SIZE = 32; |
| 29 | __declspec(align(MEMORY_ALLOCATION_ALIGNMENT)) TChar SsoBuffer[SSO_SIZE]; |
| 30 | |
| 31 | static constexpr unsigned short AllocationGranularity = 64; |
| 32 | |
| 33 | using STRING_INFO = struct { |
| 34 | TChar* Buffer; |
| 35 | size_t Length; // Symbols count without null-terminator |
| 36 | size_t BufferSize; // Buffer size in bytes |
| 37 | BOOLEAN SsoUsing; |
| 38 | }; |
| 39 | |
| 40 | STRING_INFO Data; |
| 41 | |
| 42 | static inline VOID SetupSso(OUT STRING_INFO* StringInfo, const TChar* SsoBuffer) { |
| 43 | StringInfo->Buffer = const_cast<TChar*>(SsoBuffer); |
| 44 | StringInfo->Length = 0; |
| 45 | StringInfo->BufferSize = SSO_SIZE * sizeof(TChar); |
| 46 | StringInfo->SsoUsing = TRUE; |
| 47 | StringInfo->Buffer[0] = NullChar; |
| 48 | StringInfo->Buffer[SSO_SIZE - 1] = NullChar; |
| 49 | } |
| 50 | |
| 51 | static inline TChar* StrAllocMem(size_t Bytes) { |
| 52 | #ifdef _NTDDK_ |
| 53 | #ifdef POOL_NX_OPTIN |
| 54 | return static_cast<TChar*>(ExAllocatePoolWithTag(ExDefaultNonPagedPoolType, Bytes, StrPoolTag)); |
| 55 | #else |
| 56 | return static_cast<TChar*>(ExAllocatePoolWithTag(NonPagedPool, Bytes, StrPoolTag)); |
| 57 | #endif |
| 58 | #else |
| 59 | return reinterpret_cast<TChar*>(new BYTE[Bytes]); |
| 60 | #endif |
| 61 | } |
| 62 | |
| 63 | static inline VOID StrFreeMem(TChar* Memory) { |
| 64 | #ifdef _NTDDK_ |
| 65 | ExFreePoolWithTag(Memory, StrPoolTag); |
| 66 | #else |
| 67 | delete[] Memory; |
| 68 | #endif |
| 69 | } |
| 70 | |
| 71 | static bool Alloc(OUT STRING_INFO* StringInfo, size_t Characters) { |
| 72 | if (!StringInfo || !Characters) return false; |
| 73 | *StringInfo = {}; |
| 74 | size_t Size = (Characters + 1) * sizeof(TChar); // Null-terminated buffer |
| 75 | Size = ((Size / AllocationGranularity) + 1) * AllocationGranularity; |
| 76 | TChar* Buffer = StrAllocMem(Size); |
| 77 | if (!Buffer) return false; |
| 78 | Buffer[0] = NullChar; |
| 79 | Buffer[Characters] = NullChar; |
| 80 | StringInfo->Buffer = Buffer; |
no test coverage detected