Ruby 4.1.0dev (2026-11-24 revision 9920c0670630fd2ca853d66ca08e5848c96c0301)
memequal.h
1#ifndef PRISM_INTERNAL_MEMEQUAL_H
2#define PRISM_INTERNAL_MEMEQUAL_H
3
5
6#include <stdbool.h>
7#include <stdint.h>
8#include <string.h>
9
10/* Copy into integer locals so the input slices may have any alignment. */
11static PRISM_INLINE bool
12pm_memequal_16(const unsigned char *a, const unsigned char *b) {
13 uint16_t left, right;
14 memcpy(&left, a, sizeof(left));
15 memcpy(&right, b, sizeof(right));
16 return left == right;
17}
18
19static PRISM_INLINE bool
20pm_memequal_32(const unsigned char *a, const unsigned char *b) {
21 uint32_t left, right;
22 memcpy(&left, a, sizeof(left));
23 memcpy(&right, b, sizeof(right));
24 return left == right;
25}
26
27static PRISM_INLINE bool
28pm_memequal_64(const unsigned char *a, const unsigned char *b) {
29 uint64_t left, right;
30 memcpy(&left, a, sizeof(left));
31 memcpy(&right, b, sizeof(right));
32 return left == right;
33}
34
35/* Compare slices longer than 16 bytes out of line. */
36bool pm_memequal_long(const unsigned char *a, const unsigned char *b, size_t length);
37
38/*
39 * Test two byte slices for equality using fixed-size loads. The final load
40 * ends at the end of the slice and may overlap the preceding load.
41 */
42static PRISM_FORCE_INLINE bool
43pm_memequal(const void *left, const void *right, size_t length) {
44 const unsigned char *a = (const unsigned char *) left;
45 const unsigned char *b = (const unsigned char *) right;
46
47 if (length > 16) {
48 return pm_memequal_long(a, b, length);
49 } else if (length >= 8) {
50 return pm_memequal_64(a, b) && pm_memequal_64(a + (length - 8), b + (length - 8));
51 } else if (length >= 4) {
52 return pm_memequal_32(a, b) && pm_memequal_32(a + (length - 4), b + (length - 4));
53 } else if (length >= 2) {
54 return pm_memequal_16(a, b) && pm_memequal_16(a + (length - 2), b + (length - 2));
55 } else if (length == 1) {
56 return *a == *b;
57 } else {
58 return true;
59 }
60}
61
62#endif
#define PRISM_FORCE_INLINE
Force a function to be inlined at every call site.
#define PRISM_INLINE
Old Visual Studio versions do not support the inline keyword, so we need to define it to be __inline.
Definition inline.h:12
C99 shim for <stdbool.h>.