Skip to main content

hex/
hex.rs

1// Copyright 2023 The rust-ggstd authors.
2// Copyright 2016 The Go Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style
4// license that can be found in the LICENSE file.
5
6use ggstd::encoding::hex;
7
8fn main() {
9    example_encode();
10    example_decode();
11    example_decode_string();
12    example_encode_to_string();
13}
14
15fn example_encode() {
16    let src = "Hello Gopher!";
17
18    let mut dst = vec![0; hex::encoded_len(src.len())];
19    let n = hex::encode(&mut dst, src.as_bytes());
20
21    println!("{}", String::from_utf8_lossy(&dst[..n]));
22
23    // Output:
24    // 48656c6c6f20476f7068657221
25}
26
27fn example_decode() {
28    let src = b"48656c6c6f20476f7068657221";
29
30    let mut dst = vec![0; hex::decoded_len(src.len())];
31    let (n, err) = hex::decode(&mut dst, src);
32    if err.is_some() {
33        panic!("{}", err.unwrap());
34    }
35
36    println!("{}", String::from_utf8_lossy(&dst[..n]));
37
38    // Output:
39    // Hello Gopher!
40}
41
42fn example_decode_string() {
43    let s = "48656c6c6f20476f7068657221";
44    let (decoded, err) = hex::decode_string(s);
45    if err.is_some() {
46        panic!("{}", err.unwrap());
47    }
48
49    println!("{}", String::from_utf8_lossy(&decoded));
50
51    // Output:
52    // Hello Gopher!
53}
54
55// fn ExampleDump() {
56// 	content := []byte("Go is an open source programming language.")
57
58// 	fmt.Printf("%s", hex::Dump(content))
59
60// 	// Output:
61// 	// 00000000  47 6f 20 69 73 20 61 6e  20 6f 70 65 6e 20 73 6f  |Go is an open so|
62// 	// 00000010  75 72 63 65 20 70 72 6f  67 72 61 6d 6d 69 6e 67  |urce programming|
63// 	// 00000020  20 6c 61 6e 67 75 61 67  65 2e                    | language.|
64// }
65
66// fn ExampleDumper() {
67// 	lines := []string{
68// 		"Go is an open source programming language.",
69// 		"\n",
70// 		"We encourage all Go users to subscribe to golang-announce.",
71// 	}
72
73// 	stdoutDumper := hex::Dumper(os.Stdout)
74
75// 	defer stdoutDumper.Close()
76
77// 	for _, line := range lines {
78// 		stdoutDumper.Write([]byte(line))
79// 	}
80
81// 	// Output:
82// 	// 00000000  47 6f 20 69 73 20 61 6e  20 6f 70 65 6e 20 73 6f  |Go is an open so|
83// 	// 00000010  75 72 63 65 20 70 72 6f  67 72 61 6d 6d 69 6e 67  |urce programming|
84// 	// 00000020  20 6c 61 6e 67 75 61 67  65 2e 0a 57 65 20 65 6e  | language..We en|
85// 	// 00000030  63 6f 75 72 61 67 65 20  61 6c 6c 20 47 6f 20 75  |courage all Go u|
86// 	// 00000040  73 65 72 73 20 74 6f 20  73 75 62 73 63 72 69 62  |sers to subscrib|
87// 	// 00000050  65 20 74 6f 20 67 6f 6c  61 6e 67 2d 61 6e 6e 6f  |e to golang-anno|
88// 	// 00000060  75 6e 63 65 2e                                    |unce.|
89// }
90
91fn example_encode_to_string() {
92    let src = b"Hello";
93    let encoded_str = hex::encode_to_string(src);
94
95    println!("{}", encoded_str);
96
97    // Output:
98    // 48656c6c6f
99}