| 1 | /* |
| 2 | * Open Chinese Convert |
| 3 | * |
| 4 | * Copyright 2010-2026 Carbo Kuo and contributors |
| 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 | #include "SingleStageConverter.hpp" |
| 20 | |
| 21 | #include "ConversionChain.hpp" |
| 22 | #include "ConversionInspection.hpp" |
| 23 | #include "Segments.hpp" |
| 24 | |
| 25 | using namespace opencc; |
| 26 | |
| 27 | std::string SingleStageConverter::Convert(std::string_view text) const { |
| 28 | std::string converted; |
| 29 | converted.reserve(text.length() + text.length() / 5); |
| 30 | if (segmentation == nullptr) { |
| 31 | conversionChain->AppendConvertedSegment(text, &converted); |
| 32 | return converted; |
| 33 | } |
| 34 | const SegmentsPtr& segments = segmentation->Segment(text); |
| 35 | for (const char* segment : *segments) { |
| 36 | conversionChain->AppendConvertedSegment(segment, &converted); |
| 37 | } |
| 38 | return converted; |
| 39 | } |
| 40 | |
| 41 | ConversionInspectionResult |
| 42 | SingleStageConverter::Inspect(std::string_view text) const { |
| 43 | ConversionInspectionResult result; |
| 44 | result.input = text; |
| 45 | |
| 46 | SegmentsPtr initialSegments; |
| 47 | if (segmentation == nullptr) { |
| 48 | initialSegments.reset(new Segments); |
| 49 | initialSegments->AddSegment(text); |
| 50 | } else { |
| 51 | initialSegments = segmentation->Segment(text); |
| 52 | } |
| 53 | result.segments = initialSegments->ToVector(); |
| 54 | |
| 55 | const std::vector<SegmentsPtr> trace = |
| 56 | conversionChain->ConvertWithTrace(initialSegments); |
| 57 | |
| 58 | result.stages.reserve(trace.size()); |
| 59 | for (size_t i = 0; i < trace.size(); i++) { |
| 60 | ConversionInspectionStage stage; |
| 61 | stage.index = i + 1; |
| 62 | stage.segments = trace[i]->ToVector(); |
| 63 | result.stages.push_back(std::move(stage)); |
| 64 | } |
| 65 | |
| 66 | if (!trace.empty()) { |
| 67 | result.output = trace.back()->ToString(); |
| 68 | } else { |
| 69 | result.output = initialSegments->ToString(); |
| 70 | } |
| 71 | |
| 72 | return result; |
| 73 | } |