byteorder: Add buffer swap helpers
Two functions are proposed:
- sys_memcpy_swap(): will memcpy and swap the 2 given buffers
- sys_mem_swap(): will swap the buffer in place.
The idea is to propose 2 different functions optimized for 2 different
usage.
Change-Id: I1c23907c1f287b72d9be077ccf3aadbb8d379e71
Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
diff --git a/include/misc/byteorder.h b/include/misc/byteorder.h
index 9322caa..57539fc 100644
--- a/include/misc/byteorder.h
+++ b/include/misc/byteorder.h
@@ -22,6 +22,8 @@
#define __BYTEORDER_H__
#include <stdint.h>
+#include <stddef.h>
+#include <misc/__assert.h>
/* Internal helpers only used by the sys_* APIs further below */
#define __bswap_16(x) ((uint16_t) ((((x) >> 8) & 0xff) | (((x) & 0xff) << 8)))
@@ -266,4 +268,52 @@
return ((uint64_t)sys_get_le32(&src[4]) << 32) | sys_get_le32(&src[0]);
}
+/**
+ * @brief Swap one buffer content into another
+ *
+ * Copy the content of src buffer into dst buffer in reversed order,
+ * i.e.: src[n] will be put in dst[end-n]
+ * Where n is an index and 'end' the last index in both arrays.
+ * The 2 memory pointers must be pointing to different areas, and have
+ * a minimum size of given length.
+ *
+ * @param dst A valid pointer on a memory area where to copy the data in
+ * @param src A valid pointer on a memory area where to copy the data from
+ * @param length Size of both dst and src memory areas
+ */
+static inline void sys_memcpy_swap(void *dst, const void *src, size_t length)
+{
+ __ASSERT(((src < dst && src + length < dst) ||
+ (src > dst && dst + length < src)),
+ "Source and destination pointers must not overlap");
+
+ src += length - 1;
+
+ for (; length > 0; length--) {
+ *((uint8_t *)dst++) = *((uint8_t *)src--);
+ }
+}
+
+/**
+ * @brief Swap buffer content
+ *
+ * In-place memory swap, where final content will be reversed.
+ * I.e.: buf[n] will be put in buf[end-n]
+ * Where n is an index and 'end' the last index of buf.
+ *
+ * @param buf A valid pointer on a memory area to swap
+ * @param length Size of buf memory area
+ */
+static inline void sys_mem_swap(void *buf, size_t length)
+{
+ int i;
+
+ for (i = 0; i < (length/2); i++) {
+ uint8_t tmp = ((uint8_t *)buf)[i];
+
+ ((uint8_t *)buf)[i] = ((uint8_t *)buf)[length - 1 - i];
+ ((uint8_t *)buf)[length - 1 - i] = tmp;
+ }
+}
+
#endif /* __BYTEORDER_H__ */