blob: 3d39feb6eb63dfe19620797ce740ac681fa9c8cc [file] [log] [blame]
Yingdi Yuf50098d2014-02-26 14:26:29 -08001/**
2 * Copyright (C) 2013 Regents of the University of California.
3 * See COPYING for copyright and distribution information.
4 */
5
6#ifndef NDN_UTIL_IO_HPP
7#define NDN_UTIL_IO_HPP
8
9#include "../common.hpp"
10
11#include "../encoding/block.hpp"
12
13#include <string>
14#include <iostream>
15#include <fstream>
16#include <cryptopp/files.h>
17#include <cryptopp/base64.h>
18#include <cryptopp/hex.h>
19
20
21namespace ndn {
22namespace io {
23
24struct Error : public std::runtime_error { Error(const std::string &what) : std::runtime_error(what) {} };
25
26enum IoEncoding {
27 NO_ENCODING,
28 BASE_64,
29 HEX
30};
31
32template<typename T>
33shared_ptr<T>
34load(std::istream& is, IoEncoding encoding = BASE_64)
35{
36 typedef typename T::Error TypeError;
37 try
38 {
39 using namespace CryptoPP;
40
41 shared_ptr<T> object = make_shared<T>();
42
43 OBufferStream os;
44
45 switch(encoding)
46 {
47 case NO_ENCODING:
48 {
49 FileSource ss(is, true, new FileSink(os));
50 break;
51 }
52 case BASE_64:
53 {
54 FileSource ss(is, true, new Base64Decoder(new FileSink(os)));
55 break;
56 }
57 case HEX:
58 {
59 FileSource ss(is, true, new HexDecoder(new FileSink(os)));
60 break;
61 }
62 default:
63 return shared_ptr<T>();
64 }
65
66 object->wireDecode(Block(os.buf()));
67 return object;
68 }
69 catch(CryptoPP::Exception& e)
70 {
71 return shared_ptr<T>();
72 }
73 catch(Block::Error& e)
74 {
75 return shared_ptr<T>();
76 }
77 catch(TypeError& e)
78 {
79 return shared_ptr<T>();
80 }
81}
82
83template<typename T>
84shared_ptr<T>
85load(const std::string& file, IoEncoding encoding = BASE_64)
86{
87 std::ifstream is(file.c_str());
88 return load<T>(is, encoding);
89}
90
91template<typename T>
92void
93save(const T& object, std::ostream& os, IoEncoding encoding = BASE_64)
94{
95 typedef typename T::Error TypeError;
96 try
97 {
98 using namespace CryptoPP;
99
100 Block block = object.wireEncode();
101
102 switch(encoding)
103 {
104 case NO_ENCODING:
105 {
106 StringSource ss(block.wire(), block.size(), true, new FileSink(os));
107 break;
108 }
109 case BASE_64:
110 {
111 StringSource ss(block.wire(), block.size(), true, new Base64Encoder(new FileSink(os), true, 64));
112 break;
113 }
114 case HEX:
115 {
116 StringSource ss(block.wire(), block.size(), true, new HexEncoder(new FileSink(os)));
117 break;
118 }
119 default:
120 return;
121 }
122 return;
123 }
124 catch(CryptoPP::Exception& e)
125 {
126 throw Error(e.what());
127 }
128 catch(Block::Error& e)
129 {
130 throw Error(e.what());
131 }
132 catch(TypeError& e)
133 {
134 throw Error(e.what());
135 }
136}
137
138template<typename T>
139void
140save(const T& object, const std::string& file, IoEncoding encoding = BASE_64)
141{
142 std::ofstream os(file.c_str());
143 save(object, os, encoding);
144}
145
146} // namespace io
147} // namespace ndn
148
149#endif // NDN_UTIL_IO_HPP
150