/*
 * slip-filter.cpp
 *
 *  Created on: 31 ���. 2018 �.
   Copyright 2018 alexrayne <alexraynepe196@gmail.com>

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

#include "slip-filter.hpp"



//------------------------      SLIPBufFilter         ----------------------------
SLIPBufFilter::SLIPBufFilter(buffer_t* src)
: parsed()
{
    on_frame = NULL;
    rx = src;
    reset();
}

void        SLIPBufFilter::reset(){
    state = dsNorm;
    if (rx == NULL)
        return;
    buf_head  = rx->DataBuf();//FreeBuf();
    if (!rx->isEmpty()){
        if (rx->touch_char() != ESC){
            // в буфере непонятно что, отброшу это.
            rx->Drop();
        }
        // в буфере лежит фрейм,  перефильтрую что там осталось
        buf_head  = rx->DataBuf();
    }
    parsed.Assign(*rx);
}


int        SLIPBufFilter::have_frame() const{
    if (state == dsFrame)
        return parsed.DataSize();
    return -1;
}

void        SLIPBufFilter::leave_frame(){
    rx->DataBuf(buf_head);
    clear_parsed();
    state = dsNorm;
    on_receive_refresh();
}

// clears parsed stream
void        SLIPBufFilter::clear_parsed(){
    parsed.FreeBuf(buf_head);
    parsed.Drop();
}

// спросматривает поступившие в буфер данные и фильтрует их.
int         SLIPBufFilter::on_receive_refresh(){
    value_p end = rx->FreeBuf();
    if (end == buf_head)
        // no data in rx added
        return 0;
    if (state == dsFrame)
        //have buffered frame, need leave to continue
        return 0;

    unsigned size = 0;

    if (end < buf_head){
        // buffer overrun
        size = decode(rx->StoreLimit()-buf_head);
        if (buf_head >= rx->StoreLimit())
            buf_head = rx->Store();
        if (have_frame() > 0)
            return 1;
    }
    if (end > buf_head)
        size += decode(end-buf_head);
    if (have_frame() > 0)
        return 1;
    return 0;
}

//  decode data from buf_head block size len
// \arg     buf_head - moves to end decoded source
// \return  decoded data len
unsigned    SLIPBufFilter::decode(unsigned len){
    if (state == dsFrame)
        return 0;

    if (parsed.isEmpty()){
        clear_parsed();
    }
    unsigned res = parsed.DataSize();
    for ( ; len > 0; len--){
        u8 c = *buf_head++;
        if (c == END) {
            if (!parsed.isEmpty() || zero_frames_valid ){
                state = dsFrame;
                if (on_frame)
                    on_frame(this);
                break; //return rx->DataSize() - res;
            }
            clear_parsed();
            // из приемника отброшу отпаршеные фреймы
            rx->DataBuf(buf_head);
            continue;
        }
        else if (c == ESC){
            state = dsESC;
            continue;
        }
        else if (c == ESC_END) {
            if (state == dsESC){
                c = END;
                state = dsNorm;
            }
        } else if (c == ESC_ESC) {
            if (state == dsESC){
                c = ESC;
                state = dsNorm;
            }
        }
        parsed.push_char(c);
    }
    return parsed.DataSize() - res;
}

// \return dst encoded len
//static
unsigned  SLIPBufFilter::encode(void* __restrict dst, const void* __restrict src, unsigned len){
    u8* __restrict          pd = (u8*)dst;
    const u8* __restrict    ps = (const u8*)src;
    for (;len > 0; len--){
        u8 c = *ps++;
        if (c == END){
            *pd++ = ESC;
            *pd++ = ESC_END;
        }
        else if (c == ESC){
            *pd++ = ESC;
            *pd++ = ESC_ESC;
        }
        else
            *pd++ = c;
    }
    return pd - (u8*)dst;
}

//static
unsigned SLIPBufFilter::encode(void* dst, char c){
    u8* pd = (u8*)dst;
    if (c == END){
        *pd++ = ESC;
        *pd++ = ESC_END;
    }
    else if (c == ESC){
        *pd++ = ESC;
        *pd++ = ESC_ESC;
    }
    else {
        *pd++ = c;
    }
    return pd - (u8*)dst;
}

//static
unsigned SLIPBufFilter::strcspn(const void* src, unsigned len){
    const u8* ps = (const u8*)src;
    for ( ;len > 0 ;len--, ps++){
        u8 c = *ps;
        if ((c == ESC) || (c == END))
            break;
    }
    return ps - (u8*)src;
}

//static
unsigned SLIPBufFilter::strcspn(const void* src){
    const u8* ps = (const u8*)src;
    for ( ; (*ps != 0) ;ps++){
        u8 c = *ps;
        if ((c == ESC) || (c == END))
            break;
    }
    return ps - (u8*)src;
}
