2 * Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
19 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
20 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 br_i32_decode_reduce(uint32_t *x
,
30 const void *src
, size_t len
, const uint32_t *m
)
34 const unsigned char *buf
;
39 * Special case for an invalid modulus.
47 * Clear the destination.
49 br_i32_zero(x
, m_bitlen
);
52 * First decode directly as many bytes as possible without
53 * reduction, taking care to leave a number of bytes which
56 mblen
= (m_bitlen
+ 7) >> 3;
60 * Up to k bytes can be safely decoded.
63 br_i32_decode(x
, src
, len
);
69 * We want to first inject some bytes with direct decoding,
70 * then extra bytes by whole 32-bit words. First compute
71 * the size that should be injected that way.
74 q
= (len
- k
+ 3) & ~(size_t)3;
77 * It may happen that this is more than what we already have
78 * (by at most 3 bytes). Such a case may happen only with
79 * a very short modulus. In that case, we must process the first
87 for (i
= 0; i
< 4; i
++) {
94 br_i32_muladd_small(x
, w
, m
);
96 br_i32_decode(x
, buf
, len
- q
);
101 * At that point, we have exactly q bytes to inject, and q is
104 for (k
= len
- q
; k
< len
; k
+= 4) {
105 br_i32_muladd_small(x
, br_dec32be(buf
+ k
), m
);