Design Pattern Examples
Overview of object-oriented design patterns
mapofint.c
Go to the documentation of this file.
1
5
6#include <memory.h>
7#include <stdbool.h>
8#include <stdlib.h>
9#include <string.h>
10
11#include "mapofint.h"
12
14// MapOfInt_Initialize()
17{
18 if (map != NULL)
19 {
20 map->entries = NULL;
21 map->entries_count = 0;
22 }
23}
24
26// MapOfInt_Clear()
29{
30 if (map != NULL)
31 {
32 free(map->entries);
34 }
35}
36
38// MapOfInt_Add()
40bool MapOfInt_Add(MapOfInt* map, const char* key, int value)
41{
42 bool success = false;
43
44 if (map != NULL && key != NULL)
45 {
46 MapOfIntEntry* new_list;
47 if (map->entries == NULL)
48 {
49 new_list = calloc(1, sizeof(MapOfIntEntry));
50 }
51 else
52 {
53 size_t new_count = map->entries_count + 1;
54 size_t new_size = new_count * sizeof(MapOfIntEntry);
55 new_list = realloc(map->entries, new_size);
56 }
57 if (new_list != NULL)
58 {
59 map->entries = new_list;
60 map->entries[map->entries_count].key = key;
61 map->entries[map->entries_count].value = value;
62 map->entries_count++;
63 success = true;
64 }
65 }
66 return success;
67}
68
70// MapOfInt_Find()
72int MapOfInt_Find(MapOfInt* map, const char* key)
73{
74 int foundIndex = -1;
75
76 if (map != NULL && key != NULL)
77 {
78 for (size_t index = 0; index < map->entries_count; index++)
79 {
80 if (strcmp(map->entries[index].key, key) == 0)
81 {
82 foundIndex = (int)index;
83 break;
84 }
85 }
86 }
87
88 return foundIndex;
89}
void MapOfInt_Clear(MapOfInt *map)
Clear the given MapOfInt object, releasing all memory associated with it. Leaves the object in an ini...
Definition: mapofint.c:28
void MapOfInt_Initialize(MapOfInt *map)
Initialize the given MapOfInt structure so it is ready for use.
Definition: mapofint.c:16
bool MapOfInt_Add(MapOfInt *map, const char *key, int value)
Add a key/value association to the given MapOfInt object. The MapOfInt object takes ownership of the ...
Definition: mapofint.c:40
int MapOfInt_Find(MapOfInt *map, const char *key)
Find the specified key in the given MapOfInt object, returning an index into the object.
Definition: mapofint.c:72
Declaration of the MapOfInt structure and supporting functions for managing a map of integers keyed b...
Represents an association between a string and an integer.
Definition: mapofint.h:16
int value
The integer value.
Definition: mapofint.h:18
const char * key
Key associated with this integer. Borrowed pointer.
Definition: mapofint.h:17
Represents a list of MapOfIntEntry objects that maps a string to an integer value....
Definition: mapofint.h:27
size_t entries_count
Definition: mapofint.h:29
MapOfIntEntry * entries
Definition: mapofint.h:28