map.c (1873B)
1 // PingPongOS - PingPong Operating System 2 // Prof. Carlos A. Maziero, DINF UFPR 3 // Versão 2.1 -- 07/2026 4 5 // Este arquivo PODE/DEVE ser alterado. 6 7 // Implementação do TAD Mapa de objetos 8 9 #include "map.h" 10 11 #include <stdio.h> 12 #include <stdlib.h> 13 14 struct map_t { 15 int size; 16 void* items[]; 17 }; 18 19 struct map_t* map_create(int size) 20 { 21 struct map_t* map = calloc(1, sizeof(*map) + sizeof(void*) * size); 22 map->size = size; 23 return map; 24 } 25 26 int map_destroy(struct map_t* map) 27 { 28 if (map == NULL) 29 return ERROR; 30 31 free(map); 32 33 return NOERROR; 34 } 35 36 int map_put(struct map_t* map, void* object) 37 { 38 if (map == NULL) 39 return ERROR; 40 41 for (int i = 0; i < map->size; i += 1) { 42 if (map->items[i] == NULL) { 43 map->items[i] = object; 44 return i; 45 } 46 } 47 48 return ERROR; 49 } 50 51 void* map_get(struct map_t* map, int id) 52 { 53 if (map == NULL || id >= map->size) 54 return NULL; 55 return map->items[id]; 56 } 57 58 void* map_del(struct map_t* map, int id) 59 { 60 if (map == NULL || id >= map->size) 61 return NULL; 62 63 void* p = map->items[id]; 64 map->items[id] = NULL; 65 return p; 66 } 67 68 int map_items(struct map_t* map) 69 { 70 if (map == NULL) 71 return ERROR; 72 73 int c = 0; 74 for (int i = 0; i < map->size; i += 1) 75 c += map->items[i] != NULL; 76 77 return c; 78 } 79 80 int map_size(struct map_t* map) 81 { 82 if (map == NULL) 83 return ERROR; 84 return map->size; 85 } 86 87 void map_print(char* name, struct map_t* map) 88 { 89 printf("%s: ", name); 90 if (map == NULL) { 91 printf("undef\n"); 92 return; 93 } 94 printf("[ "); 95 96 int c = 0; 97 for (int i = 0; i < map->size; i += 1) { 98 if (map->items[i] == NULL) { 99 printf("- "); 100 } else { 101 printf("* "); 102 c += 1; 103 } 104 } 105 printf("] (%d/%d)\n", c, map->size); 106 }