| 1 | // SPDX-License-Identifier: MIT OR MPL-2.0 OR LGPL-2.1-or-later OR GPL-2.0-or-later |
| 2 | // Copyright 2015, SIL International, All rights reserved. |
| 3 | |
| 4 | |
| 5 | #pragma once |
| 6 | |
| 7 | #include <cassert> |
| 8 | #include <cstddef> |
| 9 | #include <cstring> |
| 10 | |
| 11 | namespace |
| 12 | { |
| 13 | |
| 14 | #if defined(_MSC_VER) |
| 15 | typedef unsigned __int8 u8; |
| 16 | typedef unsigned __int16 u16; |
| 17 | typedef unsigned __int32 u32; |
| 18 | typedef unsigned __int64 u64; |
| 19 | #else |
| 20 | #include <stdint.h> |
| 21 | typedef uint8_t u8; |
| 22 | typedef uint16_t u16; |
| 23 | typedef uint32_t u32; |
| 24 | typedef uint64_t u64; |
| 25 | #endif |
| 26 | |
| 27 | ptrdiff_t const MINMATCH = 4, |
| 28 | LASTLITERALS = 5, |
| 29 | MINCODA = LASTLITERALS+1, |
| 30 | MINSRCSIZE = 13; |
| 31 | |
| 32 | template<int S> |
| 33 | inline |
| 34 | void unaligned_copy(void * d, void const * s) { |
| 35 | ::memcpy(d, s, S); |
| 36 | } |
| 37 | |
| 38 | inline |
| 39 | size_t align(size_t p) { |
| 40 | return (p + sizeof(unsigned long)-1) & ~(sizeof(unsigned long)-1); |
| 41 | } |
| 42 | |
| 43 | inline |
| 44 | u8 * safe_copy(u8 * d, u8 const * s, size_t n) { |
| 45 | while (n--) *d++ = *s++; |
| 46 | return d; |
| 47 | } |
| 48 | |
| 49 | inline |
| 50 | u8 * overrun_copy(u8 * d, u8 const * s, size_t n) { |
| 51 | size_t const WS = sizeof(unsigned long); |
| 52 | u8 const * e = s + n; |
| 53 | do |
| 54 | { |
| 55 | unaligned_copy<WS>(d, s); |
| 56 | d += WS; |
| 57 | s += WS; |
| 58 | } |
| 59 | while (s < e); |
| 60 | d-=(s-e); |
| 61 | |
| 62 | return d; |
| 63 | } |
| 64 | |
| 65 | |
| 66 | inline |
| 67 | u8 * fast_copy(u8 * d, u8 const * s, size_t n) { |
| 68 | size_t const WS = sizeof(unsigned long); |
| 69 | size_t wn = n/WS; |
| 70 | while (wn--) |
| 71 | { |
| 72 | unaligned_copy<WS>(d, s); |
| 73 | d += WS; |
| 74 | s += WS; |
| 75 | } |
| 76 | n &= WS-1; |
| 77 | return safe_copy(d, s, n); |
| 78 | } |
| 79 | |
| 80 | |
| 81 | } // end of anonymous namespace |
| 82 | |