| 60 | } |
| 61 | |
| 62 | std::unique_ptr<PacketLock> PacketReadCache::lock( uint64_t packetLogicalOffset, char *&pkt ) |
| 63 | { |
| 64 | #ifdef E57_VERBOSE |
| 65 | std::cout << "PacketReadCache::lock() called, packetLogicalOffset=" << packetLogicalOffset |
| 66 | << std::endl; |
| 67 | #endif |
| 68 | |
| 69 | // Only allow one locked packet at a time. |
| 70 | if ( lockCount_ > 0 ) |
| 71 | { |
| 72 | throw E57_EXCEPTION2( ErrorInternal, "lockCount=" + toString( lockCount_ ) ); |
| 73 | } |
| 74 | |
| 75 | // Offset can't be 0 |
| 76 | if ( packetLogicalOffset == 0 ) |
| 77 | { |
| 78 | throw E57_EXCEPTION2( ErrorInternal, |
| 79 | "packetLogicalOffset=" + toString( packetLogicalOffset ) ); |
| 80 | } |
| 81 | |
| 82 | // Linear scan for matching packet offset in cache |
| 83 | for ( unsigned i = 0; i < entries_.size(); ++i ) |
| 84 | { |
| 85 | auto &entry = entries_[i]; |
| 86 | |
| 87 | if ( packetLogicalOffset == entry.logicalOffset_ ) |
| 88 | { |
| 89 | // Found a match, so don't have to read anything |
| 90 | #ifdef E57_VERBOSE |
| 91 | std::cout << " Found matching cache entry, index=" << i << std::endl; |
| 92 | #endif |
| 93 | // Mark entry with current useCount (keeps track of age of entry). |
| 94 | entry.lastUsed_ = ++useCount_; |
| 95 | |
| 96 | // Publish buffer address to caller |
| 97 | pkt = entry.buffer_; |
| 98 | |
| 99 | // Create lock so we are sure that we will be unlocked when use is finished. |
| 100 | std::unique_ptr<PacketLock> plock( new PacketLock( this, i ) ); |
| 101 | |
| 102 | // Increment cache lock just before return |
| 103 | ++lockCount_; |
| 104 | |
| 105 | return plock; |
| 106 | } |
| 107 | } |
| 108 | // Get here if didn't find a match already in cache. |
| 109 | |
| 110 | // Find least recently used (LRU) packet buffer |
| 111 | unsigned oldestEntry = 0; |
| 112 | unsigned oldestUsed = entries_.at( 0 ).lastUsed_; |
| 113 | |
| 114 | for ( unsigned i = 0; i < entries_.size(); ++i ) |
| 115 | { |
| 116 | const auto &entry = entries_[i]; |
| 117 | |
| 118 | if ( entry.lastUsed_ < oldestUsed ) |
| 119 | { |
no test coverage detected