39 bool *right_relabel_output) {
43 std::unique_ptr<SymbolTable> merged(
46 bool left_has_all =
true;
47 bool right_has_all =
true;
49 for (
const auto &litem : left) {
50 merged->AddSymbol(litem.Symbol(), litem.Label());
52 int64_t key = right.
Find(litem.Symbol());
54 right_has_all =
false;
55 }
else if (!relabel && key != litem.Label()) {
61 if (right_relabel_output) *right_relabel_output = relabel;
65 std::vector<std::string> conflicts;
66 for (
const auto &ritem : right) {
67 int64_t key = merged->
Find(ritem.Symbol());
70 if (key != ritem.Label()) relabel =
true;
75 if (!merged->Find(ritem.Label()).empty()) {
77 conflicts.push_back(ritem.Symbol());
81 merged->AddSymbol(ritem.Symbol(), ritem.Label());
83 if (right_relabel_output) *right_relabel_output = relabel;
84 if (left_has_all)
return left.Copy();
86 for (
const auto &conflict : conflicts) merged->AddSymbol(conflict);
87 return merged.release();
91 std::map<int64_t, std::string> sorted;
92 for (
const auto &stitem : syms) {
93 sorted[stitem.Label()] = stitem.Symbol();
95 auto compact = std::make_unique<SymbolTable>(syms.Name() +
"_compact");
97 for (
const auto &kv : sorted) compact->
AddSymbol(kv.second, newkey++);
98 return compact.release();
102 bool input_symbols) {
103 std::ifstream in(source, std::ios_base::in | std::ios_base::binary);
105 LOG(ERROR) <<
"FstReadSymbols: Can't open file " << source;
109 if (!hdr.
Read(in, source)) {
110 LOG(ERROR) <<
"FstReadSymbols: Couldn't read header from " << source;
115 if (isymbols ==
nullptr) {
116 LOG(ERROR) <<
"FstReadSymbols: Couldn't read input symbols from " 120 if (input_symbols)
return isymbols.release();
124 if (osymbols ==
nullptr) {
125 LOG(ERROR) <<
"FstReadSymbols: Couldn't read output symbols from " 129 if (!input_symbols)
return osymbols.release();
131 LOG(ERROR) <<
"FstReadSymbols: The file " << source
132 <<
" doesn't contain the requested symbols";
138 for (int64_t i = 0; i < nlabels; ++i) {
139 auto index = i + start_label;
140 if (index != syms->
AddSymbol(prefix + std::to_string(i), index)) {
141 FSTERROR() <<
"AddAuxiliarySymbols: Symbol table clash";
const std::string & Name() const
int64_t AddSymbol(std::string_view symbol, int64_t key)
virtual SymbolTable * Copy() const
constexpr int64_t kNoSymbol
SymbolTable * CompactSymbolTable(const SymbolTable &syms)
SymbolTable * FstReadSymbols(const std::string &source, bool input)
std::string Find(int64_t key) const
SymbolTable * MergeSymbolTable(const SymbolTable &left, const SymbolTable &right, bool *right_relabel_output=nullptr)
static SymbolTable * Read(std::istream &strm, std::string_view source)
bool AddAuxiliarySymbols(const std::string &prefix, int64_t start_label, int64_t nlabels, SymbolTable *syms)