1 // Copyright 2017 Google
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 #import "Private/GULMutableDictionary.h"
17 @implementation GULMutableDictionary {
18 /// The mutable dictionary.
19 NSMutableDictionary *_objects;
21 /// Serial synchronization queue. All reads should use dispatch_sync, while writes use
23 dispatch_queue_t _queue;
26 - (instancetype)init {
30 _objects = [[NSMutableDictionary alloc] init];
31 _queue = dispatch_queue_create("GULMutableDictionary", DISPATCH_QUEUE_SERIAL);
37 - (NSString *)description {
38 __block NSString *description;
39 dispatch_sync(_queue, ^{
40 description = self->_objects.description;
45 - (id)objectForKey:(id)key {
47 dispatch_sync(_queue, ^{
48 object = self->_objects[key];
53 - (void)setObject:(id)object forKey:(id<NSCopying>)key {
54 dispatch_async(_queue, ^{
55 self->_objects[key] = object;
59 - (void)removeObjectForKey:(id)key {
60 dispatch_async(_queue, ^{
61 [self->_objects removeObjectForKey:key];
65 - (void)removeAllObjects {
66 dispatch_async(_queue, ^{
67 [self->_objects removeAllObjects];
72 __block NSUInteger count;
73 dispatch_sync(_queue, ^{
74 count = self->_objects.count;
79 - (id)objectForKeyedSubscript:(id<NSCopying>)key {
80 // The method this calls is already synchronized.
81 return [self objectForKey:key];
84 - (void)setObject:(id)obj forKeyedSubscript:(id<NSCopying>)key {
85 // The method this calls is already synchronized.
86 [self setObject:obj forKey:key];
89 - (NSDictionary *)dictionary {
90 __block NSDictionary *dictionary;
91 dispatch_sync(_queue, ^{
92 dictionary = [self->_objects copy];