mirror of
https://github.com/RGBCube/serenity
synced 2025-07-26 05:37:35 +00:00
LibCrypto+LibTLS: Avoid unaligned reads and writes
This adds an `AK::ByteReader` to help with that so we don't duplicate the logic all over the place. No more `*(const u16*)` and `*(const u32*)` for anyone. This should help a little with #7060.
This commit is contained in:
parent
bfd4c7a16c
commit
df515e1d85
6 changed files with 88 additions and 17 deletions
69
AK/ByteReader.h
Normal file
69
AK/ByteReader.h
Normal file
|
@ -0,0 +1,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;
|
Loading…
Add table
Add a link
Reference in a new issue