lib/mpi: mpi_read_buffer(): optimize skipping of leading zero limbs
authorNicolai Stange <nicstange@gmail.com>
Tue, 22 Mar 2016 12:12:40 +0000 (13:12 +0100)
committerHerbert Xu <herbert@gondor.apana.org.au>
Tue, 5 Apr 2016 12:35:49 +0000 (20:35 +0800)
Currently, if the number of leading zeros is greater than fits into a
complete limb, mpi_read_buffer() skips them by iterating over them
limb-wise.

Instead of skipping the high order zero limbs within the loop as shown
above, adjust the copying loop's bounds.

Signed-off-by: Nicolai Stange <nicstange@gmail.com>
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>
lib/mpi/mpicoder.c

index 623439e4bad5a8014698451b44bcf29fb6885a35..2fd8d418526ca9c03f26a15c28c7416d5da6b3ae 100644 (file)
@@ -184,7 +184,9 @@ int mpi_read_buffer(MPI a, uint8_t *buf, unsigned buf_len, unsigned *nbytes,
        p = buf;
        *nbytes = n - lzeros;
 
-       for (i = a->nlimbs - 1; i >= 0; i--) {
+       for (i = a->nlimbs - 1 - lzeros / BYTES_PER_MPI_LIMB,
+                       lzeros %= BYTES_PER_MPI_LIMB;
+               i >= 0; i--) {
                alimb = a->d[i];
 #if BYTES_PER_MPI_LIMB == 4
                *p++ = alimb >> 24;
@@ -205,15 +207,11 @@ int mpi_read_buffer(MPI a, uint8_t *buf, unsigned buf_len, unsigned *nbytes,
 #endif
 
                if (lzeros > 0) {
-                       if (lzeros >= sizeof(alimb)) {
-                               p -= sizeof(alimb);
-                       } else {
-                               mpi_limb_t *limb1 = (void *)p - sizeof(alimb);
-                               mpi_limb_t *limb2 = (void *)p - sizeof(alimb)
-                                                       + lzeros;
-                               *limb1 = *limb2;
-                               p -= lzeros;
-                       }
+                       mpi_limb_t *limb1 = (void *)p - sizeof(alimb);
+                       mpi_limb_t *limb2 = (void *)p - sizeof(alimb)
+                               + lzeros;
+                       *limb1 = *limb2;
+                       p -= lzeros;
                        lzeros -= sizeof(alimb);
                }
        }