|
| 1 | +/* |
| 2 | + +----------------------------------------------------------------------+ |
| 3 | + | Copyright (c) The PHP Group | |
| 4 | + +----------------------------------------------------------------------+ |
| 5 | + | This source file is subject to version 3.01 of the PHP license, | |
| 6 | + | that is bundled with this package in the file LICENSE, and is | |
| 7 | + | available through the world-wide-web at the following url: | |
| 8 | + | https://www.php.net/license/3_01.txt | |
| 9 | + | If you did not receive a copy of the PHP license and are unable to | |
| 10 | + | obtain it through the world-wide-web, please send a note to | |
| 11 | + | license@php.net so we can mail you a copy immediately. | |
| 12 | + +----------------------------------------------------------------------+ |
| 13 | + | Authors: Niels Dossche <nielsdos@php.net> | |
| 14 | + +----------------------------------------------------------------------+ |
| 15 | +*/ |
| 16 | + |
| 17 | +#include "bcmath.h" |
| 18 | +#include "convert.h" |
| 19 | + |
| 20 | +/* This will be 0x01010101 for 32-bit and 0x0101010101010101 */ |
| 21 | +#define SWAR_ONES (~((size_t) 0) / 0xFF) |
| 22 | +/* This repeats a byte `x` into an entire 32/64-bit word. |
| 23 | + * Example: SWAR_REPEAT(0xAB) will be 0xABABABAB for 32-bit and 0xABABABABABABABAB for 64-bit. */ |
| 24 | +#define SWAR_REPEAT(x) (SWAR_ONES * (x)) |
| 25 | + |
| 26 | +static char *bc_copy_and_shift_numbers(char *restrict dest, const char *source, const char *source_end, unsigned char shift, bool add) |
| 27 | +{ |
| 28 | + size_t bulk_shift = SWAR_REPEAT(shift); |
| 29 | + if (!add) { |
| 30 | + bulk_shift = -bulk_shift; |
| 31 | + shift = -shift; |
| 32 | + } |
| 33 | + |
| 34 | + /* Handle sizeof(size_t) (i.e. 4/8) bytes at once. |
| 35 | + * We know that adding/subtracting an individual byte cannot overflow, |
| 36 | + * so it is possible to add/subtract an entire word of bytes at once |
| 37 | + * by using SWAR_REPEAT. */ |
| 38 | + while (source + sizeof(size_t) <= source_end) { |
| 39 | + size_t bytes; |
| 40 | + memcpy(&bytes, source, sizeof(bytes)); |
| 41 | + |
| 42 | + bytes += bulk_shift; |
| 43 | + memcpy(dest, &bytes, sizeof(bytes)); |
| 44 | + |
| 45 | + source += sizeof(size_t); |
| 46 | + dest += sizeof(size_t); |
| 47 | + } |
| 48 | + |
| 49 | + while (source < source_end) { |
| 50 | + *dest = *source + shift; |
| 51 | + dest++; |
| 52 | + source++; |
| 53 | + } |
| 54 | + |
| 55 | + return dest; |
| 56 | +} |
| 57 | + |
| 58 | +char *bc_copy_ch_val(char *restrict dest, const char *source, const char *source_end) |
| 59 | +{ |
| 60 | + return bc_copy_and_shift_numbers(dest, source, source_end, '0', false); |
| 61 | +} |
| 62 | + |
| 63 | +char *bc_copy_bcd_val(char *restrict dest, const char *source, const char *source_end) |
| 64 | +{ |
| 65 | + return bc_copy_and_shift_numbers(dest, source, source_end, '0', true); |
| 66 | +} |
0 commit comments