OXYGENHUB
◆ main openmsx / src / utils / String32.hh
1.5 KiB · C++ · last changed chore(): initial commit 1 month ago source blame history raw
e8555c89 Andy McCall 1
#ifndef STRING32_HH
2
#define STRING32_HH
3
4
#include "narrow.hh"
5
#include <cassert>
6
#include <cstdint>
7
#include <type_traits>
8
9
// Given a buffer of max size 4GB, 32 bits are enough to address each position
10
// in that buffer.
11
// - On 32-bit systems we can use a pointer to a location in the buffer.
12
// - On 64-bit systems a pointer is too large (64 bit), but an index in the
13
//   buffer works fine. (An index works fine on 32-bit systems as well, but is
14
//   slightly less efficient).
15
// The String32 helper abstracts the difference between the two above
16
// approaches. In both cases it is a 32-bit type (hence the name). And on
17
// both 32/64-bit systems it uses the more efficient implementation.
18
19
using String32 = std::conditional_t<
20
	(sizeof(char*) > sizeof(uint32_t)), // is a pointer bigger than an uint32_t
21
	uint32_t,                           // yes -> use uint32_t
22
	const char*>;                       // no  -> directly use pointer
23
24
// convert string in buffer to String32
25
constexpr void toString32(const char* buffer, const char* str, uint32_t& result) {
26
	assert(buffer <= str);
27
	result = narrow<uint32_t>(str - buffer);
28
}
29
constexpr void toString32(const char* /*buffer*/, const char* str, const char*& result) {
30
	result = str;
31
}
32
33
// convert String32 back to string in buffer
34
[[nodiscard]] constexpr const char* fromString32(const char* buffer, uint32_t str32) {
35
	return buffer + str32;
36
}
37
[[nodiscard]] constexpr const char* fromString32(const char* /*buffer*/, const char* str32) {
38
	return str32;
39
}
40
41
#endif