aboutsummaryrefslogtreecommitdiff
path: root/middle/tanya/memory/op.d
blob: 93a507f9766055318ac8046e518706ebd6953b92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
 * Set of operations on memory blocks.
 *
 * Copyright: Eugene Wissner 2017-2020.
 * License: $(LINK2 https://www.mozilla.org/en-US/MPL/2.0/,
 *                  Mozilla Public License, v. 2.0).
 * Authors: $(LINK2 mailto:info@caraus.de, Eugene Wissner)
 * Source: $(LINK2 https://github.com/caraus-ecms/tanya/blob/master/middle/tanya/memory/op.d,
 *                 tanya/memory/op.d)
 */
module tanya.memory.op;

version (TanyaNative)
{
    extern private void fillMemory(void[], size_t) pure nothrow @system @nogc;

    extern private void copyMemory(const void[], void[])
    pure nothrow @system @nogc;

    extern private void moveMemory(const void[], void[])
    pure nothrow @system @nogc;

    extern private bool equalMemory(const void[], const void[])
    pure nothrow @system @nogc;
}
else
{
    import core.stdc.string;
}

private enum alignMask = size_t.sizeof - 1;

/**
 * Copies $(D_PARAM source) into $(D_PARAM target).
 *
 * $(D_PARAM source) and $(D_PARAM target) shall not overlap so that
 * $(D_PARAM source) points ahead of $(D_PARAM target).
 *
 * $(D_PARAM target) shall have enough space for $(D_INLINECODE source.length)
 * elements.
 *
 * Params:
 *  source = Memory to copy from.
 *  target = Destination memory.
 *
 * See_Also: $(D_PSYMBOL copyBackward).
 *
 * Precondition: $(D_INLINECODE source.length <= target.length).
 */
void copy(const void[] source, void[] target) @nogc nothrow pure @trusted
in (source.length <= target.length)
in (source.length == 0 || source.ptr !is null)
in (target.length == 0 || target.ptr !is null)
{
    version (TanyaNative)
    {
        copyMemory(source, target);
    }
    else
    {
        memcpy(target.ptr, source.ptr, source.length);
    }
}

///
@nogc nothrow pure @safe unittest
{
    ubyte[9] source = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    ubyte[9] target;
    source.copy(target);
    assert(equal(source, target));
}

/*
 * size_t value each of which bytes is set to `Byte`.
 */
private template filledBytes(ubyte Byte, ubyte I = 0)
{
    static if (I == size_t.sizeof)
    {
        enum size_t filledBytes = Byte;
    }
    else
    {
        enum size_t filledBytes = (filledBytes!(Byte, I + 1) << 8) | Byte;
    }
}

/**
 * Fills $(D_PARAM memory) with the single byte $(D_PARAM c).
 *
 * Param:
 *  c      = The value to fill $(D_PARAM memory) with.
 *  memory = Memory block.
 */
void fill(ubyte c = 0)(void[] memory) @trusted
in (memory.length == 0 || memory.ptr !is null)
{
    version (TanyaNative)
    {
        fillMemory(memory, filledBytes!c);
    }
    else
    {
        memset(memory.ptr, c, memory.length);
    }
}

///
@nogc nothrow pure @safe unittest
{
    ubyte[9] memory = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    memory.fill!0();
    foreach (ubyte v; memory)
    {
        assert(v == 0);
    }
}

/**
 * Copies starting from the end of $(D_PARAM source) into the end of
 * $(D_PARAM target).
 *
 * $(D_PSYMBOL copyBackward) copies the elements in reverse order, but the
 * order of elements in the $(D_PARAM target) is exactly the same as in the
 * $(D_PARAM source).
 *
 * $(D_PARAM source) and $(D_PARAM target) shall not overlap so that
 * $(D_PARAM target) points ahead of $(D_PARAM source).
 *
 * $(D_PARAM target) shall have enough space for $(D_INLINECODE source.length)
 * elements.
 *
 * Params:
 *  source = Memory to copy from.
 *  target = Destination memory.
 *
 * See_Also: $(D_PSYMBOL copy).
 *
 * Precondition: $(D_INLINECODE source.length <= target.length).
 */
void copyBackward(const void[] source, void[] target) @nogc nothrow pure @trusted
in (source.length <= target.length)
in (source.length == 0 || source.ptr !is null)
in (target.length == 0 || target.ptr !is null)
{
    version (TanyaNative)
    {
        moveMemory(source, target);
    }
    else
    {
        memmove(target.ptr, source.ptr, source.length);
    }
}

///
@nogc nothrow pure @safe unittest
{
    ubyte[6] mem = [ 'a', 'a', 'b', 'b', 'c', 'c' ];
    ubyte[6] expected = [ 'a', 'a', 'a', 'a', 'b', 'b' ];

    copyBackward(mem[0 .. 4], mem[2 .. $]);
    assert(equal(expected, mem));
}

/**
 * Finds the first occurrence of $(D_PARAM needle) in $(D_PARAM haystack) if
 * any.
 *
 * Params:
 *  haystack = Memory block.
 *  needle   = A byte.
 *
 * Returns: The subrange of $(D_PARAM haystack) whose first element is the
 *          first occurrence of $(D_PARAM needle). If $(D_PARAM needle)
 *          couldn't be found, an empty `inout void[]` is returned.
 */
inout(void[]) find(return inout void[] haystack, ubyte needle)
@nogc nothrow pure @trusted
in (haystack.length == 0 || haystack.ptr !is null)
{
    auto length = haystack.length;
    const size_t needleWord = size_t.max * needle;
    enum size_t highBits = filledBytes!(0x01, 0);
    enum size_t mask = filledBytes!(0x80, 0);

    // Align
    auto bytes = cast(inout(ubyte)*) haystack;
    while (length > 0 && ((cast(size_t) bytes) & 3) != 0)
    {
        if (*bytes == needle)
        {
            return bytes[0 .. length];
        }
        ++bytes;
        --length;
    }

    // Check if some of the words has the needle
    auto words = cast(inout(size_t)*) bytes;
    while (length >= size_t.sizeof)
    {
        if ((((*words ^ needleWord) - highBits) & (~*words) & mask) != 0)
        {
            break;
        }
        ++words;
        length -= size_t.sizeof;
    }

    // Find the exact needle position in the word
    bytes = cast(inout(ubyte)*) words;
    while (length > 0)
    {
        if (*bytes == needle)
        {
            return bytes[0 .. length];
        }
        ++bytes;
        --length;
    }

    return haystack[$ .. $];
}

///
@nogc nothrow pure @safe unittest
{
    const ubyte[9] haystack = ['a', 'b', 'c', 'd', 'e', 'f', 'b', 'g', 'h'];

    assert(equal(find(haystack, 'a'), haystack[]));
    assert(equal(find(haystack, 'b'), haystack[1 .. $]));
    assert(equal(find(haystack, 'c'), haystack[2 .. $]));
    assert(equal(find(haystack, 'd'), haystack[3 .. $]));
    assert(equal(find(haystack, 'e'), haystack[4 .. $]));
    assert(equal(find(haystack, 'f'), haystack[5 .. $]));
    assert(equal(find(haystack, 'h'), haystack[8 .. $]));
    assert(find(haystack, 'i').length == 0);

    assert(find(null, 'a').length == 0);
}

/**
 * Looks for `\0` in the $(D_PARAM haystack) and returns the part of the
 * $(D_PARAM haystack) ahead of it.
 *
 * Returns $(D_KEYWORD null) if $(D_PARAM haystack) doesn't contain a null
 * character.
 *
 * Params:
 *  haystack = Memory block.
 *
 * Returns: The subrange that spans all bytes before the null character or
 *          $(D_KEYWORD null) if the $(D_PARAM haystack) doesn't contain any.
 */
inout(char[]) findNullTerminated(return inout char[] haystack)
@nogc nothrow pure @trusted
in (haystack.length == 0 || haystack.ptr !is null)
{
    auto length = haystack.length;
    enum size_t highBits = filledBytes!(0x01, 0);
    enum size_t mask = filledBytes!(0x80, 0);

    // Align
    auto bytes = cast(inout(ubyte)*) haystack;
    while (length > 0 && ((cast(size_t) bytes) & 3) != 0)
    {
        if (*bytes == '\0')
        {
            return haystack[0 .. haystack.length - length];
        }
        ++bytes;
        --length;
    }

    // Check if some of the words contains 0
    auto words = cast(inout(size_t)*) bytes;
    while (length >= size_t.sizeof)
    {
        if (((*words - highBits) & (~*words) & mask) != 0)
        {
            break;
        }
        ++words;
        length -= size_t.sizeof;
    }

    // Find the exact 0 position in the word
    bytes = cast(inout(ubyte)*) words;
    while (length > 0)
    {
        if (*bytes == '\0')
        {
            return haystack[0 .. haystack.length - length];
        }
        ++bytes;
        --length;
    }

    return null;
}

///
@nogc nothrow pure @safe unittest
{
    assert(equal(findNullTerminated("abcdef\0gh"), "abcdef"));
    assert(equal(findNullTerminated("\0garbage"), ""));
    assert(equal(findNullTerminated("\0"), ""));
    assert(equal(findNullTerminated("cstring\0"), "cstring"));
    assert(findNullTerminated(null) is null);
    assert(findNullTerminated("abcdef") is null);
}

/**
 * Compares two memory areas $(D_PARAM r1) and $(D_PARAM r2) for equality.
 *
 * Params:
 *  r1 = First memory block.
 *  r2 = Second memory block.
 *
 * Returns: $(D_KEYWORD true) if $(D_PARAM r1) and $(D_PARAM r2) are equal,
 *          $(D_KEYWORD false) otherwise.
 */
bool equal(const void[] r1, const void[] r2) @nogc nothrow pure @trusted
in (r1.length == 0 || r1.ptr !is null)
in (r2.length == 0 || r2.ptr !is null)
{
    version (TanyaNative)
    {
        return equalMemory(r1, r2);
    }
    else
    {
        return r1.length == r2.length
            && memcmp(r1.ptr, r2.ptr, r1.length) == 0;
    }
}

///
@nogc nothrow pure @safe unittest
{
    assert(equal("asdf", "asdf"));
    assert(!equal("asd", "asdf"));
    assert(!equal("asdf", "asd"));
    assert(!equal("asdf", "qwer"));
}