Debian Codegraph @

src/SerializableDict.hpp

raw symbols SCIP
1 /*
2 * Open Chinese Convert
3 *
4 * Copyright 2010-2014 Carbo Kuo <[email protected]>
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
23 namespace opencc {
24
25 OPENCC_EXPORT FILE* OpenSerializableFileUtf8(const std::string& fileName,
26 const char* mode);
27
28 /**
29 * Serializable dictionary interface
30 * @ingroup opencc_cpp_api
31 */
32 class OPENCC_EXPORT SerializableDict {
33 public:
34 /**
35 * Serializes the dictionary and writes in to a file.
36 */
37 virtual void SerializeToFile(FILE* fp) const = 0;
38
39 /**
40 * Serializes the dictionary and writes in to a file.
41 */
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