diff --git a/example/ex11-algo02.c b/example/ex11-algo02.c index 37e4ae84..af6cc08e 100644 --- a/example/ex11-algo02.c +++ b/example/ex11-algo02.c @@ -17,10 +17,14 @@ ARRAY_DEF(vector_employee, employee_t) #define M_OPL_vector_employee_t() ARRAY_OPLIST(vector_employee, M_OPL_employee_t()) ALGO_DEF(vector_employee, vector_employee_t) -/* Define the function object to select the sort order */ -FUNC_OBJ_INS_DEF(compare_by, - vector_employee_cmp_obj, - (a, b), { +/* Define the function object to select the sort order + * named 'compare_by' which is an instance of the interface + * 'vector_employee_cmp_obj' created by ALGO_DEF. + */ +FUNC_OBJ_INS_DEF(compare_by /* name of the instance */, + vector_employee_cmp_obj /* name of the interface */, + (a, b) /* name of the input parameters of the function like object. The type are inherited from the interface. */, { + /* code of the function object */ if (string_equal_str_p(self->sort_field, "name")) return string_cmp(a->name, b->name); else if (string_equal_str_p(self->sort_field, "age")) @@ -28,6 +32,7 @@ FUNC_OBJ_INS_DEF(compare_by, else return a->idnum < b->idnum ? -1 : a->idnum > b->idnum; }, + /* Additional fields stored in the function object */ (sort_field, string_t) ) #define M_OPL_compare_by_t() FUNC_OBJ_INS_OPLIST(compare_by, STRING_OPLIST) @@ -39,19 +44,25 @@ static void read(vector_employee_t base, const char filename[]) // Open the file FILE *f = fopen(filename, "rt"); if (!f) { + // Handle errors fprintf(stderr, "ERROR: Cannot open file '%s'.\n", filename); exit(2); } + // Initialize the JSON serializer with this file M_LET( (in,f), m_serial_json_read_t) + // Read the JSON file and fill in 'base' with it. ret = vector_employee_in_serial(base, in); - // Let's handle errors + + // Let's handle serialization error if (ret != M_SERIAL_OK_DONE) { fprintf(stderr, "ERROR: Cannot read JSON data from file '%s'.\nParsing stops at:\n", filename); while (!feof(f)) { fputc(fgetc(f), stdout); } fclose(f); exit(2); } + + // Close the FILE fclose(f); } @@ -67,11 +78,14 @@ int main(void) printf("Employees sorted by idnum are: "); vector_employee_out_str(stdout, emps); + // Sort the database by employee name M_LET( (cmp, STRING_CTE("name")), compare_by_t ) vector_employee_sort_fo(emps, compare_by_as_interface(cmp)); printf("\nEmployees sorted by name are: "); vector_employee_out_str(stdout, emps); printf("\n"); + + // End } return 0; }