File: switchendianness.d

package info (click to toggle)
sambamba 1.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 3,528 kB
  • sloc: sh: 220; python: 166; ruby: 147; makefile: 103
file content (50 lines) | stat: -rw-r--r-- 1,159 bytes parent folder | download | duplicates (2)
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
/**
  (Almost) a copy-paste from contrib.undead.stream.d
*/
module bio.core.utils.switchendianness;

import core.bitop;

/***
* Switches the byte order of buffer.
* $(D size) must be even.
*/
void switchEndianness(const(void)* buffer, size_t size)
in
{
  assert((size & 1) == 0);
}
do
{
    ubyte* startb = cast(ubyte*)buffer;
    uint* start = cast(uint*)buffer;
    switch (size) {
        case 0: break;
        case 2: {
            ubyte x = *startb;
            *startb = *(startb+1);
            *(startb+1) = x;
            break;
        }
        case 4: {
            *start = bswap(*start);
            break;
        }
        default: {
            uint* end = cast(uint*)(buffer + size - uint.sizeof);
            while (start < end) {
                uint x = bswap(*start);
                *start = bswap(*end);
                *end = x;
                ++start;
                --end;
            }
            startb = cast(ubyte*)start;
            ubyte* endb = cast(ubyte*)end;
            auto len = uint.sizeof - (startb - endb);
            if (len > 0) {
                switchEndianness(startb,len);
            }
        }
    }
}