source: trunk/src/dict.cpp @ 259

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

Slightly change the ...Data initialisation in classes.

  • Property svn:keywords set to Id
File size: 2.3 KB
Line 
1//
2// Lol Engine
3//
4// Copyright: (c) 2010-2011 Sam Hocevar <sam@hocevar.net>
5//   This program is free software; you can redistribute it and/or
6//   modify it under the terms of the Do What The Fuck You Want To
7//   Public License, Version 2, as published by Sam Hocevar. See
8//   http://sam.zoy.org/projects/COPYING.WTFPL for more details.
9//
10
11#if defined HAVE_CONFIG_H
12#   include "config.h"
13#endif
14
15#include <cstring>
16#include <cstdio>
17#include <cstdlib>
18
19#include "core.h"
20
21#if defined WIN32
22#   define strcasecmp _stricmp
23#endif
24
25/*
26 * Dict implementation class
27 */
28
29class DictData
30{
31    friend class Dict;
32
33public:
34    DictData() :
35        entities(0),
36        nentities(0)
37    {
38        /* Nothing to do */
39    }
40
41    ~DictData()
42    {
43#if !FINAL_RELEASE
44        if (nentities)
45            fprintf(stderr, "ERROR: still %i entities in dict\n", nentities);
46#endif
47        free(entities);
48    }
49
50private:
51    Entity **entities;
52    int nentities;
53};
54
55/*
56 * Public Dict class
57 */
58
59Dict::Dict()
60  : data(new DictData())
61{
62}
63
64Dict::~Dict()
65{
66    delete data;
67}
68
69int Dict::MakeSlot(char const *name)
70{
71    int id, empty = -1;
72
73    /* If the entry is already registered, remember its ID. Look for an
74     * empty slot at the same time. */
75    for (id = 0; id < data->nentities; id++)
76    {
77        Entity *e = data->entities[id];
78        if (!e)
79            empty = id;
80        else if (!strcasecmp(name, e->GetName()))
81            break;
82    }
83
84    /* If this is a new entry, create a new slot for it. */
85    if (id == data->nentities)
86    {
87        if (empty == -1)
88        {
89            empty = data->nentities++;
90            data->entities = (Entity **)realloc(data->entities,
91                                           data->nentities * sizeof(Entity *));
92        }
93
94        data->entities[empty] = NULL;
95        id = empty;
96    }
97    else
98    {
99        Ticker::Ref(data->entities[id]);
100    }
101
102    return id;
103}
104
105void Dict::RemoveSlot(int id)
106{
107    if (Ticker::Unref(data->entities[id]) == 0)
108    {
109        data->entities[id] = NULL;
110        if (data->nentities)
111            data->nentities--;
112#if !FINAL_RELEASE
113        else
114            fprintf(stderr, "ERROR: removing entity from empty dict\n");
115#endif
116    }
117}
118
119
120void Dict::SetEntity(int id, Entity *entity)
121{
122    Ticker::Ref(entity);
123    data->entities[id] = entity;
124}
125
126Entity *Dict::GetEntity(int id)
127{
128    return data->entities[id];
129}
130
Note: See TracBrowser for help on using the repository browser.