Move mbedtls_cf_mem_move_to_left function to the constant-time module

Signed-off-by: Gabor Mezei <gabor.mezei@arm.com>
diff --git a/library/constant_time.c b/library/constant_time.c
index b48305a..281df64 100644
--- a/library/constant_time.c
+++ b/library/constant_time.c
@@ -354,3 +354,44 @@
 }
 
 #endif /* MBEDTLS_BIGNUM_C */
+
+/** Shift some data towards the left inside a buffer without leaking
+ * the length of the data through side channels.
+ *
+ * `mbedtls_cf_mem_move_to_left(start, total, offset)` is functionally
+ * equivalent to
+ * ```
+ * memmove(start, start + offset, total - offset);
+ * memset(start + offset, 0, total - offset);
+ * ```
+ * but it strives to use a memory access pattern (and thus total timing)
+ * that does not depend on \p offset. This timing independence comes at
+ * the expense of performance.
+ *
+ * \param start     Pointer to the start of the buffer.
+ * \param total     Total size of the buffer.
+ * \param offset    Offset from which to copy \p total - \p offset bytes.
+ */
+void mbedtls_cf_mem_move_to_left( void *start,
+                                         size_t total,
+                                         size_t offset )
+{
+    volatile unsigned char *buf = start;
+    size_t i, n;
+    if( total == 0 )
+        return;
+    for( i = 0; i < total; i++ )
+    {
+        unsigned no_op = mbedtls_cf_size_gt( total - offset, i );
+        /* The first `total - offset` passes are a no-op. The last
+         * `offset` passes shift the data one byte to the left and
+         * zero out the last byte. */
+        for( n = 0; n < total - 1; n++ )
+        {
+            unsigned char current = buf[n];
+            unsigned char next = buf[n+1];
+            buf[n] = mbedtls_cf_uint_if( no_op, current, next );
+        }
+        buf[total-1] = mbedtls_cf_uint_if( no_op, buf[total-1], 0 );
+    }
+}