codex
Loading...
Searching...
No Matches
block.hpp
Go to the documentation of this file.
1#ifndef CODEX_BASE64_BLOCK_H
2#define CODEX_BASE64_BLOCK_H
3
4#include <cassert>
5#include <cerrno>
6#include <concepts>
7#include <cstdio>
8#include <cstring>
9#include <iostream>
10#include <optional>
11#include <span>
12#include <string_view>
13#include <type_traits>
14
21template<typename T> concept ProcessingFunc =
22 std::same_as<
23 std::invoke_result_t<T, std::size_t>,
24 std::size_t>;
25
26inline std::optional<std::size_t> read_all(
27 FILE *f, std::size_t size, std::span<char> s);
28inline bool write_all(FILE *f, std::string_view s);
29inline bool process_blocks(
30 FILE *in, FILE *out, std::size_t size,
31 std::span<char> in_s, std::span<char> out_s,
32 ProcessingFunc auto f);
33
43std::optional<std::size_t> read_all(
44 FILE *f, std::size_t size, std::span<char> s
45) {
46 assert(s.size() % size == 0);
47 std::size_t n = 0;
48 do {
49 n += fread(s.data() + n, 1, s.size() - n, f);
50 if(ferror(f)) {
51 std::cerr << "fread: " << std::strerror(errno) << '\n';
52 return {};
53 }
54 } while(!feof(f) && n != s.size());
55 if(const auto r = n % size)
56 std::memset(s.data() + n, 0, size - r);
57 return {n};
58}
59
63bool write_all(FILE *f, std::string_view s) {
64 for(std::size_t n = 0; n != s.size();) {
65 n += fwrite(s.data() + n, 1, s.size() - n, f);
66 if(ferror(f)) {
67 std::cerr << "fwrite: " << std::strerror(errno) << '\n';
68 return false;
69 }
70 }
71 return true;
72}
73
81 FILE *in, FILE *out, std::size_t size,
82 std::span<char> in_s, std::span<char> out_s,
83 ProcessingFunc auto f
84) {
85 while(!feof(in)) {
86 if(const auto n = read_all(in, size, in_s); !n)
87 return false;
88 else if(const auto ret = f(*n); !ret)
89 return false;
90 else if(!write_all(out, {out_s.data(), ret}))
91 return false;
92 }
93 return true;
94}
95
96#endif
#define f(x)
Definition 5.c:2
bool process_blocks(FILE *in, FILE *out, std::size_t size, std::span< char > in_s, std::span< char > out_s, ProcessingFunc auto f)
Reads block of a specific size, processes them, and outputs.
Definition block.hpp:80
bool write_all(FILE *f, std::string_view s)
Writes the entire content of s into an output stream.
Definition block.hpp:63
std::optional< std::size_t > read_all(FILE *f, std::size_t size, std::span< char > s)
Reads a block of a specific size.
Definition block.hpp:43
Processes an input buffer.
Definition block.hpp:21
#define r(x, y)
Definition std2.c:13
constexpr const char * data(void) const
Definition utils.hpp:18
constexpr std::size_t size(void) const
Definition utils.hpp:17
constexpr fixed_string s
Definition test.cpp:6