-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathi2pbase64.cpp
82 lines (76 loc) · 1.5 KB
/
i2pbase64.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <unistd.h>
#include <fcntl.h>
#include <iostream>
#include <fstream>
#include <functional>
#include <cassert>
#include "Base.h"
const size_t BUFFSZ = 1024;
static int printHelp(const char * exe, int exitcode)
{
std::cout << "usage: " << exe << " [-d] [filename]" << std::endl;
return exitcode;
}
template <typename InCh, typename OutCh, size_t isz, size_t osz>
static int operate(std::function<std::size_t(const InCh *, size_t, OutCh *, size_t)> f, int infile, int outfile)
{
InCh inbuf[isz];
OutCh outbuf[osz];
ssize_t sz;
size_t outsz;
while((sz = read(infile, inbuf, sizeof(inbuf))) > 0)
{
outsz = f(inbuf, sz, outbuf, sizeof(outbuf));
if(outsz && outsz <= sizeof(outbuf))
{
write(outfile, outbuf, outsz);
}
else
{
return -1;
}
}
return errno;
}
int main(int argc, char * argv[])
{
int opt;
bool decode = false;
int infile = 0;
while((opt = getopt(argc, argv, "dh")) != -1)
{
switch(opt)
{
case 'h':
return printHelp(argv[0], 0);
case 'd':
decode = true;
break;
default:
continue;
}
}
if (argc - optind > 1)
{
return printHelp(argv[0], -1);
}
if (optind < argc)
{
infile = open(argv[optind], O_RDONLY);
if(infile == -1) {
perror(argv[optind]);
return -1;
}
}
int retcode = 0;
if(decode)
{
retcode = operate<char, uint8_t, BUFFSZ*4, BUFFSZ*3>(i2p::data::Base64ToByteStream, infile, 1);
}
else
{
retcode = operate<uint8_t, char, BUFFSZ*3, BUFFSZ*4>(&i2p::data::ByteStreamToBase64, infile, 1);
}
close(infile);
return retcode;
}