Brain_Fuck/include/bf_interpreter.h

89 lines
1.7 KiB
C++

#pragma once
/*
* Created by Brett on 17/11/23.
* Licensed under GNU General Public License V3.0
* See LICENSE file for license detail
*/
#ifndef BRAINFUCK_MISC_BF_INTERPRETER_H
#define BRAINFUCK_MISC_BF_INTERPRETER_H
#include <cstdint>
#include <cstring>
#include <string>
class brainfuck_interpreter
{
private:
size_t _size;
size_t _dp;
char* _data;
void check_size();
public:
brainfuck_interpreter(): _size(30000), _dp(0), _data(new char[_size])
{std::memset(_data, 0, _size);}
void increment_dp()
{
_dp++;
}
void decrement_dp()
{
if (_dp != 0)
_dp--;
}
void increment()
{
check_size();
_data[_dp]++;
}
void decrement()
{
check_size();
_data[_dp]--;
}
template<typename OutStream>
void print(OutStream& stream)
{
stream << _data[_dp];
}
template<typename InStream>
void read(InStream& stream)
{
_data[_dp] = stream.get();
}
char is()
{
return _data[_dp];
}
~brainfuck_interpreter()
{ delete[] _data; }
};
template<typename functor>
static inline void match(functor f, int sp, size_t& index, const std::string& program)
{
while (f(index) < program.size())
{
if (program[index] == '[')
sp++;
if (program[index] == ']')
sp--;
if (sp == 0)
break;
}
}
void interpret_bf(const std::string& program);
#endif //BRAINFUCK_MISC_BF_INTERPRETER_H