Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <assert.h>
- #include <stdlib.h>
- #include <string.h>
- #define GRAPH_DEFAULT_CAPACITY 10
- typedef struct {
- const char* city_name;
- GraphNode* edges;
- } GraphNode;
- typedef struct {
- GraphNode* other_node;
- GraphNode* sibling_edge;
- } GraphEdge;
- typedef struct {
- enum {GRAPH_NULL=0, GRAPH_NODE, GRAPH_EDGE} type;
- union {
- GraphNode* node;
- GraphEdge* edge;
- void* data_ptr;
- };
- } GraphObject;
- typedef struct {
- GraphObject* gc_objects;
- size_t gc_obj_capacity;
- size_t gc_obj_count;
- } Graph;
- void graph_gc_reserve_more_objects(Graph* graph) {
- GraphObject* new_storage = malloc(sizeof(GraphObject) * graph->gc_obj_capacity * 2);
- memset(new_storage, 0, sizeof(graph->gc_obj_capacity * 2));
- memcpy(new_storage, graph->gc_objects, graph->gc_obj_capacity);
- free(graph->gc_objects);
- graph->gc_objects = new_storage;
- graph->gc_obj_capacity *= 2;
- }
- void graph_gc_register_object(Graph* graph, GraphObject* object) {
- if(graph->gc_obj_capacity == graph->gc_obj_count) {
- graph_gc_reserve_more_objects(graph);
- }
- memcpy(&graph->gc_objects[graph->gc_obj_count], object, sizeof(*object));
- graph->gc_obj_count++;
- }
- void graph_edge_new(Graph* graph, GraphNode* source, GraphNode* destination) {
- assert(source != destination);
- GraphObject new_obj;
- memset(&new_obj, 0, sizeof(new_obj));
- new_obj.type = GRAPH_EDGE;
- new_obj.edge = malloc(sizeof(GraphEdge));
- new_obj.edge->other_node = destination;
- new_obj.edge->sibling_edge = source->edges;
- graph_gc_register_object(graph, &new_obj);
- source->edges = new_obj.edge;
- }
- GraphNode* graph_node_new(Graph* graph, const char* city_name) {
- GraphObject new_obj;
- memset(&new_obj, 0, sizeof(new_obj));
- GraphNode* node = malloc(sizeof(GraphNode));
- memset(node, 0, sizeof(*node));
- new_obj.type = GRAPH_NODE;
- new_obj.node = node;
- graph_gc_register_object(graph, &new_obj);
- node->city_name = city_name;
- return node;
- }
- void graph_destroy(Graph* graph) {
- for(size_t i = 0; i < graph->gc_obj_count; i++) {
- free(graph->gc_objects[i].data_ptr);
- }
- free(graph->gc_objects);
- free(graph);
- }
- Graph* graph_new() {
- Graph *graph = malloc(sizeof(Graph));
- memset(graph, 0, sizeof(*graph));
- graph->gc_objects = malloc(sizeof(GraphObject)*GRAPH_DEFAULT_CAPACITY);
- return graph;
- }
- int main(int argc, char** argv) {
- Graph* graph = graph_new();
- GraphNode* node_a = graph_node_new(graph, "London");
- GraphNode* node_b = graph_node_new(graph, "Birmingham");
- GraphEdge* edge0 = graph_edge_new(graph, node_a, node_b);
- graph_destroy(graph);
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement