summaryrefslogtreecommitdiff
path: root/SmartDeviceLink/SDLMutableDataQueue.m
blob: a2a98f494b6136da949a182d1e97ebe0067b2fe8 (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
70
71
72
73
74
75
//
//  SDLMutableDataQueue.m
//
//
//  Created by David Switzer on 3/2/17.
//
//

#import "SDLMutableDataQueue.h"

NS_ASSUME_NONNULL_BEGIN

@interface SDLMutableDataQueue ()

@property (nonatomic, strong) NSMutableArray *elements;
@property (nonatomic, assign, readwrite) BOOL frontDequeued;

@end

@implementation SDLMutableDataQueue

- (instancetype)init {
    self = [super init];
    if (!self) {
        return nil;
    }

    _elements = [NSMutableArray array];

    return self;
}

- (void)enqueueBuffer:(NSMutableData *)data {
    // Since this method is being called from the main thread and the dequeue methods are being called from the data session stream thread, we need to put critical sections around the queue members. Use the @synchronized object level lock to do this.
    @synchronized(self) {
        [self.elements addObject:data];
        self.frontDequeued = NO;
    }
}

- (NSMutableData *_Nullable)frontBuffer {
    NSMutableData *dataAtFront = nil;

    @synchronized(self) {
        if (self.elements.count) {
            // The front of the queue is always at index 0
            dataAtFront = self.elements[0];
            self.frontDequeued = YES;
        }
    }

    return dataAtFront;
}

- (void)popBuffer {
    @synchronized(self) {
        [self.elements removeObjectAtIndex:0];
    }
}

- (void)removeAllObjects {
    @synchronized(self) {
        [self.elements removeAllObjects];
    }
}

- (NSUInteger)count {
    @synchronized(self) {
        return self.elements.count;
    }
}

NS_ASSUME_NONNULL_END

@end