GetOrCreate gets the cached value if available, otherwise fetches it.
(name string, alignedOffset int64, count int, fetch func() ([]byte, error))
| 48 | |
| 49 | // GetOrCreate gets the cached value if available, otherwise fetches it. |
| 50 | func (c *fileCache) GetOrCreate(name string, alignedOffset int64, count int, fetch func() ([]byte, error)) ([]byte, error) { |
| 51 | key := c.getKey(name, alignedOffset) |
| 52 | val, found := c.fileCache.Get(key) |
| 53 | if !found { |
| 54 | c.lock.Lock() |
| 55 | if val, found = c.fileCache.Get(key); found && val != nil { |
| 56 | c.lock.Unlock() |
| 57 | } else { |
| 58 | var err error |
| 59 | val, err = newItem(key, c.log) |
| 60 | if err != nil { |
| 61 | c.lock.Unlock() |
| 62 | return nil, err |
| 63 | } |
| 64 | ok := c.fileCache.Set(key, val, 0) |
| 65 | if !ok { |
| 66 | c.lock.Unlock() |
| 67 | return nil, io.ErrUnexpectedEOF |
| 68 | } |
| 69 | |
| 70 | // wait for value to pass through buffers |
| 71 | waitForSet() |
| 72 | |
| 73 | c.lock.Unlock() |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | cacheItem := val.(*item) |
| 78 | |
| 79 | cacheItem.lock.RLock() |
| 80 | info, err := cacheItem.file.Stat() |
| 81 | |
| 82 | if err != nil { |
| 83 | cacheItem.lock.RUnlock() |
| 84 | return nil, err |
| 85 | } |
| 86 | |
| 87 | if info.Size() != int64(count) { |
| 88 | cacheItem.lock.RUnlock() |
| 89 | |
| 90 | cacheItem.lock.Lock() |
| 91 | |
| 92 | // check again after acquiring lock |
| 93 | info, err = cacheItem.file.Stat() |
| 94 | if err != nil { |
| 95 | cacheItem.lock.Unlock() |
| 96 | return nil, err |
| 97 | } else if info.Size() != int64(count) { |
| 98 | |
| 99 | n, err := cacheItem.fill(c.log, fetch) |
| 100 | cacheItem.lock.Unlock() |
| 101 | |
| 102 | if err != nil { |
| 103 | return nil, err |
| 104 | } else if int64(n) != int64(count) { |
| 105 | return nil, fmt.Errorf("fill did not retrieve expected number of bytes, expected: %v, got: %v", count, n) |
| 106 | } |
| 107 | } else { |