Skip to content

Commit

Permalink
feat: add note functions
Browse files Browse the repository at this point in the history
  • Loading branch information
b4nst committed Aug 20, 2023
1 parent 4ac8b3d commit abd284f
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 6 deletions.
16 changes: 10 additions & 6 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
define execute-command
$(1)

endef

BUILDDIR = build

TOOLS = tools
Expand Down Expand Up @@ -62,15 +67,14 @@ $(BUILDDIR)/%.o: %.c
mkdir -p $(dir $@)
$(CC) -c $(CFLAGS) -MMD -o $@ $<

$(BUILDDIR)/tests/%.run: tests/%.c
$(BUILDDIR)/tests/%.run: tests/%.c $(SOURCES) $(MOCKS)
mkdir -p $(dir $@)
$(HOST_GCC) -g3 -O0 -std=c99 -Iinclude $^ $(SOURCES) $(MOCKS) -o $@ -lcmocka
$(HOST_GCC) -g3 -O0 -std=c99 -Iinclude $^ -o $@ -lcmocka

test: $(TEST_RUNS)
@for test in $(TEST_RUNS); do \
echo "Running $$test"; \
$$test; \
done
@$(foreach test, $(TEST_RUNS), \
$(call execute-command, $(test)))
@echo "All tests completed"

fmt: $(SOURCES) $(HEADERS)
clang-format --style=$(CODE_STYLE) -i $^
Expand Down
25 changes: 25 additions & 0 deletions include/note.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#ifndef NOTE_H
#define NOTE_H

#define OCTAVE 12

enum ScaleIndex {
MAJOR_SCALE = 0,
MINOR_SCALE,
};

static const short scales[][12] = {{1, -1, 0, -1, 0, 0, -1, 0, -1, 0, -1, 0},
{1, -1, 0, 0, -1, 0, -1, 0, 0, -1, 0, -1}};

/**
* @brief Checks if a note is in a scale.
* @param note The note to check.
* @param scale The root note of the scale.
* @param scale_index The index of the scale table.
* @return -1 if the note is not in the scale, 0 if it is, 1 if it is and it's
* the root note.
*/
short is_note_in_scale(unsigned char note, unsigned char scale,
int scale_index);

#endif // NOTE_H
11 changes: 11 additions & 0 deletions src/note.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#include "note.h"

short is_note_in_scale(const unsigned char note, const unsigned char scale,
const int scale_index) {
int idx = (note - scale) % OCTAVE;
if (idx < 0) {
idx += OCTAVE;
}

return scales[scale_index][idx];
}
21 changes: 21 additions & 0 deletions tests/note_test.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <stdint.h>
#include <cmocka.h>
#include "note.h"

static void test_is_note_in_scale(void **state) {
assert_int_equal(is_note_in_scale(0, 0, MAJOR_SCALE), 1);
assert_int_equal(is_note_in_scale(92, 0, MINOR_SCALE), 0);
assert_int_equal(is_note_in_scale(0, 3, MAJOR_SCALE), 0);
assert_int_equal(is_note_in_scale(95, 0, MINOR_SCALE), -1);
}

int main(void) {
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_is_note_in_scale),
};

return cmocka_run_group_tests(tests, NULL, NULL);
}

0 comments on commit abd284f

Please sign in to comment.