Objectively 1.0.0
Ultra-lightweight object oriented framework for GNU C.
Functions
Enum.c File Reference
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "Enum.h"
#include "MutableString.h"

Go to the source code of this file.

Functions

Stringnameof (const EnumName *names, int value)
 Marshal value, returning a String of OR'ed EnumNames for the given enum value. More...
 
int valueof (const EnumName *names, const char *chars)
 Parse string, returning the corresponding enum value. More...
 

Function Documentation

◆ nameof()

String * nameof ( const EnumName names,
int  value 
)

Marshal value, returning a String of OR'ed EnumNames for the given enum value.

Parameters
namesA null-terminated array of EnumNames.
valueThe enum value, which may be a bitwise OR of multiple enum values.
Returns
A String of EnumNames matching value, or NULL.

Definition at line 31 of file Enum.c.

31 {
32
33 for (const EnumName *name = names; name->name; name++) {
34 if (name->value == value) {
35 return $$(String, stringWithCharacters, name->name);
36 }
37 }
38
39 MutableString *string = NULL;
40
41 for (const EnumName *name = names; name->name; name++) {
42 if (name->value) {
43 if ((name->value & value) == name->value) {
44 if (string == NULL) {
45 string = $$(MutableString, string);
46 } else {
47 $(string, appendCharacters, " | ");
48 }
49 $(string, appendCharacters, name->name);
50 }
51 }
52 }
53
54 return (String *) string;
55}
The EnumName type.
Definition: Enum.h:37
const char * name
Definition: Enum.h:38
Mutable UTF-8 strings.
Definition: MutableString.h:40
MutableString * string(void)
Returns a new MutableString.
void appendCharacters(MutableString *self, const char *chars)
Appends the specified UTF-8 encoded C string.
Definition: MutableString.c:54
Immutable UTF-8 strings.
Definition: String.h:69
String * stringWithCharacters(const char *chars)
Returns a new String by copying chars.
Definition: String.c:487

◆ valueof()

int valueof ( const EnumName names,
const char *  chars 
)

Parse string, returning the corresponding enum value.

Parameters
namesA null-terminated array of EnumNames.
charsA null-terminated C string.
Returns
The value of the EnumName matching string, or -1.

Definition at line 57 of file Enum.c.

57 {
58
59 int value = 0;
60
61 const char *c = chars;
62 while (*c) {
63 const size_t size = strcspn(c, " |");
64 if (size) {
65 const EnumName *en;
66 for (en = names; en->name; en++) {
67 if (strncmp(en->name, c, size) == 0) {
68 value |= en->value;
69 break;
70 }
71 if (en->alias && strncmp(en->alias, c, size) == 0) {
72 value |= en->value;
73 break;
74 }
75 }
76 if (en->name == NULL) {
77 fprintf(stderr, "%s: Unknown character sequence: %s\n", __func__, c);
78 }
79 }
80 c += size;
81 c += strspn(c, " |");
82 }
83
84 return value;
85}
int value
Definition: Enum.h:40
const char * alias
Definition: Enum.h:39