/*
MIT License

Copyright (c) 2020-2022 Rupert Carmichael

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/* Signed values are pushed and popped unsigned, but will retain their initial
 * value, as these functions simply record the bit pattern.
 */

#include <stddef.h>
#include <stdint.h>

#include "vecx_serial.h"

static size_t pos = 0;

// Begin a Serialize or Deserialize operation
void vecx_serial_begin(void) {
    pos = 0;
}

// Serially push a block of memory, one byte at a time
void vecx_serial_pushblk(uint8_t *dst, uint8_t *src, size_t len) {
    for (size_t i = 0; i < len; ++i)
        dst[pos + i] = src[i];
    pos += len;
}

// Serially pop a block of memory, one byte at a time
void vecx_serial_popblk(uint8_t *dst, uint8_t *src, size_t len) {
    for (size_t i = 0; i < len; ++i)
        dst[i] = src[pos + i];
    pos += len;
}

// Push an 8-bit integer
void vecx_serial_push8(uint8_t *mem, uint8_t v) {
    mem[pos++] = v;
}

// Push a 16-bit integer
void vecx_serial_push16(uint8_t *mem, uint16_t v) {
    mem[pos++] = v >> 8;
    mem[pos++] = v & 0xff;
}

// Push a 32-bit integer
void vecx_serial_push32(uint8_t *mem, uint32_t v) {
    mem[pos++] = v >> 24;
    mem[pos++] = (v >> 16) & 0xff;
    mem[pos++] = (v >> 8) & 0xff;
    mem[pos++] = v & 0xff;
}

// Pop an 8-bit integer
uint8_t vecx_serial_pop8(uint8_t *mem) {
    return mem[pos++];
}

// Pop a 16-bit integer
uint16_t vecx_serial_pop16(uint8_t *mem) {
    uint16_t ret = mem[pos++] << 8;
    ret |= mem[pos++];
    return ret;
}

// Pop a 32-bit integer
uint32_t vecx_serial_pop32(uint8_t *mem) {
    uint32_t ret = mem[pos++] << 24;
    ret |= mem[pos++] << 16;
    ret |= mem[pos++] << 8;
    ret |= mem[pos++];
    return ret;
}

// Return the size of the serialized data
size_t vecx_serial_size(void) {
    return pos + 1;
}
