#include <sys/time.h>

#include <cstdint>

#include "itoa.h"
#include "lock.h"
#include "timer.h"
#include "uart.h"

extern unsigned char _heap_begin, _heap_end;

namespace {
void LogStats(unsigned char* heap) {
    char number[] = "00000000\r\n";
    UartWriteBlocking("Program break now at 0x");
    itoa(reinterpret_cast<int>(heap), number);
    UartWriteBlocking(number);
}
}  // namespace

extern "C" void* _sbrk(int increment) {
    static unsigned char* heap = &_heap_begin;
    unsigned char* prev_heap = heap;
    if (heap + increment >= &_heap_end) {
        UartWriteBlocking("Heap overflow!\r\n");
        return reinterpret_cast<void*>(-1);
    }
    heap += increment;
    LogStats(heap);
    return prev_heap;
}

extern "C" int _gettimeofday(struct timeval* tv, void* tzvp) {
    uint32_t ticks = timer0->GetT1Ticks();
    tv->tv_sec = ticks / 100000000;
    tv->tv_usec = (ticks % 100000000) / 100;

    return 0;
}

extern "C" uint8_t __atomic_exchange_1(volatile void* ptr, uint8_t val,
                                       int memorder) {
    auto* dest = reinterpret_cast<volatile uint8_t*>(ptr);
    bool ret;

    {
        InterruptLock lock;
        ret = *dest;
        *dest = val;
    }

    return ret;
}
