epoger@google.com | ec3ed6a | 2011-07-28 14:26:00 +0000 | [diff] [blame] | 1 | |
reed@google.com | 3636ed5 | 2011-01-25 23:50:57 +0000 | [diff] [blame] | 2 | /* |
epoger@google.com | ec3ed6a | 2011-07-28 14:26:00 +0000 | [diff] [blame] | 3 | * Copyright 2011 Google Inc. |
| 4 | * |
| 5 | * Use of this source code is governed by a BSD-style license that can be |
| 6 | * found in the LICENSE file. |
reed@google.com | 3636ed5 | 2011-01-25 23:50:57 +0000 | [diff] [blame] | 7 | */ |
| 8 | |
epoger@google.com | ec3ed6a | 2011-07-28 14:26:00 +0000 | [diff] [blame] | 9 | |
reed@google.com | 0e190d0 | 2011-01-25 23:36:05 +0000 | [diff] [blame] | 10 | #include "SkRefDict.h" |
| 11 | #include "SkString.h" |
| 12 | |
| 13 | struct SkRefDict::Impl { |
| 14 | Impl* fNext; |
| 15 | SkString fName; |
| 16 | SkRefCnt* fData; |
| 17 | }; |
| 18 | |
| 19 | SkRefDict::SkRefDict() : fImpl(NULL) {} |
| 20 | |
| 21 | SkRefDict::~SkRefDict() { |
| 22 | this->removeAll(); |
| 23 | } |
| 24 | |
| 25 | SkRefCnt* SkRefDict::find(const char name[]) const { |
| 26 | if (NULL == name) { |
| 27 | return NULL; |
| 28 | } |
| 29 | |
| 30 | Impl* rec = fImpl; |
| 31 | while (rec) { |
| 32 | if (rec->fName.equals(name)) { |
| 33 | return rec->fData; |
| 34 | } |
| 35 | rec = rec->fNext; |
| 36 | } |
| 37 | return NULL; |
| 38 | } |
| 39 | |
| 40 | void SkRefDict::set(const char name[], SkRefCnt* data) { |
| 41 | if (NULL == name) { |
| 42 | return; |
| 43 | } |
| 44 | |
| 45 | Impl* rec = fImpl; |
| 46 | Impl* prev = NULL; |
| 47 | while (rec) { |
| 48 | if (rec->fName.equals(name)) { |
| 49 | if (data) { |
| 50 | // replace |
| 51 | data->ref(); |
| 52 | rec->fData->unref(); |
| 53 | rec->fData = data; |
| 54 | } else { |
| 55 | // remove |
| 56 | rec->fData->unref(); |
| 57 | if (prev) { |
| 58 | prev->fNext = rec->fNext; |
| 59 | } else { |
| 60 | fImpl = rec->fNext; |
| 61 | } |
| 62 | } |
| 63 | return; |
| 64 | } |
| 65 | prev = rec; |
| 66 | rec = rec->fNext; |
| 67 | } |
| 68 | |
| 69 | // if get here, name was not found, so add it |
| 70 | data->ref(); |
| 71 | rec = new Impl; |
| 72 | rec->fName.set(name); |
| 73 | rec->fData = data; |
| 74 | // prepend to the head of our list |
| 75 | rec->fNext = fImpl; |
| 76 | fImpl = rec; |
| 77 | } |
| 78 | |
| 79 | void SkRefDict::removeAll() { |
| 80 | Impl* rec = fImpl; |
| 81 | while (rec) { |
| 82 | Impl* next = rec->fNext; |
| 83 | rec->fData->unref(); |
| 84 | delete rec; |
| 85 | rec = next; |
| 86 | } |
| 87 | fImpl = NULL; |
| 88 | } |
| 89 | |