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