FST  openfst-1.8.3
OpenFst Library
create.h
Go to the documentation of this file.
1 // Copyright 2005-2024 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the 'License');
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an 'AS IS' BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 // See www.openfst.org for extensive documentation on this weighted
16 // finite-state transducer library.
17 //
18 // Creates a finite-state archive from component FSTs.
19 
20 #ifndef FST_EXTENSIONS_FAR_CREATE_H_
21 #define FST_EXTENSIONS_FAR_CREATE_H_
22 
23 #include <libgen.h>
24 
25 #include <cstddef>
26 #include <cstdint>
27 #include <cstring>
28 #include <memory>
29 #include <sstream>
30 #include <string>
31 #include <vector>
32 
33 #include <fst/extensions/far/far.h>
34 #include <fst/fst.h>
35 
36 namespace fst {
37 
38 template <class Arc>
39 void Create(const std::vector<std::string> &sources, FarWriter<Arc> &writer,
40  int32_t generate_keys, const std::string &key_prefix,
41  const std::string &key_suffix) {
42  for (size_t i = 0; i < sources.size(); ++i) {
43  std::unique_ptr<Fst<Arc>> ifst(Fst<Arc>::Read(sources[i]));
44  if (!ifst) return;
45  std::string key;
46  if (generate_keys > 0) {
47  std::ostringstream keybuf;
48  keybuf.width(generate_keys);
49  keybuf.fill('0');
50  keybuf << i + 1;
51  key = keybuf.str();
52  } else {
53  auto source =
54  fst::make_unique_for_overwrite<char[]>(sources[i].size() + 1);
55  strcpy(source.get(), sources[i].c_str()); // NOLINT(runtime/printf)
56  key = basename(source.get());
57  }
58  writer.Add(key_prefix + key + key_suffix, *ifst);
59  }
60 }
61 
62 } // namespace fst
63 
64 #endif // FST_EXTENSIONS_FAR_CREATE_H_
void Create(const std::vector< std::string > &sources, FarWriter< Arc > &writer, int32_t generate_keys, const std::string &key_prefix, const std::string &key_suffix)
Definition: create.h:39
virtual void Add(std::string_view key, const Fst< Arc > &fst)=0