/*
 * src/tee_string.c
 *
 * Copyright (C) 2013, Samsung Electronics Co., Ltd.
 *
 * TEE memory manipulation routines
 */

#include <tee_internal_api.h>
#include <string.h>
#include <stdlib.h>

char *strdup(const char *s)
{
    size_t size = strlen(s) + 1;
    char *result = TEE_Malloc(size, HINT_FILL_WITH_ZEROS);
    if (result != NULL) {
        TEE_MemMove(result, s, size);
        return result;
    }
    return NULL;
}

static uint32_t le2be32(uint32_t n) {
    return 0 | ((n & 0x000000ff) << 24)
             | ((n & 0x0000ff00) << 8)
             | ((n & 0x00ff0000) >> 8)
             | ((n & 0xff000000) >> 24);
}
static uint16_t le2be16(uint16_t n) {
    return 0 | ((n & 0x00ff) << 8)
             | ((n & 0xff00) >> 8);
}

char* uuid2string(const TEE_UUID* uuid, char* str) {
    /* we want str like this: 79B77788-9789-4a7a-A2BE-B60155EEF5F3 */
    static const char digits[] = "0123456789abcdef";
    /* convert to big endian */
    static TEE_UUID _uuid;
    memcpy(&_uuid, uuid, sizeof(TEE_UUID));
    _uuid.timeLow = le2be32(_uuid.timeLow);
    _uuid.timeMid = le2be16(_uuid.timeMid);
    _uuid.timeHiAndVersion = le2be16(_uuid.timeHiAndVersion);

    int i;
    char* origin_str = str;
    const char* data = (const char*) &_uuid;
    for (i = 0; i < 16; i++) {
        int c = (data[i] >> 4) & 0xf;
        *str++ = digits[c];

        c = data[i] & 0xf;
        *str++ = digits[c];

        if (i == 3 || i == 5 || i == 7 || i == 9)
            *str++ = '-';
    }
    origin_str[36] = '\0';
    return origin_str;
}

char* u32_2string(const uint32_t* u_int, char* str) {
    /* we want str like this: 0x0F00A5A5 */
    static const char digits[] = "0123456789abcdef";
    /* convert to big endian */
    static uint32_t _u32;
    _u32 = *u_int;
    _u32 = le2be32(_u32);

    int i;
    char* origin_str = str;
    const char* data = (const char*) &_u32;
    *str++ = '0';
    *str++ = 'x';
    for (i = 0; i < 4; i++) {
        int c = (data[i] >> 4) & 0xf;
        *str++ = digits[c];

        c = data[i] & 0xf;
        *str++ = digits[c];

    }
    origin_str[10] = '\0';
    return origin_str;
}
