Debian Codegraph @

common/mptStringBuffer.cpp

raw
1 /*
2 * mptStringBuffer.cpp
3 * -------------------
4 * Purpose: Various functions for "fixing" char array strings for writing to or
5 * reading from module files, or for securing char arrays in general.
6 * Notes : (currently none)
7 * Authors: OpenMPT Devs
8 * The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
9 */
10
11
12 #include "stdafx.h"
13
14 #include "mptStringBuffer.h"
15
16
17 OPENMPT_NAMESPACE_BEGIN
18
19
20
21 namespace mpt
22 {
23
24 namespace String
25 {
26
27 namespace detail
28 {
29
30 std::string ReadStringBuffer(String::ReadWriteMode mode, const char *srcBuffer, std::size_t srcSize)
31 {
32
33 std::string dest;
34 const char *src = srcBuffer;
35
36 if(mode == nullTerminated || mode == spacePaddedNull)
37 {
38 // We assume that the last character of the source buffer is null.
39 if(srcSize > 0)
40 {
41 srcSize -= 1;
42 }
43 }
44
45 if(mode == nullTerminated || mode == maybeNullTerminated)
46 {
47
48 // Copy null-terminated string, stopping at null.
49 dest.assign(src, std::find(src, src + srcSize, '\0'));
50
51 } else if(mode == spacePadded || mode == spacePaddedNull)
52 {
53
54 // Copy string over.
55 dest.assign(src, src + srcSize);
56
57 // Convert null characters to spaces.
58 std::transform(dest.begin(), dest.end(), dest.begin(), [] (char c) -> char { return (c != '\0') ? c : ' '; });
59
60 // Trim trailing spaces.
61 dest = mpt::trim_right(dest, std::string(" "));
62
63 }
64
65 return dest;
66
67 }
68
69 void WriteStringBuffer(String::ReadWriteMode mode, char *destBuffer, const std::size_t destSize, const char *srcBuffer, const std::size_t srcSize)
70 {
71
72 MPT_ASSERT(destSize > 0);
73
74 const size_t maxSize = std::min(destSize, srcSize);
75 char *dst = destBuffer;
76 const char *src = srcBuffer;
77
78 // First, copy over null-terminated string.
79 size_t pos = maxSize;
80 while(pos > 0)
81 {
82 if((*dst = *src) == '\0')
83 {
84 break;
85 }
86 pos--;
87 dst++;
88 src++;
89 }
90
91 if(mode == nullTerminated || mode == maybeNullTerminated)
92 {
93 // Fill rest of string with nulls.
94 std::fill(dst, dst + destSize - maxSize + pos, '\0');
95 } else if(mode == spacePadded || mode == spacePaddedNull)
96 {
97 // Fill the rest of the destination string with spaces.
98 std::fill(dst, dst + destSize - maxSize + pos, ' ');
99 }
100
101 if(mode == nullTerminated || mode == spacePaddedNull)
102 {
103 // Make sure that destination is really null-terminated.
104 SetNullTerminator(destBuffer, destSize);
105 }
106
107 }
108
109 } // namespace detail
110
111 } // namespace String
112
113 } // namespace mpt
114
115
116
117 OPENMPT_NAMESPACE_END