Path: blob/main/contrib/bearssl/src/int/i31_decred.c
39483 views
/*1* Copyright (c) 2016 Thomas Pornin <[email protected]>2*3* Permission is hereby granted, free of charge, to any person obtaining4* a copy of this software and associated documentation files (the5* "Software"), to deal in the Software without restriction, including6* without limitation the rights to use, copy, modify, merge, publish,7* distribute, sublicense, and/or sell copies of the Software, and to8* permit persons to whom the Software is furnished to do so, subject to9* the following conditions:10*11* The above copyright notice and this permission notice shall be12* included in all copies or substantial portions of the Software.13*14* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,15* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF16* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND17* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS18* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN19* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN20* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE21* SOFTWARE.22*/2324#include "inner.h"2526/* see inner.h */27void28br_i31_decode_reduce(uint32_t *x,29const void *src, size_t len, const uint32_t *m)30{31uint32_t m_ebitlen, m_rbitlen;32size_t mblen, k;33const unsigned char *buf;34uint32_t acc;35int acc_len;3637/*38* Get the encoded bit length.39*/40m_ebitlen = m[0];4142/*43* Special case for an invalid (null) modulus.44*/45if (m_ebitlen == 0) {46x[0] = 0;47return;48}4950/*51* Clear the destination.52*/53br_i31_zero(x, m_ebitlen);5455/*56* First decode directly as many bytes as possible. This requires57* computing the actual bit length.58*/59m_rbitlen = m_ebitlen >> 5;60m_rbitlen = (m_ebitlen & 31) + (m_rbitlen << 5) - m_rbitlen;61mblen = (m_rbitlen + 7) >> 3;62k = mblen - 1;63if (k >= len) {64br_i31_decode(x, src, len);65x[0] = m_ebitlen;66return;67}68buf = src;69br_i31_decode(x, buf, k);70x[0] = m_ebitlen;7172/*73* Input remaining bytes, using 31-bit words.74*/75acc = 0;76acc_len = 0;77while (k < len) {78uint32_t v;7980v = buf[k ++];81if (acc_len >= 23) {82acc_len -= 23;83acc <<= (8 - acc_len);84acc |= v >> acc_len;85br_i31_muladd_small(x, acc, m);86acc = v & (0xFF >> (8 - acc_len));87} else {88acc = (acc << 8) | v;89acc_len += 8;90}91}9293/*94* We may have some bits accumulated. We then perform a shift to95* be able to inject these bits as a full 31-bit word.96*/97if (acc_len != 0) {98acc = (acc | (x[1] << acc_len)) & 0x7FFFFFFF;99br_i31_rshift(x, 31 - acc_len);100br_i31_muladd_small(x, acc, m);101}102}103104105