aboutsummaryrefslogtreecommitdiffstats
path: root/marshal.c
diff options
context:
space:
mode:
authorMattias Andrée <maandree@kth.se>2019-02-09 20:44:43 +0100
committerMattias Andrée <maandree@kth.se>2019-02-09 20:44:43 +0100
commit8d0cea10adbe544c38ee458b9b2b67bba2c72959 (patch)
tree25cfa294cb284ca21ffb0a8c3793471dc6804543 /marshal.c
parentMinor changes, add man pages, rename libsha2_state_initialise to libsha2_init (diff)
downloadlibsha2-8d0cea10adbe544c38ee458b9b2b67bba2c72959.tar.gz
libsha2-8d0cea10adbe544c38ee458b9b2b67bba2c72959.tar.bz2
libsha2-8d0cea10adbe544c38ee458b9b2b67bba2c72959.tar.xz
Add marshal and unmarshal functions
Signed-off-by: Mattias Andrée <maandree@kth.se>
Diffstat (limited to '')
-rw-r--r--marshal.c62
1 files changed, 62 insertions, 0 deletions
diff --git a/marshal.c b/marshal.c
new file mode 100644
index 0000000..21f0f79
--- /dev/null
+++ b/marshal.c
@@ -0,0 +1,62 @@
+/* See LICENSE file for copyright and license details. */
+#include "common.h"
+
+
+/**
+ * Marshal a state into a buffer
+ *
+ * @param state The state to marshal
+ * @param buf Output buffer, `NULL` to only return the required size
+ * @return The number of bytes marshalled to `buf`
+ */
+size_t
+libsha2_marshal(const struct libsha2_state *restrict state, char *restrict buf)
+{
+ size_t off = 0;
+
+ if (buf)
+ *(int *)buf = 0; /* version */
+ off += sizeof(int);
+ if (buf)
+ *(enum libsha2_algorithm *)&buf[off] = state->algorithm;
+ off += sizeof(enum libsha2_algorithm);
+ if (buf)
+ *(size_t *)&buf[off] = state->message_size;
+ off += sizeof(size_t);
+
+ switch (state->algorithm) {
+ case LIBSHA2_224:
+ case LIBSHA2_256:
+ if (buf)
+ memcpy(&buf[off], state->k.b32, sizeof(state->k.b32));
+ off += sizeof(state->k.b32);
+ if (buf)
+ memcpy(&buf[off], state->w.b32, sizeof(state->w.b32));
+ off += sizeof(state->w.b32);
+ if (buf)
+ memcpy(&buf[off], state->h.b32, sizeof(state->h.b32));
+ off += sizeof(state->h.b32);
+ break;
+
+ default:
+ if (buf)
+ memcpy(&buf[off], state->k.b64, sizeof(state->k.b64));
+ off += sizeof(state->k.b64);
+ if (buf)
+ memcpy(&buf[off], state->w.b64, sizeof(state->w.b64));
+ off += sizeof(state->w.b64);
+ if (buf)
+ memcpy(&buf[off], state->h.b64, sizeof(state->h.b64));
+ off += sizeof(state->h.b64);
+ break;
+ }
+
+ if (buf)
+ memcpy(&buf[off], state->chunk, sizeof(state->chunk));
+ off += sizeof(state->chunk);
+ if (buf)
+ *(size_t *)&buf[off] = state->chunk_size;
+ off += sizeof(size_t);
+
+ return off;
+}