/*
 * Copyright (c) 2016 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Created in Samsung Ukraine R&D Center (SRK) under a contract between
 * LLC "Samsung Electronics Ukraine Company" (Kiev, Ukraine)
 * and "Samsung Electronics Co", Ltd (Seoul, Republic of Korea)
 */

/**
 * @file TigerPemUtils.c
 * @brief TigerTa
 * @author Viktor Kopp (v.kopp@samsung.com)
 * @date Created Sep 26, 2016
 */

#include "TigerPemUtils.h"
#include <assert.h>

size_t getNewLineCharactersCount(const uint8_t* str, size_t strlen) {
    assert(NULL != str);

    size_t count = 0;
    for (size_t i = 0; i < strlen; ++i) {
        if (str[i] == '\n') {
            ++count;
        }
    }

    return count;
}

int replaceNewLineCharacters(uint8_t* dst, size_t dstlen, const uint8_t* src, size_t srclen) {
    assert(NULL != dst);
    assert(NULL != src);
    assert(0 != dstlen);
    assert(0 != srclen);

    size_t j = 0;
    for (size_t i = 0; (i < srclen) && (j < dstlen); ++i) {
        if (src[i] == '\n') {
            dst[j++] = '\\';
            if (j >= dstlen) {
                break;
            }
            dst[j++] = 'n';
        } else {
            dst[j++] = src[i];
        }
    }

    // To avoid an integer underflow due to arithmetic operation (unsigned subtraction)
    if (0 == j) {
        j = 1;
    }

    return (j - 1 < dstlen) ? 0 : -1;
}
