added Matcher and Meanbuf files

master
Ondřej Hruška 8 years ago
parent 2f352b653f
commit 9984962b98
  1. 28
      matcher.c
  2. 21
      matcher.h
  3. 48
      meanbuf.c
  4. 21
      meanbuf.h

@ -0,0 +1,28 @@
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include "matcher.h"
/** Handle incoming char. Returns true if this char completed the match. */
bool matcher_test(matcher_t * m, uint8_t b)
{
// If mismatch, rewind (and check at 0)
if (m->pattern[m->cursor] != b) {
m->cursor = 0;
}
// Check for match
if (m->pattern[m->cursor] == b) {
// Good char
m->cursor++;
if (m->pattern[m->cursor] == 0) { // end of pattern
m->cursor = 0; // rewind
return true; // indicate success
}
}
return false;
}

@ -0,0 +1,21 @@
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
typedef struct {
const char *pattern;
size_t cursor;
} matcher_t;
/**
* Consume an incoming character.
* If this char was the last char of the pattern, returns true and rewinds.
*
* If the char is not in the pattern, resets match state.
*
* @returns true if the char concluded the expected pattern.
*/
bool matcher_test(matcher_t * mb, uint8_t b);

@ -0,0 +1,48 @@
#include <stdint.h>
#include <malloc.h>
#include "meanbuf.h"
/** Init a buffer */
void meanbuf_init(meanbuf_t *mb, size_t size)
{
if (size < 1) size = 1;
mb->buf = calloc(size, sizeof(float)); // calloc, so it starts with zeros.
mb->cap = size;
mb->nw = 0;
mb->mean = 0;
// clean buffer
for (uint16_t i = 0; i < size; i++) {
mb->buf[i] = 0;
}
}
void meanbuf_deinit(meanbuf_t *mb)
{
if (mb->buf != NULL) {
free(mb->buf);
}
}
/** Add a value to the buffer. Returns current mean. */
float meanbuf_add(meanbuf_t *mb, float f)
{
// add sample
mb->buf[mb->nw++] = f;
if (mb->nw == mb->cap) mb->nw = 0;
// calculate average
float acc = 0;
for (size_t i = 0; i < mb->cap; i++) {
acc += mb->buf[i];
}
acc /= mb->cap;
return mb->mean = acc;
}

@ -0,0 +1,21 @@
#pragma once
#include <stdlib.h>
#include <stdint.h>
typedef struct {
float * buf; // buffer (allocated at init)
size_t cap; // capacity
size_t nw; // next write index
float mean; // updated on write
} meanbuf_t;
/** Init a buffer */
void meanbuf_init(meanbuf_t *mb, size_t size);
/** Deinit a buffer (free buffer array) */
void meanbuf_deinit(meanbuf_t *mb);
/** Add a value to the buffer. Returns current mean. */
float meanbuf_add(meanbuf_t *mb, float f);
Loading…
Cancel
Save