summaryrefslogtreecommitdiff
path: root/SmartDeviceLink/SDLPrioritizedObjectCollection.m
blob: b28a99ca78e2b5a648d3a058c2cf60aa448ad192 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//
//  SDLPrioritizedOutputCollection.m
//  SmartDeviceLink
//

#import "SDLPrioritizedObjectCollection.h"
#import "SDLObjectWithPriority.h"

NS_ASSUME_NONNULL_BEGIN

@interface SDLPrioritizedObjectCollection () {
    NSMutableArray<id> *privateArray;
}
@end


@implementation SDLPrioritizedObjectCollection

- (instancetype)init {
    self = [super init];
    if (self) {
        privateArray = [NSMutableArray<id> new];
    }
    return self;
}

- (void)addObject:(nullable id)object withPriority:(NSInteger)priority {
    if (object == nil || [[NSNull null] isEqual:object]) {
        return;
    }

    SDLObjectWithPriority *newWrapper = [SDLObjectWithPriority objectWithObject:object priority:priority];

    @synchronized(privateArray) {
        // Find correct place to insert.
        // Sorted in descending order.
        BOOL lowerPriorityFound = NO;
        NSUInteger currentCount = privateArray.count;
        for (NSUInteger x = 0; x < currentCount; x++) {
            SDLObjectWithPriority *o = privateArray[x];
            if (o.priority <= priority) {
                lowerPriorityFound = YES;
                [privateArray insertObject:newWrapper atIndex:x];
                break;
            }
        }
        if (!lowerPriorityFound) {
            [privateArray addObject:newWrapper];
        }
    }
}

- (nullable instancetype)nextObject {
    if (privateArray.count == 0) {
        return nil;
    }

    SDLObjectWithPriority *obj = nil;
    @synchronized(privateArray) {
        obj = (SDLObjectWithPriority *)[privateArray lastObject];
        [privateArray removeLastObject];
    }

    return obj.object;
}

@end

NS_ASSUME_NONNULL_END