Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sarpik:sarpik/add-nesting-fix-circular-deps #5

Merged
merged 8 commits into from
Jan 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
"cinttypes": "cpp",
"typeinfo": "cpp",
"valarray": "cpp",
"variant": "cpp"
"variant": "cpp",
"*.rh": "cpp"
}
}
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

I needed [xstate](https://github.com/davidkpiano/xstate) in C++. Here we are

## Features

* Basic stuff (I dunno I'm new here I just wanted a state machine for myself ☃)
* Nested state machines just landed in by #5 - see [./xstate.cpp](./xstate.cpp) for an example.
* Others coming in real soon. Actually, even sooner, if you wanna contribute:P

## Installation

You only need the [`xstate.h`](./xstate.h) header file - that's it.
Expand Down Expand Up @@ -83,13 +89,13 @@ int main() {
compile with:

```sh
g++ -std=c++11
g++ -std=c++17
```

for example,

```sh
g++ -std=c++11 ./xstate.cpp -o xstate.out
g++ -std=c++17 ./xstate.cpp -o xstate.out
```

## License
Expand Down
2 changes: 1 addition & 1 deletion go
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@

PROGNAME="${1:-"xstate"}"

g++ -std=c++11 ./"$PROGNAME".cpp -o "$PROGNAME".out && ./"$PROGNAME".out
g++ -std=c++17 ./"$PROGNAME".cpp -o "$PROGNAME".out && ./"$PROGNAME".out
240 changes: 233 additions & 7 deletions xstate.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,219 @@
* compile with:
*
* ```sh
* g++ -std=c++11 ./xstate.cpp -o xstate.out
* g++ -std=c++17 ./xstate.cpp -o xstate.out
* ```
*
*/

#include "xstate.h"

// using namespace xs;
#include <vector>
#include <string>
#include <sstream>

std::vector<std::string> splitStr(std::string str = "", const char delim = ' ') {
std::string buf; // Have a buffer string
std::stringstream ss(str); // Insert the string into a stream

std::vector<std::string> tokens; // Create vector to hold our words

while (getline(ss, buf, delim)) {
tokens.push_back(buf);
}

return tokens;
}

namespace xs {

const char *StateMachine::transition(const char *currentState, const char *event)
{
std::vector<std::string> stateAccessTokens = splitStr(currentState, '.');

// printf("num of tokens %d\n", stateAccessTokens.size());

// for (auto &token : stateAccessTokens) {
// printf("token %s\n", token.c_str());
// }

StateMachine *head = this;

/** go deeper & traverse */
for (size_t i = 0; i + 1 < stateAccessTokens.size(); ++i) {
const char *stateToken = stateAccessTokens[i].c_str();
head = &head->states[stateToken].nested;
}

const int lastIndex = stateAccessTokens.size() - 1;
std::string lastStateAccessToken = stateAccessTokens[lastIndex];

/**
* HALP FIXME
*
* lmfao I spent way too much time here
*
* don't use `const char *` for indexing for sure.
*
*/
const char *nextState = head->states[lastStateAccessToken].on[event];

// printf("nextState %s\n", nextState);

return nextState;
}

struct Interpreter {
private:

InterpreterStatus status;

InterpreterState *state;
StateMachine *stateMachine;

public:

Interpreter(StateMachine *stateMachine)
:
stateMachine(stateMachine),
state(new InterpreterState({ .value = stateMachine->initial})),
status(notStarted)
{
}

const char *getStatusStr() const {
return InterpreterStatusStrings[this->status];
}

Interpreter *logInfo() {
printf("status = %d (%s) | state = %s \n", this->status, this->getStatusStr(), this->state->value);
return this;
}

Interpreter *send(const char *event) {
if (this->status != started) {
fprintf(
stderr,
"\nERR interpreter.send was called when it was not started / stopped (%s).\n",
this->getStatusStr()
);

throw;
}

const char *nextState = this->stateMachine->transition(this->state->value, event);
// printf("nextState %s\n", nextState);

/**
* An event might've been fired at the wrong time /
* when the state didn't have any handlers for that specific event,
* thus we just skip it, since that's allowed.
*/
if (nextState != NULL) {
this->state->value = nextState;
}

this->handleOnTransition();

return this;
}

/** handlers (identical) */



// void onStart(std::function<void(const InterpreterState *state)> callback = [](const InterpreterState *state) {}) const {
// callback(this->state);
// }

Interpreter *start() {
this->status = started;
this->handleOnStart();

return this;
}

/** the one we call ourselves */
private: std::function<const void()> handleOnStart = []() {};

public:
Interpreter *onStart(const std::function<const void( )> callback = []( ) {}) {
this->handleOnStart = [&]() { callback( ); };
return this;
}

/** the one we expose to the consumer so he can inject the callback */
Interpreter *onStart(const std::function<const void(Interpreter *self)> callback = [](Interpreter *self) {}) {
this->handleOnStart = [&]() { callback(this); };
return this;
}



// std::function<void( )> onTransition = []( ) {};
// std::function<void(const InterpreterState *state)> onTransition = [](const InterpreterState *state) {};

// void onTransition(std::function<void()> callback = []() {}) const {
// callback();
// }

/** the one we call ourselves */
private: std::function<const void()> handleOnTransition = []() {};

/** the one we expose to the consumer so he can inject the callback */
public:
Interpreter *onTransition(const std::function<const void( )> callback = []( ) {}) {
this->handleOnTransition = [&]() { callback( ); };
return this;
}

Interpreter *onTransition(const std::function<const void(Interpreter *self)> callback = [](Interpreter *self) {}) {
this->handleOnTransition = [&]() { callback(this); };
return this;
}



// std::function<void()> onStop = []() {};
// void onStop(std::function<void(const InterpreterState *state)> callback = [](const InterpreterState *state) {}) const {
// callback(this->state);
// }

Interpreter *stop() {
this->status = stopped;
this->handleOnStop();
return this;
}

/** the one we call ourselves */
private: std::function<const void()> handleOnStop = []() {};

/** the one we expose to the consumer so he can inject the callback */
public:
Interpreter *onStop(const std::function<const void( )> callback = []( ) {}) {
this->handleOnStop = [&]() { callback( ); };
return this;
}

Interpreter *onStop(const std::function<const void(Interpreter *self)> callback = [](Interpreter *self) {}) {
this->handleOnStop = [&]() { callback(this); };
return this;
}
};

Interpreter *interpret(StateMachine stateMachine) {
Interpreter *interpreter = new Interpreter(new StateMachine(stateMachine));

return interpreter;
}

Interpreter *interpret(StateMachine *stateMachine) {
Interpreter *interpreter = new Interpreter( stateMachine );

return interpreter;
}

} // namespace xs

int main() {
xs::StateMachine machine = {
Expand All @@ -36,7 +241,23 @@ int main() {
},
{
"red" ,
{ .on = { { "TIMER", "green" } } }
{
.on = { { "TIMER", "red.red-100" } },
.nested = {
.id = "red-brightness",
.initial = "red-100",
.states = {
{
"red-100",
{ .on = { { "TIMER", "red.red-0" } } }
},
{
"red-0",
{ .on = { { "TIMER", "green" } } }
}
}
}
},
}
}
};
Expand All @@ -46,12 +267,11 @@ int main() {
->onStart([]() {
printf("let's go!\n");
})
->onTransition([]() {
printf("yay we transitioned!\n");
->onTransition([](xs::Interpreter *self) {
self->logInfo();
})
->onStop([](xs::Interpreter *self) {
->onStop([]() {
printf("oh no we stopped c:\n");
self->logInfo();
})
->start();

Expand All @@ -61,6 +281,12 @@ int main() {

toggleMachine->send("TIMER");

toggleMachine->send("TIMER");

toggleMachine->send("TIMER");

toggleMachine->send("TIMER");

toggleMachine->stop();

delete toggleMachine;
Expand Down
Loading