OXYGENHUB
◆ main openmsx / src / utils / StringStorage.hh
1.0 KiB · C++ · last changed chore(): initial commit 1 month ago source blame history raw
e8555c89 Andy McCall 1
#ifndef STRINGSTORAGE_HH
2
#define STRINGSTORAGE_HH
3
4
#include <algorithm>
5
#include <cstdlib>
6
#include <memory>
7
#include <string_view>
8
9
/** StringStorage:
10
 * Acts like a 'const char*', but in addition calls free() when the pointer
11
 * goes out of scope.
12
 */
13
struct FreeStringStorage
14
{
15
	void operator()(char* p) const { free(p); }
16
};
17
using StringStorage = std::unique_ptr<char, FreeStringStorage>;
18
19
20
/** Allocate a 'StringStorage' large enough for 'size' characters.
21
  */
22
inline StringStorage allocate_string_storage(size_t size)
23
{
24
	return StringStorage(static_cast<char*>(malloc(size)));
25
}
26
27
/** Allocate memory for and copy a c-string (zero-terminated string).
28
  * This function is similar to strdup(), except that this function:
29
  * - takes a 'string_view' instead of a 'const char*' parameter.
30
  * - returns a 'StringStorage' instead of 'char*'.
31
  */
32
inline StringStorage allocate_c_string(std::string_view s)
33
{
34
	auto result = allocate_string_storage(s.size() + 1);
35
	char* p = result.get();
36
	char* z = std::ranges::copy(s, p).out;
37
	*z = '\0';
38
	return result;
39
}
40
41
#endif