Open Chinese Convert: SerializableDict.hpp Source File

Open Chinese Convert 1.3.2+gad37fd0a6.dirty A project for conversion between Traditional and Simplified Chinese

Loading...
Searching...
No Matches
SerializableDict.hpp
1/*
2 * Open Chinese Convert
3 *
4 * Copyright 2010-2014 Carbo Kuo <byvoid@byvoid.com>
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19#pragma once
20
21#include "Dict.hpp"
22
23namespace opencc {
24
25OPENCC_EXPORT FILE* OpenSerializableFileUtf8(const std::string& fileName,
26 const char* mode);
27
32 class OPENCC_EXPORT SerializableDict {
33public:
37 virtual void SerializeToFile(FILE* fp) const = 0;
38
42 virtual void SerializeToFile(const std::string& fileName) const {
43 FILE* fp = OpenSerializableFileUtf8(fileName, "wb");
44 if (fp == NULL) {
45 throw FileNotWritable(fileName);
46 }
47 SerializeToFile(fp);
48 fclose(fp);
49 }
50
51 template <typename DICT>
52 static bool TryLoadFromFile(const std::string& fileName,
53 std::shared_ptr<DICT>* dict) {
54 FILE* fp = OpenSerializableFileUtf8(fileName, "rb");
55
56 if (fp == NULL) {
57 return false;
58 }
59 std::shared_ptr<DICT> loadedDict = DICT::NewFromFile(fp);
60 fclose(fp);
61 *dict = loadedDict;
62 return true;
63 }
64
65 template <typename DICT>
66 static std::shared_ptr<DICT> NewFromFile(const std::string& fileName) {
67 std::shared_ptr<DICT> dict;
68 if (!TryLoadFromFile<DICT>(fileName, &dict)) {
69 throw FileNotFound(fileName);
70 }
71 return dict;
72 }
73};
74} // namespace opencc
opencc::FileNotWritable
Definition Exception.hpp:55
opencc::SerializableDict
Serializable dictionary interface.
Definition SerializableDict.hpp:32
opencc::SerializableDict::SerializeToFile
virtual void SerializeToFile(const std::string &fileName) const
Serializes the dictionary and writes in to a file.
Definition SerializableDict.hpp:42
opencc::SerializableDict::SerializeToFile
virtual void SerializeToFile(FILE *fp) const =0
Serializes the dictionary and writes in to a file.