#include <stdint.h>
#include "tz_debug.h"

/*
 * Compute LRC value of p_buf[offset:offset+length]
 * Return : Computed LRC value.
 */
uint8_t computeLRC(uint8_t *p_buf, uint32_t offset, uint32_t length) {
    uint32_t LRC = 0, i = 0;

    for (i = offset; i < length; i++) {
        LRC = LRC ^ p_buf[i];
    }

    return (uint8_t) LRC;
}

/*
 * Calculate the LRC of buffer and compare it with received LRC value.
 * Return : 0 for success, computed LRC value for fail.
 */
uint8_t checkLRC(uint8_t *p_buf, uint32_t buf_len) {
    uint8_t calc_lrc = 0;
    uint8_t recv_lrc = 0;
    recv_lrc = p_buf[buf_len - 1];
    /* calculate the LRC after excluding received LRC  */
    calc_lrc = computeLRC(p_buf, 0, (buf_len -1));

    if (recv_lrc != calc_lrc) {
        LOGE("[%s] LRC is incorrect. recv_lrc[0x%x], computed_lrc[0x%x]",
             __func__, recv_lrc, calc_lrc);
        return calc_lrc;
    }

    return 0;
}
