aboutsummaryrefslogtreecommitdiff
path: root/src/streams.h
diff options
context:
space:
mode:
authorLarry Ruane <larryruane@gmail.com>2020-08-10 15:23:03 -0600
committerLarry Ruane <larryruane@gmail.com>2023-05-05 06:03:17 -0600
commit72efc26439da9a1344a19569fb0cab01f82ae7d1 (patch)
treecbd3224cf41567a97866a3213c2441e794cc27c2 /src/streams.h
parent604df63f6c70b9692b067777ddb38d946ac0b2fc (diff)
downloadbitcoin-72efc26439da9a1344a19569fb0cab01f82ae7d1.tar.xz
util: improve streams.h:FindByte() performance
Avoid use of the expensive mod operator (%) when calculating the buffer offset. No functional difference. Co-authored-by: Hennadii Stepanov <32963518+hebasto@users.noreply.github.com>
Diffstat (limited to 'src/streams.h')
-rw-r--r--src/streams.h20
1 files changed, 15 insertions, 5 deletions
diff --git a/src/streams.h b/src/streams.h
index 8788343809..e346aa0a3f 100644
--- a/src/streams.h
+++ b/src/streams.h
@@ -756,15 +756,25 @@ public:
}
//! search for a given byte in the stream, and remain positioned on it
- void FindByte(uint8_t ch)
+ void FindByte(std::byte byte)
{
+ // For best performance, avoid mod operation within the loop.
+ size_t buf_offset{size_t(m_read_pos % uint64_t(vchBuf.size()))};
while (true) {
- if (m_read_pos == nSrcPos)
+ if (m_read_pos == nSrcPos) {
+ // No more bytes available; read from the file into the buffer,
+ // setting nSrcPos to one beyond the end of the new data.
+ // Throws exception if end-of-file reached.
Fill();
- if (vchBuf[m_read_pos % vchBuf.size()] == std::byte{ch}) {
- break;
}
- m_read_pos++;
+ const size_t len{std::min<size_t>(vchBuf.size() - buf_offset, nSrcPos - m_read_pos)};
+ const auto it_start{vchBuf.begin() + buf_offset};
+ const auto it_find{std::find(it_start, it_start + len, byte)};
+ const size_t inc{size_t(std::distance(it_start, it_find))};
+ m_read_pos += inc;
+ if (inc < len) break;
+ buf_offset += inc;
+ if (buf_offset >= vchBuf.size()) buf_offset = 0;
}
}
};