File:  [ELWIX - Embedded LightWeight unIX -] / embedaddon / bird / lib / unaligned.h
Revision 1.1.1.2 (vendor branch): download - view: text, annotated - select for diffs - revision graph
Wed Mar 17 19:50:23 2021 UTC (3 years, 4 months ago) by misho
Branches: bird, MAIN
CVS tags: v1_6_8p3, HEAD
bird 1.6.8

    1: /*
    2:  *	Unaligned Data Accesses -- Generic Version, Network Order
    3:  *
    4:  *	(c) 2000 Martin Mares <mj@ucw.cz>
    5:  *
    6:  *	Can be freely distributed and used under the terms of the GNU GPL.
    7:  */
    8: 
    9: #ifndef _BIRD_UNALIGNED_H_
   10: #define _BIRD_UNALIGNED_H_
   11: 
   12: /*
   13:  *  We don't do any clever tricks with unaligned accesses since it's
   14:  *  virtually impossible to figure out what alignment does the CPU want
   15:  *  (unaligned accesses can be emulated by the OS which makes them work,
   16:  *  but unusably slow). We use memcpy and hope GCC will optimize it out
   17:  *  if possible.
   18:  */
   19: 
   20: #include "lib/string.h"
   21: 
   22: static inline u16
   23: get_u16(const void *p)
   24: {
   25:   u16 x;
   26:   memcpy(&x, p, 2);
   27:   return ntohs(x);
   28: }
   29: 
   30: static inline u32
   31: get_u32(const void *p)
   32: {
   33:   u32 x;
   34:   memcpy(&x, p, 4);
   35:   return ntohl(x);
   36: }
   37: 
   38: static inline u64
   39: get_u64(const void *p)
   40: {
   41:   u32 xh, xl;
   42:   memcpy(&xh, p, 4);
   43:   memcpy(&xl, p+4, 4);
   44:   return (((u64) ntohl(xh)) << 32) | ntohl(xl);
   45: }
   46: 
   47: static inline void
   48: put_u8(void *p, u8 x)
   49: {
   50:   memcpy(p, &x, 1);
   51: }
   52: 
   53: static inline void
   54: put_u16(void *p, u16 x)
   55: {
   56:   x = htons(x);
   57:   memcpy(p, &x, 2);
   58: }
   59: 
   60: static inline void
   61: put_u32(void *p, u32 x)
   62: {
   63:   x = htonl(x);
   64:   memcpy(p, &x, 4);
   65: }
   66: 
   67: static inline void
   68: put_u64(void *p, u64 x)
   69: {
   70:   u32 xh, xl;
   71:   xh = htonl(x >> 32);
   72:   xl = htonl((u32) x);
   73:   memcpy(p, &xh, 4);
   74:   memcpy(p+4, &xl, 4);
   75: }
   76: 
   77: #endif

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>