/* * TinyBlocks - tb_csv.c * Blocos Csv.Rows e Csv.Get. */ #include #include #include #include #include "tb_csv.h" #define CAT_COLOR 120/255.f, 180/255.f, 90/255.f, 1.f #define CAT_DARK 80/255.f, 140/255.f, 55/255.f, 1.f static void eval_rows(TinyBlocks_Block* self, TinyBlocks* rt) { TinyBlocks_Value text = tb_block_get_input(self, rt, 0); const char* src = (text.kind == TB_VALUE_TEXT && text.as.text) ? text.as.text : ""; CsvTable* t = csv_split(src, ',', NULL, 0); tb_block_set_output(self, 0, tb_value_integer(t ? t->count : 0)); csv_table_free(t); self->dirty = false; } static void eval_get(TinyBlocks_Block* self, TinyBlocks* rt) { TinyBlocks_Value text = tb_block_get_input(self, rt, 0); TinyBlocks_Value rv = tb_block_get_input(self, rt, 1); TinyBlocks_Value cv = tb_block_get_input(self, rt, 2); const char* src = (text.kind == TB_VALUE_TEXT && text.as.text) ? text.as.text : ""; int row = (rv.kind == TB_VALUE_INTEGER) ? (int)rv.as.integer : 0; int col = (cv.kind == TB_VALUE_INTEGER) ? (int)cv.as.integer : 0; CsvTable* t = csv_split(src, ',', NULL, 0); const char* out = ""; if (t && row >= 0 && row < t->count && col >= 0 && col < t->rows[row].count) out = t->rows[row].fields[col]; tb_block_set_output(self, 0, tb_value_text(out)); csv_table_free(t); self->dirty = false; } static bool csv_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { static const TinyBlocks_Category cat = { "CSV", {CAT_COLOR}, {CAT_DARK} }; tb_library_set_category(lib, &cat); static const TinyBlocks_SlotDesc rows_in[] = {{"texto", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc get_in[] = {{"texto", TB_VALUE_TEXT}, {"linha", TB_VALUE_INTEGER}, {"coluna", TB_VALUE_INTEGER}}; static const TinyBlocks_SlotDesc out_i[] = {{"linhas", TB_VALUE_INTEGER}}; static const TinyBlocks_SlotDesc out_t[] = {{"valor", TB_VALUE_TEXT}}; TinyBlocks_TypeBlock* a = tb_type_block_create(rt, "Csv.Rows", rows_in, 1, out_i, 1, eval_rows); TinyBlocks_TypeBlock* b = tb_type_block_create(rt, "Csv.Get", get_in, 3, out_t, 1, eval_get); return a && b && tb_library_add(lib, &a->base) && tb_library_add(lib, &b->base); } static void csv_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { (void)rt; (void)lib; } TINYBLOCKS_DEFINE_LIBRARY(csv, "tinyblocks-csv", "1.0.0", csv_init, csv_deinit) const TinyBlocks_LibraryDescriptor* tb_csv_get_library(void) { return &_tb_lib_desc_csv; }