forked from SerenityOS/serenity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iconv.cpp
58 lines (44 loc) · 1.62 KB
/
iconv.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
* Copyright (c) 2024, Nico Weber <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/StringView.h>
#include <LibCore/ArgsParser.h>
#include <LibCore/File.h>
#include <LibTextCodec/Decoder.h>
#include <LibTextCodec/Encoder.h>
ErrorOr<int> serenity_main(Main::Arguments arguments)
{
Core::ArgsParser args_parser;
StringView in_path = "-"sv;
args_parser.add_positional_argument(in_path, "Path to input file (reads STDIN if this is omitted)", "FILE", Core::ArgsParser::Required::No);
StringView from = "utf-8"sv;
args_parser.add_option(from, "Source encoding (default utf-8)", "from", 'f', "ENCODING");
StringView to = "utf-8"sv;
args_parser.add_option(to, "Destination encoding (default utf-8)", "to", 't', "ENCODING");
args_parser.parse(arguments);
auto decoder = TextCodec::decoder_for(from);
if (!decoder.has_value()) {
warnln("Unknown source encoding '{}'", from);
return 1;
}
auto encoder = TextCodec::encoder_for(to);
if (!encoder.has_value()) {
warnln("Unknown destination encoding '{}'", to);
return 1;
}
auto file = TRY(Core::File::open_file_or_standard_stream(in_path, Core::File::OpenMode::Read));
auto input = TRY(file->read_until_eof());
auto decoded = TRY(decoder->to_utf8(input));
TRY(encoder->process(
Utf8View(decoded),
[](u8 byte) -> ErrorOr<void> {
out("{}", static_cast<char>(byte));
return {};
},
[](u32) -> ErrorOr<void> {
return Error::from_string_literal("failure during conversion");
}));
return 0;
}