1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* Functions for reading and writing integers in various endiannesses. */
10 * The classes LittleEndian and BigEndian expose static methods for
11 * reading and writing 16-, 32-, and 64-bit signed and unsigned integers
12 * in their respective endianness. The naming scheme is:
14 * {Little,Big}Endian::{read,write}{Uint,Int}<bitsize>
16 * For instance, LittleEndian::readInt32 will read a 32-bit signed
17 * integer from memory in little endian format. Similarly,
18 * BigEndian::writeUint16 will write a 16-bit unsigned integer to memory
19 * in big-endian format.
21 * The class NativeEndian exposes methods for conversion of existing
22 * data to and from the native endianness. These methods are intended
23 * for cases where data needs to be transferred, serialized, etc.
24 * swap{To,From}{Little,Big}Endian byteswap a single value if necessary.
25 * Bulk conversion functions are also provided which optimize the
26 * no-conversion-needed case:
28 * - copyAndSwap{To,From}{Little,Big}Endian;
29 * - swap{To,From}{Little,Big}EndianInPlace.
31 * The *From* variants are intended to be used for reading data and the
32 * *To* variants for writing data.
34 * Methods on NativeEndian work with integer data of any type.
35 * Floating-point data is not supported.
37 * For clarity in networking code, "Network" may be used as a synonym
38 * for "Big" in any of the above methods or class names.
40 * As an example, reading a file format header whose fields are stored
41 * in big-endian format might look like:
48 * uint32_t totalRecords;
52 * ExampleHeader(const void* data) {
53 * const uint8_t* ptr = static_cast<const uint8_t*>(data);
54 * magic = BigEndian::readUint32(ptr); ptr += sizeof(uint32_t);
55 * length = BigEndian::readUint32(ptr); ptr += sizeof(uint32_t);
56 * totalRecords = BigEndian::readUint32(ptr); ptr += sizeof(uint32_t);
57 * checksum = BigEndian::readUint64(ptr);
63 #ifndef mozilla_Endian_h
64 #define mozilla_Endian_h
66 #include "mozilla/Assertions.h"
67 #include "mozilla/Attributes.h"
68 #include "mozilla/Compiler.h"
69 #include "mozilla/DebugOnly.h"
70 #include "mozilla/TypeTraits.h"
75 #if defined(_MSC_VER) && _MSC_VER >= 1300
77 # pragma intrinsic(_byteswap_ushort)
78 # pragma intrinsic(_byteswap_ulong)
79 # pragma intrinsic(_byteswap_uint64)
83 # if defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_)
84 # define MOZ_LITTLE_ENDIAN 1
86 # error "CPU type is unknown"
90 # define MOZ_LITTLE_ENDIAN 1
92 # error "CPU type is unknown"
94 #elif defined(__APPLE__)
95 # if __LITTLE_ENDIAN__
96 # define MOZ_LITTLE_ENDIAN 1
98 # define MOZ_BIG_ENDIAN 1
100 #elif defined(__GNUC__) && \
101 defined(__BYTE_ORDER__) && \
102 defined(__ORDER_LITTLE_ENDIAN__) && \
103 defined(__ORDER_BIG_ENDIAN__)
105 * Some versions of GCC provide architecture-independent macros for
106 * this. Yes, there are more than two values for __BYTE_ORDER__.
108 # if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
109 # define MOZ_LITTLE_ENDIAN 1
110 # elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
111 # define MOZ_BIG_ENDIAN 1
113 # error "Can't handle mixed-endian architectures"
116 * We can't include useful headers like <endian.h> or <sys/isa_defs.h>
117 * here because they're not present on all platforms. Instead we have
118 * this big conditional that ideally will catch all the interesting
121 #elif defined(__sparc) || defined(__sparc__) || \
122 defined(_POWER) || defined(__powerpc__) || \
123 defined(__ppc__) || defined(__hppa) || \
124 defined(_MIPSEB) || defined(__ARMEB__) || \
125 defined(__s390__) || \
126 (defined(__sh__) && defined(__LITTLE_ENDIAN__)) || \
127 (defined(__ia64) && defined(__BIG_ENDIAN__))
128 # define MOZ_BIG_ENDIAN 1
129 #elif defined(__i386) || defined(__i386__) || \
130 defined(__x86_64) || defined(__x86_64__) || \
131 defined(_MIPSEL) || defined(__ARMEL__) || \
132 defined(__alpha__) || \
133 (defined(__sh__) && defined(__BIG_ENDIAN__)) || \
134 (defined(__ia64) && !defined(__BIG_ENDIAN__))
135 # define MOZ_LITTLE_ENDIAN 1
139 # define MOZ_LITTLE_ENDIAN 0
140 #elif MOZ_LITTLE_ENDIAN
141 # define MOZ_BIG_ENDIAN 0
143 # error "Cannot determine endianness"
146 #if defined(__clang__)
147 # if __has_builtin(__builtin_bswap16)
148 # define MOZ_HAVE_BUILTIN_BYTESWAP16 __builtin_bswap16
150 #elif defined(__GNUC__)
151 # if MOZ_GCC_VERSION_AT_LEAST(4, 8, 0)
152 # define MOZ_HAVE_BUILTIN_BYTESWAP16 __builtin_bswap16
154 #elif defined(_MSC_VER)
155 # define MOZ_HAVE_BUILTIN_BYTESWAP16 _byteswap_ushort
163 * We need wrappers here because free functions with default template
164 * arguments and/or partial specialization of function templates are not
165 * supported by all the compilers we use.
167 template<typename T
, size_t Size
= sizeof(T
)>
173 static T
swap(T value
)
175 #if defined(MOZ_HAVE_BUILTIN_BYTESWAP16)
176 return MOZ_HAVE_BUILTIN_BYTESWAP16(value
);
178 return T(((value
& 0x00ff) << 8) | ((value
& 0xff00) >> 8));
186 static T
swap(T value
)
188 #if defined(__clang__) || defined(__GNUC__)
189 return T(__builtin_bswap32(value
));
190 #elif defined(_MSC_VER)
191 return T(_byteswap_ulong(value
));
193 return T(((value
& 0x000000ffU
) << 24) |
194 ((value
& 0x0000ff00U
) << 8) |
195 ((value
& 0x00ff0000U
) >> 8) |
196 ((value
& 0xff000000U
) >> 24));
204 static inline T
swap(T value
)
206 #if defined(__clang__) || defined(__GNUC__)
207 return T(__builtin_bswap64(value
));
208 #elif defined(_MSC_VER)
209 return T(_byteswap_uint64(value
));
211 return T(((value
& 0x00000000000000ffULL
) << 56) |
212 ((value
& 0x000000000000ff00ULL
) << 40) |
213 ((value
& 0x0000000000ff0000ULL
) << 24) |
214 ((value
& 0x00000000ff000000ULL
) << 8) |
215 ((value
& 0x000000ff00000000ULL
) >> 8) |
216 ((value
& 0x0000ff0000000000ULL
) >> 24) |
217 ((value
& 0x00ff000000000000ULL
) >> 40) |
218 ((value
& 0xff00000000000000ULL
) >> 56));
223 enum Endianness
{ Little
, Big
};
226 # define MOZ_NATIVE_ENDIANNESS detail::Big
228 # define MOZ_NATIVE_ENDIANNESS detail::Little
234 * Assert that the memory regions [dest, dest+count) and [src, src+count]
235 * do not overlap. count is given in bytes.
237 static void assertNoOverlap(const void* dest
, const void* src
, size_t count
)
239 DebugOnly
<const uint8_t*> byteDestPtr
= static_cast<const uint8_t*>(dest
);
240 DebugOnly
<const uint8_t*> byteSrcPtr
= static_cast<const uint8_t*>(src
);
241 MOZ_ASSERT((byteDestPtr
<= byteSrcPtr
&&
242 byteDestPtr
+ count
<= byteSrcPtr
) ||
243 (byteSrcPtr
<= byteDestPtr
&&
244 byteSrcPtr
+ count
<= byteDestPtr
));
248 static void assertAligned(T
* ptr
)
250 MOZ_ASSERT((uintptr_t(ptr
) % sizeof(T
)) == 0, "Unaligned pointer!");
255 * Return |value| converted from SourceEndian encoding to DestEndian
258 template<Endianness SourceEndian
, Endianness DestEndian
, typename T
>
259 static inline T
maybeSwap(T value
)
261 if (SourceEndian
== DestEndian
)
264 return Swapper
<T
>::swap(value
);
268 * Convert |count| elements at |ptr| from SourceEndian encoding to
269 * DestEndian encoding.
271 template<Endianness SourceEndian
, Endianness DestEndian
, typename T
>
272 static inline void maybeSwapInPlace(T
* ptr
, size_t count
)
276 if (SourceEndian
== DestEndian
)
279 for (size_t i
= 0; i
< count
; i
++)
280 ptr
[i
] = Swapper
<T
>::swap(ptr
[i
]);
284 * Write |count| elements to the unaligned address |dest| in DestEndian
285 * format, using elements found at |src| in SourceEndian format.
287 template<Endianness SourceEndian
, Endianness DestEndian
, typename T
>
288 static void copyAndSwapTo(void* dest
, const T
* src
, size_t count
)
290 assertNoOverlap(dest
, src
, count
* sizeof(T
));
293 if (SourceEndian
== DestEndian
) {
294 memcpy(dest
, src
, count
* sizeof(T
));
298 uint8_t* byteDestPtr
= static_cast<uint8_t*>(dest
);
299 for (size_t i
= 0; i
< count
; ++i
) {
302 uint8_t buffer
[sizeof(T
)];
304 u
.val
= maybeSwap
<SourceEndian
, DestEndian
>(src
[i
]);
305 memcpy(byteDestPtr
, u
.buffer
, sizeof(T
));
306 byteDestPtr
+= sizeof(T
);
311 * Write |count| elements to |dest| in DestEndian format, using elements
312 * found at the unaligned address |src| in SourceEndian format.
314 template<Endianness SourceEndian
, Endianness DestEndian
, typename T
>
315 static void copyAndSwapFrom(T
* dest
, const void* src
, size_t count
)
317 assertNoOverlap(dest
, src
, count
* sizeof(T
));
320 if (SourceEndian
== DestEndian
) {
321 memcpy(dest
, src
, count
* sizeof(T
));
325 const uint8_t* byteSrcPtr
= static_cast<const uint8_t*>(src
);
326 for (size_t i
= 0; i
< count
; ++i
) {
329 uint8_t buffer
[sizeof(T
)];
331 memcpy(u
.buffer
, byteSrcPtr
, sizeof(T
));
332 dest
[i
] = maybeSwap
<SourceEndian
, DestEndian
>(u
.val
);
333 byteSrcPtr
+= sizeof(T
);
338 template<Endianness ThisEndian
>
339 class Endian
: private EndianUtils
342 /** Read a uint16_t in ThisEndian endianness from |p| and return it. */
343 static MOZ_WARN_UNUSED_RESULT
uint16_t readUint16(const void* p
) {
344 return read
<uint16_t>(p
);
347 /** Read a uint32_t in ThisEndian endianness from |p| and return it. */
348 static MOZ_WARN_UNUSED_RESULT
uint32_t readUint32(const void* p
) {
349 return read
<uint32_t>(p
);
352 /** Read a uint64_t in ThisEndian endianness from |p| and return it. */
353 static MOZ_WARN_UNUSED_RESULT
uint64_t readUint64(const void* p
) {
354 return read
<uint64_t>(p
);
357 /** Read an int16_t in ThisEndian endianness from |p| and return it. */
358 static MOZ_WARN_UNUSED_RESULT
int16_t readInt16(const void* p
) {
359 return read
<int16_t>(p
);
362 /** Read an int32_t in ThisEndian endianness from |p| and return it. */
363 static MOZ_WARN_UNUSED_RESULT
int32_t readInt32(const void* p
) {
364 return read
<uint32_t>(p
);
367 /** Read an int64_t in ThisEndian endianness from |p| and return it. */
368 static MOZ_WARN_UNUSED_RESULT
int64_t readInt64(const void* p
) {
369 return read
<int64_t>(p
);
372 /** Write |val| to |p| using ThisEndian endianness. */
373 static void writeUint16(void* p
, uint16_t val
) {
376 /** Write |val| to |p| using ThisEndian endianness. */
377 static void writeUint32(void* p
, uint32_t val
) {
380 /** Write |val| to |p| using ThisEndian endianness. */
381 static void writeUint64(void* p
, uint64_t val
) {
385 /** Write |val| to |p| using ThisEndian endianness. */
386 static void writeInt16(void* p
, int16_t val
) {
389 /** Write |val| to |p| using ThisEndian endianness. */
390 static void writeInt32(void* p
, int32_t val
) {
393 /** Write |val| to |p| using ThisEndian endianness. */
394 static void writeInt64(void* p
, int64_t val
) {
399 * Converts a value of type T to little-endian format.
401 * This function is intended for cases where you have data in your
402 * native-endian format and you need it to appear in little-endian
403 * format for transmission.
406 MOZ_WARN_UNUSED_RESULT
static T
swapToLittleEndian(T value
) {
407 return maybeSwap
<ThisEndian
, Little
>(value
);
410 * Copies count values of type T starting at src to dest, converting
411 * them to little-endian format if ThisEndian is Big.
412 * As with memcpy, dest and src must not overlap.
415 static void copyAndSwapToLittleEndian(void* dest
, const T
* src
,
417 copyAndSwapTo
<ThisEndian
, Little
>(dest
, src
, count
);
420 * Likewise, but converts values in place.
423 static void swapToLittleEndianInPlace(T
* p
, size_t count
) {
424 maybeSwapInPlace
<ThisEndian
, Little
>(p
, count
);
428 * Converts a value of type T to big-endian format.
431 MOZ_WARN_UNUSED_RESULT
static T
swapToBigEndian(T value
) {
432 return maybeSwap
<ThisEndian
, Big
>(value
);
435 * Copies count values of type T starting at src to dest, converting
436 * them to big-endian format if ThisEndian is Little.
437 * As with memcpy, dest and src must not overlap.
440 static void copyAndSwapToBigEndian(void* dest
, const T
* src
, size_t count
) {
441 copyAndSwapTo
<ThisEndian
, Big
>(dest
, src
, count
);
444 * Likewise, but converts values in place.
447 static void swapToBigEndianInPlace(T
* p
, size_t count
) {
448 maybeSwapInPlace
<ThisEndian
, Big
>(p
, count
);
452 * Synonyms for the big-endian functions, for better readability
456 MOZ_WARN_UNUSED_RESULT
static T
swapToNetworkOrder(T value
) {
457 return swapToBigEndian(value
);
461 copyAndSwapToNetworkOrder(void* dest
, const T
* src
, size_t count
) {
462 copyAndSwapToBigEndian(dest
, src
, count
);
466 swapToNetworkOrderInPlace(T
* p
, size_t count
) {
467 swapToBigEndianInPlace(p
, count
);
471 * Converts a value of type T from little-endian format.
474 MOZ_WARN_UNUSED_RESULT
static T
swapFromLittleEndian(T value
) {
475 return maybeSwap
<Little
, ThisEndian
>(value
);
478 * Copies count values of type T starting at src to dest, converting
479 * them to little-endian format if ThisEndian is Big.
480 * As with memcpy, dest and src must not overlap.
483 static void copyAndSwapFromLittleEndian(T
* dest
, const void* src
,
485 copyAndSwapFrom
<Little
, ThisEndian
>(dest
, src
, count
);
488 * Likewise, but converts values in place.
491 static void swapFromLittleEndianInPlace(T
* p
, size_t count
) {
492 maybeSwapInPlace
<Little
, ThisEndian
>(p
, count
);
496 * Converts a value of type T from big-endian format.
499 MOZ_WARN_UNUSED_RESULT
static T
swapFromBigEndian(T value
) {
500 return maybeSwap
<Big
, ThisEndian
>(value
);
503 * Copies count values of type T starting at src to dest, converting
504 * them to big-endian format if ThisEndian is Little.
505 * As with memcpy, dest and src must not overlap.
508 static void copyAndSwapFromBigEndian(T
* dest
, const void* src
,
510 copyAndSwapFrom
<Big
, ThisEndian
>(dest
, src
, count
);
513 * Likewise, but converts values in place.
516 static void swapFromBigEndianInPlace(T
* p
, size_t count
) {
517 maybeSwapInPlace
<Big
, ThisEndian
>(p
, count
);
521 * Synonyms for the big-endian functions, for better readability
525 MOZ_WARN_UNUSED_RESULT
static T
swapFromNetworkOrder(T value
) {
526 return swapFromBigEndian(value
);
529 static void copyAndSwapFromNetworkOrder(T
* dest
, const void* src
,
531 copyAndSwapFromBigEndian(dest
, src
, count
);
534 static void swapFromNetworkOrderInPlace(T
* p
, size_t count
) {
535 swapFromBigEndianInPlace(p
, count
);
540 * Read a value of type T, encoded in endianness ThisEndian from |p|.
541 * Return that value encoded in native endianness.
544 static T
read(const void* p
) {
547 uint8_t buffer
[sizeof(T
)];
549 memcpy(u
.buffer
, p
, sizeof(T
));
550 return maybeSwap
<ThisEndian
, MOZ_NATIVE_ENDIANNESS
>(u
.val
);
554 * Write a value of type T, in native endianness, to |p|, in ThisEndian
558 static void write(void* p
, T value
) {
559 T tmp
= maybeSwap
<MOZ_NATIVE_ENDIANNESS
, ThisEndian
>(value
);
560 memcpy(p
, &tmp
, sizeof(T
));
564 Endian(const Endian
& other
) MOZ_DELETE
;
565 void operator=(const Endian
& other
) MOZ_DELETE
;
568 template<Endianness ThisEndian
>
569 class EndianReadWrite
: public Endian
<ThisEndian
>
572 typedef Endian
<ThisEndian
> super
;
575 using super::readUint16
;
576 using super::readUint32
;
577 using super::readUint64
;
578 using super::readInt16
;
579 using super::readInt32
;
580 using super::readInt64
;
581 using super::writeUint16
;
582 using super::writeUint32
;
583 using super::writeUint64
;
584 using super::writeInt16
;
585 using super::writeInt32
;
586 using super::writeInt64
;
589 } /* namespace detail */
591 class LittleEndian MOZ_FINAL
: public detail::EndianReadWrite
<detail::Little
>
594 class BigEndian MOZ_FINAL
: public detail::EndianReadWrite
<detail::Big
>
597 typedef BigEndian NetworkEndian
;
599 class NativeEndian MOZ_FINAL
: public detail::Endian
<MOZ_NATIVE_ENDIANNESS
>
602 typedef detail::Endian
<MOZ_NATIVE_ENDIANNESS
> super
;
606 * These functions are intended for cases where you have data in your
607 * native-endian format and you need the data to appear in the appropriate
608 * endianness for transmission, serialization, etc.
610 using super::swapToLittleEndian
;
611 using super::copyAndSwapToLittleEndian
;
612 using super::swapToLittleEndianInPlace
;
613 using super::swapToBigEndian
;
614 using super::copyAndSwapToBigEndian
;
615 using super::swapToBigEndianInPlace
;
616 using super::swapToNetworkOrder
;
617 using super::copyAndSwapToNetworkOrder
;
618 using super::swapToNetworkOrderInPlace
;
621 * These functions are intended for cases where you have data in the
622 * given endianness (e.g. reading from disk or a file-format) and you
623 * need the data to appear in native-endian format for processing.
625 using super::swapFromLittleEndian
;
626 using super::copyAndSwapFromLittleEndian
;
627 using super::swapFromLittleEndianInPlace
;
628 using super::swapFromBigEndian
;
629 using super::copyAndSwapFromBigEndian
;
630 using super::swapFromBigEndianInPlace
;
631 using super::swapFromNetworkOrder
;
632 using super::copyAndSwapFromNetworkOrder
;
633 using super::swapFromNetworkOrderInPlace
;
636 #undef MOZ_NATIVE_ENDIANNESS
638 } /* namespace mozilla */
640 #endif /* mozilla_Endian_h */