##// END OF EJS Templates
rust-utils: add `Escaped` trait...
Raphaël Gomès -
r44740:aa0fc32e default
parent child Browse files
Show More
@@ -7,6 +7,9 b''
7
7
8 //! Contains useful functions, traits, structs, etc. for use in core.
8 //! Contains useful functions, traits, structs, etc. for use in core.
9
9
10 use crate::utils::hg_path::HgPath;
11 use std::{io::Write, ops::Deref};
12
10 pub mod files;
13 pub mod files;
11 pub mod hg_path;
14 pub mod hg_path;
12 pub mod path_auditor;
15 pub mod path_auditor;
@@ -112,3 +115,54 b' impl SliceExt for [u8] {'
112 }
115 }
113 }
116 }
114 }
117 }
118
119 pub trait Escaped {
120 /// Return bytes escaped for display to the user
121 fn escaped_bytes(&self) -> Vec<u8>;
122 }
123
124 impl Escaped for u8 {
125 fn escaped_bytes(&self) -> Vec<u8> {
126 let mut acc = vec![];
127 match self {
128 c @ b'\'' | c @ b'\\' => {
129 acc.push(b'\\');
130 acc.push(*c);
131 }
132 b'\t' => {
133 acc.extend(br"\\t");
134 }
135 b'\n' => {
136 acc.extend(br"\\n");
137 }
138 b'\r' => {
139 acc.extend(br"\\r");
140 }
141 c if (*c < b' ' || *c >= 127) => {
142 write!(acc, "\\x{:x}", self).unwrap();
143 }
144 c => {
145 acc.push(*c);
146 }
147 }
148 acc
149 }
150 }
151
152 impl<'a, T: Escaped> Escaped for &'a [T] {
153 fn escaped_bytes(&self) -> Vec<u8> {
154 self.iter().flat_map(|item| item.escaped_bytes()).collect()
155 }
156 }
157
158 impl<T: Escaped> Escaped for Vec<T> {
159 fn escaped_bytes(&self) -> Vec<u8> {
160 self.deref().escaped_bytes()
161 }
162 }
163
164 impl<'a> Escaped for &'a HgPath {
165 fn escaped_bytes(&self) -> Vec<u8> {
166 self.as_bytes().escaped_bytes()
167 }
168 }
General Comments 0
You need to be logged in to leave comments. Login now