diff options
author | MarcoFalke <*~=`'#}+{/-|&$^_@721217.xyz> | 2023-07-05 12:44:12 +0200 |
---|---|---|
committer | MarcoFalke <*~=`'#}+{/-|&$^_@721217.xyz> | 2023-07-13 11:51:07 +0200 |
commit | 000019e158ef01f2bedc3fc1589f95e106e817ea (patch) | |
tree | 073bdd3a2cb43bc6f628d632282b7e6e15fc9d5d /src/streams.cpp | |
parent | fa7724bc9d94c08d8facccd0a067d6a3b27fbbc6 (diff) | |
download | bitcoin-000019e158ef01f2bedc3fc1589f95e106e817ea.tar.xz |
Add AutoFile::detail_fread member function
New code can call the method without having first to retrieve the raw
FILE* pointer via Get().
Also, move implementation to the cpp file. Can be reviewed with:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space
Diffstat (limited to 'src/streams.cpp')
-rw-r--r-- | src/streams.cpp | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/src/streams.cpp b/src/streams.cpp new file mode 100644 index 0000000000..16a8e51722 --- /dev/null +++ b/src/streams.cpp @@ -0,0 +1,40 @@ +// Copyright (c) 2009-present The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or https://opensource.org/license/mit/. + +#include <span.h> +#include <streams.h> + +std::size_t AutoFile::detail_fread(Span<std::byte> dst) +{ + if (!m_file) throw std::ios_base::failure("AutoFile::read: file handle is nullptr"); + return std::fread(dst.data(), 1, dst.size(), m_file); +} + +void AutoFile::read(Span<std::byte> dst) +{ + if (detail_fread(dst) != dst.size()) { + throw std::ios_base::failure(feof() ? "AutoFile::read: end of file" : "AutoFile::read: fread failed"); + } +} + +void AutoFile::ignore(size_t nSize) +{ + if (!m_file) throw std::ios_base::failure("AutoFile::ignore: file handle is nullptr"); + unsigned char data[4096]; + while (nSize > 0) { + size_t nNow = std::min<size_t>(nSize, sizeof(data)); + if (std::fread(data, 1, nNow, m_file) != nNow) { + throw std::ios_base::failure(feof() ? "AutoFile::ignore: end of file" : "AutoFile::ignore: fread failed"); + } + nSize -= nNow; + } +} + +void AutoFile::write(Span<const std::byte> src) +{ + if (!m_file) throw std::ios_base::failure("AutoFile::write: file handle is nullptr"); + if (std::fwrite(src.data(), 1, src.size(), m_file) != src.size()) { + throw std::ios_base::failure("AutoFile::write: write failed"); + } +} |