Skip to content

Commit

Permalink
Merge pull request #10797 from kaspar030/add_unaligned
Browse files Browse the repository at this point in the history
sys: add unaligned.h (header for alignment safe value-from-pointer functions)
  • Loading branch information
miri64 authored Jan 26, 2019
2 parents 6cd81db + 344af9c commit bdd2d52
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 1 deletion.
3 changes: 2 additions & 1 deletion sys/checksum/fletcher32.c
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
* @}
*/

#include "unaligned.h"
#include "checksum/fletcher32.h"

uint32_t fletcher32(const uint16_t *data, size_t words)
Expand All @@ -28,7 +29,7 @@ uint32_t fletcher32(const uint16_t *data, size_t words)
unsigned tlen = words > 359 ? 359 : words;
words -= tlen;
do {
sum2 += sum1 += *data++;
sum2 += sum1 += unaligned_get_u16(data++);
} while (--tlen);
sum1 = (sum1 & 0xffff) + (sum1 >> 16);
sum2 = (sum2 & 0xffff) + (sum2 >> 16);
Expand Down
69 changes: 69 additions & 0 deletions sys/include/unaligned.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
* Copyright (C) 2019 Kaspar Schleiser <kaspar@schleiser.de>
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*/

/**
* @defgroup sys_unaligned unaligned memory access methods
* @ingroup sys
* @brief Provides functions for safe unaligned memory accesses
*
* This header provides functions to read values from pointers that are not
* necessarily aligned to the type's alignment requirements.
*
* E.g.,
*
* uint16_t *foo = 0x123;
* printf("%u\n", *foo);
*
* ... might cause an unaligned access, if `uint16_t` is usually aligned at
* 2-byte-boundaries, as foo has an odd address.
*
* The current implementation casts a pointer to a packed struct, which forces
* the compiler to deal with possibly unalignedness. Idea taken from linux
* kernel sources.
*
* @{
*
* @file
* @brief Unaligned but safe memory access functions
*
* @author Kaspar Schleiser <kaspar@schleiser.de>
*/

#ifndef UNALIGNED_H
#define UNALIGNED_H

#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

/** @brief Unaligned access helper struct (uint16_t version) */
typedef struct __attribute__((packed)) {
uint16_t val; /**< value */
} uint16_una_t;

/**
* @brief Get uint16_t from possibly unaligned pointer
*
* @param[in] ptr pointer to read from
*
* @returns value read from @p ptr
*/
static inline uint16_t unaligned_get_u16(const void *ptr)
{
const uint16_una_t *tmp = ptr;
return tmp->val;
}

#ifdef __cplusplus
}
#endif

/** @} */
#endif /* UNALIGNED_H */

0 comments on commit bdd2d52

Please # to comment.