source: trunk/src/dict.cpp @ 153

Last change on this file since 153 was 153, checked in by sam, 9 years ago

Factor Forge and Tiler using the new Dict class.

  • Property svn:keywords set to Id
File size: 1.8 KB
Line 
1//
2// Deus Hax (working title)
3// Copyright (c) 2010 Sam Hocevar <sam@hocevar.net>
4//
5
6#if defined HAVE_CONFIG_H
7#   include "config.h"
8#endif
9
10#include <cstring>
11#include <cstdio>
12#include <cstdlib>
13
14#include "core.h"
15
16/*
17 * Dict implementation class
18 */
19
20class DictData
21{
22    friend class Dict;
23
24public:
25    DictData() :
26        entities(0),
27        nentities(0)
28    {
29        /* Nothing to do */
30    }
31
32    ~DictData()
33    {
34        if (nentities)
35            fprintf(stderr, "ERROR: still %i entities in dict\n", nentities);
36        free(entities);
37    }
38
39private:
40    Entity **entities;
41    int nentities;
42};
43
44/*
45 * Public Dict class
46 */
47
48Dict::Dict()
49{
50    data = new DictData();
51}
52
53Dict::~Dict()
54{
55    delete data;
56}
57
58int Dict::MakeSlot(char const *name)
59{
60    int id, empty = -1;
61
62    /* If the entry is already registered, remember its ID. Look for an
63     * empty slot at the same time. */
64    for (id = 0; id < data->nentities; id++)
65    {
66        Entity *e = data->entities[id];
67        if (!e)
68            empty = id;
69        else if (!strcasecmp(name, e->GetName()))
70            break;
71    }
72
73    /* If this is a new entry, create a new slot for it. */
74    if (id == data->nentities)
75    {
76        if (empty == -1)
77        {
78            empty = data->nentities++;
79            data->entities = (Entity **)realloc(data->entities,
80                                           data->nentities * sizeof(Entity *));
81        }
82
83        data->entities[empty] = NULL;
84        id = empty;
85    }
86    else
87    {
88        data->entities[id]->Ref();
89    }
90
91    return id;
92}
93
94void Dict::RemoveSlot(int id)
95{
96    if (data->entities[id]->Unref() == 0)
97        data->entities[id] = NULL;
98}
99
100
101void Dict::SetEntity(int id, Entity *entity)
102{
103    entity->Ref();
104    data->entities[id] = entity;
105}
106
107Entity *Dict::GetEntity(int id)
108{
109    return data->entities[id];
110}
111
Note: See TracBrowser for help on using the repository browser.