LMAssembly // Introduce LMRevLookup.

- This module is not supposed to be binded to LMInstantiator. Instead, use it when calling the reverse lookup window, and throw it after the window closes.
This commit is contained in:
ShikiSuen 2022-12-10 12:25:54 +08:00
parent 16162cd9ca
commit de1710b856
1 changed files with 68 additions and 0 deletions

View File

@ -0,0 +1,68 @@
// (c) 2021 and onwards The vChewing Project (MIT-NTL License).
// ====================
// This code is released under the MIT license (SPDX-License-Identifier: MIT)
// ... with NTL restriction stating that:
// No trademark license is granted to use the trade names, trademarks, service
// marks, or product names of Contributor, except as required to fulfill notice
// requirements defined in MIT License.
import Foundation
import Shared
extension vChewingLM {
@frozen public struct LMRevLookup {
public private(set) var dataMap: [String: [Data]] = [:]
public private(set) var filePath: String = ""
public init(dataMap: [String: [Data]]) {
self.dataMap = dataMap
}
public init(path: String) {
if path.isEmpty { return }
do {
let rawData = try Data(contentsOf: URL(fileURLWithPath: path))
let rawPlist: [String: [Data]] =
try PropertyListSerialization.propertyList(from: rawData, format: nil) as? [String: [Data]] ?? .init()
dataMap = rawPlist
} catch {
vCLog("↑ Exception happened when reading plist file at: \(path).")
return
}
filePath = path
}
public func query(with kanji: String) -> [String]? {
guard let resultData = dataMap[kanji] else { return nil }
let resultArray = resultData.compactMap {
let result = restorePhonabetFromASCII(String(decoding: $0, as: UTF8.self))
return result.isEmpty ? nil : result
}
return resultArray.isEmpty ? nil : resultArray
}
///
///
/// ASCII
/// - parameters:
/// - incoming:
func restorePhonabetFromASCII(_ incoming: String) -> String {
var strOutput = incoming
if !strOutput.contains("_") {
for entry in Self.dicPhonabet4ASCII {
strOutput = strOutput.replacingOccurrences(of: entry.key, with: entry.value)
}
}
return strOutput
}
// MARK: - Constants
static let dicPhonabet4ASCII: [String: String] = [
"b": "", "p": "", "m": "", "f": "", "d": "", "t": "", "n": "", "l": "", "g": "", "k": "", "h": "",
"j": "", "q": "", "x": "", "Z": "", "C": "", "S": "", "r": "", "z": "", "c": "", "s": "", "i": "",
"u": "", "v": "", "a": "", "o": "", "e": "", "E": "", "B": "", "P": "", "M": "", "F": "", "D": "",
"T": "", "N": "", "L": "", "R": "", "2": "ˊ", "3": "ˇ", "4": "ˋ", "5": "˙",
]
}
}