Oolite
Loading...
Searching...
No Matches
OOShipGroup.m
Go to the documentation of this file.
1/*
2OOShipGroup.m
3
4IMPLEMENTATION NOTE:
5This is implemented as a dynamic array rather than a hash table for the
6following reasons:
7 * Ship groups are generally quite small, not motivating a more complex
8 implementation.
9 * The code ship groups replace was all array-based and not a significant
10 bottleneck.
11 * Ship groups are compacted (i.e., dead weak references removed) as a side
12 effect of iteration.
13 * Many uses of ship groups involve iterating over the whole group anyway.
14
15
16Oolite
17Copyright (C) 2004-2013 Giles C Williams and contributors
18
19This program is free software; you can redistribute it and/or
20modify it under the terms of the GNU General Public License
21as published by the Free Software Foundation; either version 2
22of the License, or (at your option) any later version.
23
24This program is distributed in the hope that it will be useful,
25but WITHOUT ANY WARRANTY; without even the implied warranty of
26MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27GNU General Public License for more details.
28
29You should have received a copy of the GNU General Public License
30along with this program; if not, write to the Free Software
31Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
32MA 02110-1301, USA.
33
34*/
35
36#import "OOShipGroup.h"
37#import "OOMaths.h"
38#import "ShipEntity.h"
39
40enum {
43};
44
45@interface OOShipGroupEnumerator : NSEnumerator {
46 // ivars are public so ShipGroupIterate() can peek at both these and OOShipGroup's. Naughty!
47@public
49 NSUInteger _index, _updateCount;
51}
52
53- (id)initWithShipGroup:(OOShipGroup*)group;
54
55- (NSUInteger)index;
56- (void)setPerformCleanup:(BOOL)flag;
57
58@end
59
60@interface OOShipGroup (Private)
61
62- (BOOL)resizeTo:(NSUInteger)newCapacity;
63- (void)cleanUp;
64
65- (NSUInteger)updateCount;
66
67@end
68
70
71@implementation OOShipGroup
72
73- (id)init
74{
75 return [self initWithName:nil];
76}
77
78- (id)initWithName:(NSString*)name
79{
80 if ((self = [super init])) {
82 _members = malloc(sizeof *_members * _capacity);
83 if (_members == NULL) {
84 [self release];
85 return nil;
86 }
87
88 [self setName:name];
89 }
90
91 return self;
92}
93
94+ (instancetype)groupWithName:(NSString*)name
95{
96 return [[[self alloc] initWithName:name] autorelease];
97}
98
99+ (instancetype)groupWithName:(NSString*)name leader:(ShipEntity*)leader
100{
101 OOShipGroup* result = [self groupWithName:name];
102 [result setLeader:leader];
103 return result;
104}
105
106- (void)dealloc
107{
108 NSUInteger i;
109
110 for (i = 0; i < _count; i++) {
111 [_members[i] release];
112 }
113 free(_members);
114 [_name release];
115
116 [super dealloc];
117}
118
120{
121 NSString* desc = [NSString stringWithFormat:@"%zu ships", _count];
122 if ([self name] != nil) {
123 desc = [NSString stringWithFormat:@"\"%@\", %@", [self name], desc];
124 }
125 if ([self leader] != nil) {
126 desc = [NSString stringWithFormat:@"%@, leader: %@", desc, [[self leader] shortDescription]];
127 }
128 return desc;
129}
130
131- (NSString*)name
132{
133 return _name;
134}
135
136- (void)setName:(NSString*)name
137{
138 _updateCount++;
139
140 if (_name != name) {
141 [_name release];
142 _name = [name retain];
143 }
144}
145
147{
149
150 // If reference is stale, delete weakref object.
151 if (result == nil && _leader != nil) {
152 [_leader release];
153 _leader = nil;
154 }
155
156 return result;
157}
158
159- (void)setLeader:(ShipEntity*)leader
160{
161 _updateCount++;
162
163 if (leader != [self leader]) {
164 [_leader release];
165 [self addShip:leader];
167 }
168}
169
170- (NSEnumerator*)objectEnumerator
171{
172 return [[[OOShipGroupEnumerator alloc] initWithShipGroup:self] autorelease];
173}
174
176{
177 return [[self memberArray] objectEnumerator];
178}
179
180- (NSSet*)members
181{
182 return [NSSet setWithArray:[self memberArray]];
183}
184
186{
187 return [NSSet setWithArray:[self memberArrayExcludingLeader]];
188}
189
190- (NSArray*)memberArray
191{
192 id* objects = NULL;
193 NSUInteger count = 0;
194 NSArray* result = nil;
195
196 if (_count == 0)
197 return [NSArray array];
198
199 objects = malloc(sizeof *objects * _count);
200 for (id ship in self) {
201 objects[count++] = ship;
202 }
203
204 result = [NSArray arrayWithObjects:objects count:count];
205 free(objects);
206
207 return result;
208}
209
211{
212 id* objects = NULL;
213 NSUInteger count = 0;
214 NSArray* result = nil;
216
217 if (_count == 0)
218 return [NSArray array];
219 leader = self.leader;
220
221 objects = malloc(sizeof *objects * _count);
222 for (id ship in self) {
223 if (ship != leader) {
224 objects[count++] = ship;
225 }
226 }
227
228 result = [NSArray arrayWithObjects:objects count:count];
229 free(objects);
230
231 return result;
232}
233
234- (BOOL)containsShip:(ShipEntity*)ship
235{
236 ShipEntity* containedShip = nil;
237
238 for (containedShip in self) {
239 if ([ship isEqual:containedShip]) {
240 return YES;
241 }
242 }
243
244 return NO;
245}
246
247- (BOOL)addShip:(ShipEntity*)ship
248{
249 _updateCount++;
250
251 if ([self containsShip:ship])
252 return YES; // it's in the group already, result!
253
254 // Ensure there's space.
255 if (_count == _capacity) {
256 if (![self resizeTo:(_capacity > kMaxFreeSpace) ? (_capacity + kMaxFreeSpace) : (_capacity * 2)]) {
257 if (![self resizeTo:_capacity + 1]) {
258 // Out of memory?
259 return NO;
260 }
261 }
262 }
263
264 _members[_count++] = [ship weakRetain];
265 return YES;
266}
267
268- (BOOL)removeShip:(ShipEntity*)ship
269{
270 OOShipGroupEnumerator* shipEnum = nil;
271 ShipEntity* containedShip = nil;
272 NSUInteger index;
273 BOOL foundIt = NO;
274
275 _updateCount++;
276
277 if (ship == [self leader])
278 [self setLeader:nil];
279
280 shipEnum = (OOShipGroupEnumerator*)[self objectEnumerator];
282 while ((containedShip = [shipEnum nextObject])) {
283 if ([ship isEqual:containedShip]) {
284 index = [shipEnum index] - 1;
285 _members[index] = _members[--_count];
286 foundIt = YES;
287
288 // Clean up
289 [ship setGroup:nil];
290 [ship setOwner:ship];
291 [self cleanUp];
292 break;
293 }
294 }
295 return foundIt;
296}
297
298/* TODO post-1.78: profiling indicates this is a noticeable
299 * contributor to ShipEntity::update time. Consider optimisation: may
300 * be possible to return _count if invalidation of weakref and group
301 * removal in ShipEntity::dealloc keeps the data consistent anyway -
302 * CIM */
303
304- (NSUInteger)count
305{
306 NSEnumerator* memberEnum = nil;
307 NSUInteger result = 0;
308
309 if (_count != 0) {
310 memberEnum = [self objectEnumerator];
311 while ([memberEnum nextObject] != nil)
312 result++;
313 }
314
315 assert(result == _count);
316
317 return result;
318}
319
320- (BOOL)isEmpty
321{
322 if (_count == 0)
323 return YES;
324
325 return [[self objectEnumerator] nextObject] == nil;
326}
327
328- (BOOL)resizeTo:(NSUInteger)newCapacity
329{
330 OOWeakReference** temp = NULL;
331
332 if (newCapacity < _count)
333 return NO;
334
335 temp = realloc(_members, newCapacity * sizeof *_members);
336 if (temp == NULL)
337 return NO;
338
339 _members = temp;
340 _capacity = newCapacity;
341 return YES;
342}
343
344- (void)cleanUp
345{
346 NSUInteger newCapacity = _capacity;
347
348 if (_count >= kMaxFreeSpace) {
349 if (_capacity > _count + kMaxFreeSpace) {
350 newCapacity = _count + 1; // +1 keeps us at powers of two + multiples of kMaxFreespace.
351 }
352 } else {
353 if (_capacity > _count * 2) {
354 newCapacity = OORoundUpToPowerOf2_NS(_count);
355 if (newCapacity < kMinSize)
356 newCapacity = kMinSize;
357 }
358 }
359
360 if (newCapacity != _capacity)
361 [self resizeTo:newCapacity];
362}
363
364- (NSUInteger)updateCount
365{
366 return _updateCount;
367}
368
370{
371 // The work is done here so that we can have access to both OOShipGroup's and OOShipGroupEnumerator's ivars.
372
373 OOShipGroup* group = enumerator->_group;
374 ShipEntity* result = nil;
375 BOOL cleanupNeeded = NO;
376
377 if (enumerator->_updateCount != group->_updateCount) {
378 [NSException raise:NSGenericException format:@"Collection <OOShipGroup: %p> was mutated while being enumerated.", group];
379 }
380
381 while (enumerator->_index < group->_count) {
382 result = [group->_members[enumerator->_index] weakRefUnderlyingObject];
383 if (result != nil) {
384 enumerator->_index++;
385 break;
386 }
387
388 // If we got here, the group contains a stale reference to a dead ship.
389 group->_members[enumerator->_index] = group->_members[--group->_count];
390 cleanupNeeded = YES;
391 }
392
393 // Clean-up handling. Only perform actual clean-up at end of iteration.
394 if (enumerator->_considerCleanup) {
395 enumerator->_cleanupNeeded = enumerator->_cleanupNeeded && cleanupNeeded;
396 if (enumerator->_cleanupNeeded && result == nil) {
397 [group cleanUp];
398 }
399 }
400
401 return result;
402}
403
404- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState*)state objects:(id*)stackbuf count:(NSUInteger)len
405{
406 NSUInteger srcIndex, dstIndex = 0;
407 ShipEntity* item = nil;
408 BOOL cleanupNeeded = NO;
409
410 srcIndex = state->state;
411 while (srcIndex < _count && dstIndex < len) {
413 if (item != nil) {
414 stackbuf[dstIndex++] = item;
415 srcIndex++;
416 } else {
417 _members[srcIndex] = _members[--_count];
418 cleanupNeeded = YES;
419 }
420 }
421
422 if (cleanupNeeded)
423 [self cleanUp];
424
425 state->state = srcIndex;
426 state->itemsPtr = stackbuf;
427 state->mutationsPtr = &_updateCount;
428
429 return dstIndex;
430}
431
432/* This method exists purely to suppress Clang static analyzer warnings that
433 this ivar is unused (but may be used by categories, which they are).
434 FIXME: there must be a feature macro we can use to avoid actually building
435 this into the app, but I can't find it in docs.
436*/
438{
439#if OOJS_QUICKJS
440 return !JS_IsObject(_jsSelf);
441#else
442 return !_jsSelf;
443#endif
444}
445
446@end
447
448@implementation OOShipGroupEnumerator
449
450- (id)initWithShipGroup:(OOShipGroup*)group
451{
452 assert(group != nil);
453
454 if ((self = [super init])) {
455 _group = [group retain];
456 _considerCleanup = YES;
458 }
459
460 return self;
461}
462
463- (void)dealloc
464{
466
467 [super dealloc];
468}
469
471{
472 return ShipGroupIterate(self);
473}
474
475- (NSUInteger)index
476{
477 return _index;
478}
479
480- (void)setPerformCleanup:(BOOL)flag
481{
482 _considerCleanup = flag;
483}
484
485@end
#define DESTROY(x)
return nil
@ kMaxFreeSpace
Definition OOShipGroup.m:42
@ kMinSize
Definition OOShipGroup.m:41
static id ShipGroupIterate(OOShipGroupEnumerator *enumerator)
NSUInteger updateCount()
NSUInteger _updateCount
Definition OOShipGroup.m:49
void setPerformCleanup:(BOOL flag)
OOShipGroup * _group
Definition OOShipGroup.m:48
void setName:(NSString *name)
NSString * _name
Definition OOShipGroup.h:42
BOOL addShip:(ShipEntity *ship)
OOWeakReference ** _members
Definition OOShipGroup.h:40
id initWithName:(NSString *name)
Definition OOShipGroup.m:78
void setLeader:(ShipEntity *leader)
NSUInteger count()
NSEnumerator * mutationSafeEnumerator()
instancetype groupWithName:(NSString *name)
Definition OOShipGroup.m:94
NSSet * members()
BOOL resizeTo:(NSUInteger newCapacity)
NSEnumerator * objectEnumerator()
BOOL suppressClangStuff()
NSString * descriptionComponents()
NSArray * memberArrayExcludingLeader()
unsigned long _updateCount
Definition OOShipGroup.h:39
NSString * name()
NSUInteger _count
Definition OOShipGroup.h:38
struct JSObject * _jsSelf
Definition OOShipGroup.h:47
static id ShipGroupIterate(OOShipGroupEnumerator *enumerator)
NSSet * membersExcludingLeader()
OOWeakReference * _leader
Definition OOShipGroup.h:41
NSUInteger _capacity
Definition OOShipGroup.h:38
ShipEntity * leader()
NSUInteger updateCount()
NSArray * memberArray()
void setGroup:(OOShipGroup *group)
void setOwner:(Entity *who_owns_entity)