summaryrefslogtreecommitdiff
path: root/AK/ByteReader.h
blob: 5c2a4a8bbad227aebf3bbf73be226129ddc15639 (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
/*
 * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <AK/Types.h>

namespace AK {

struct ByteReader {
    static void store(u8* address, u16 value)
    {
        union {
            u16 _16;
            u8 _8[2];
        } const v { ._16 = value };
        __builtin_memcpy(address, v._8, 2);
    }

    static void store(u8* address, u32 value)
    {
        union {
            u32 _32;
            u8 _8[4];
        } const v { ._32 = value };
        __builtin_memcpy(address, v._8, 4);
    }

    static void load(const u8* address, u16& value)
    {
        union {
            u16 _16;
            u8 _8[2];
        } v { ._16 = 0 };
        __builtin_memcpy(&v._8, address, 2);
        value = v._16;
    }

    static void load(const u8* address, u32& value)
    {
        union {
            u32 _32;
            u8 _8[4];
        } v { ._32 = 0 };
        __builtin_memcpy(&v._8, address, 4);
        value = v._32;
    }

    static u16 load16(const u8* address)
    {
        u16 value;
        load(address, value);
        return value;
    }

    static u32 load32(const u8* address)
    {
        u32 value;
        load(address, value);
        return value;
    }
};

}

using AK::ByteReader;