##// END OF EJS Templates
rust-hg-path: implement `Display` for `HgPath` and `HgPathBuf`...
Raphaël Gomès -
r44279:c27e688f default
parent child Browse files
Show More
@@ -1,402 +1,415 b''
1 // hg_path.rs
1 // hg_path.rs
2 //
2 //
3 // Copyright 2019 Raphaël Gomès <rgomes@octobus.net>
3 // Copyright 2019 Raphaël Gomès <rgomes@octobus.net>
4 //
4 //
5 // This software may be used and distributed according to the terms of the
5 // This software may be used and distributed according to the terms of the
6 // GNU General Public License version 2 or any later version.
6 // GNU General Public License version 2 or any later version.
7
7
8 use std::borrow::Borrow;
8 use std::borrow::Borrow;
9 use std::ffi::{OsStr, OsString};
9 use std::ffi::{OsStr, OsString};
10 use std::fmt;
10 use std::ops::Deref;
11 use std::ops::Deref;
11 use std::path::{Path, PathBuf};
12 use std::path::{Path, PathBuf};
12
13
13 #[derive(Debug, Eq, PartialEq)]
14 #[derive(Debug, Eq, PartialEq)]
14 pub enum HgPathError {
15 pub enum HgPathError {
15 /// Bytes from the invalid `HgPath`
16 /// Bytes from the invalid `HgPath`
16 LeadingSlash(Vec<u8>),
17 LeadingSlash(Vec<u8>),
17 /// Bytes and index of the second slash
18 /// Bytes and index of the second slash
18 ConsecutiveSlashes(Vec<u8>, usize),
19 ConsecutiveSlashes(Vec<u8>, usize),
19 /// Bytes and index of the null byte
20 /// Bytes and index of the null byte
20 ContainsNullByte(Vec<u8>, usize),
21 ContainsNullByte(Vec<u8>, usize),
21 /// Bytes
22 /// Bytes
22 DecodeError(Vec<u8>),
23 DecodeError(Vec<u8>),
23 }
24 }
24
25
25 impl ToString for HgPathError {
26 impl ToString for HgPathError {
26 fn to_string(&self) -> String {
27 fn to_string(&self) -> String {
27 match self {
28 match self {
28 HgPathError::LeadingSlash(bytes) => {
29 HgPathError::LeadingSlash(bytes) => {
29 format!("Invalid HgPath '{:?}': has a leading slash.", bytes)
30 format!("Invalid HgPath '{:?}': has a leading slash.", bytes)
30 }
31 }
31 HgPathError::ConsecutiveSlashes(bytes, pos) => format!(
32 HgPathError::ConsecutiveSlashes(bytes, pos) => format!(
32 "Invalid HgPath '{:?}': consecutive slahes at pos {}.",
33 "Invalid HgPath '{:?}': consecutive slahes at pos {}.",
33 bytes, pos
34 bytes, pos
34 ),
35 ),
35 HgPathError::ContainsNullByte(bytes, pos) => format!(
36 HgPathError::ContainsNullByte(bytes, pos) => format!(
36 "Invalid HgPath '{:?}': contains null byte at pos {}.",
37 "Invalid HgPath '{:?}': contains null byte at pos {}.",
37 bytes, pos
38 bytes, pos
38 ),
39 ),
39 HgPathError::DecodeError(bytes) => {
40 HgPathError::DecodeError(bytes) => {
40 format!("Invalid HgPath '{:?}': could not be decoded.", bytes)
41 format!("Invalid HgPath '{:?}': could not be decoded.", bytes)
41 }
42 }
42 }
43 }
43 }
44 }
44 }
45 }
45
46
46 impl From<HgPathError> for std::io::Error {
47 impl From<HgPathError> for std::io::Error {
47 fn from(e: HgPathError) -> Self {
48 fn from(e: HgPathError) -> Self {
48 std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string())
49 std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string())
49 }
50 }
50 }
51 }
51
52
52 /// This is a repository-relative path (or canonical path):
53 /// This is a repository-relative path (or canonical path):
53 /// - no null characters
54 /// - no null characters
54 /// - `/` separates directories
55 /// - `/` separates directories
55 /// - no consecutive slashes
56 /// - no consecutive slashes
56 /// - no leading slash,
57 /// - no leading slash,
57 /// - no `.` nor `..` of special meaning
58 /// - no `.` nor `..` of special meaning
58 /// - stored in repository and shared across platforms
59 /// - stored in repository and shared across platforms
59 ///
60 ///
60 /// Note: there is no guarantee of any `HgPath` being well-formed at any point
61 /// Note: there is no guarantee of any `HgPath` being well-formed at any point
61 /// in its lifetime for performance reasons and to ease ergonomics. It is
62 /// in its lifetime for performance reasons and to ease ergonomics. It is
62 /// however checked using the `check_state` method before any file-system
63 /// however checked using the `check_state` method before any file-system
63 /// operation.
64 /// operation.
64 ///
65 ///
65 /// This allows us to be encoding-transparent as much as possible, until really
66 /// This allows us to be encoding-transparent as much as possible, until really
66 /// needed; `HgPath` can be transformed into a platform-specific path (`OsStr`
67 /// needed; `HgPath` can be transformed into a platform-specific path (`OsStr`
67 /// or `Path`) whenever more complex operations are needed:
68 /// or `Path`) whenever more complex operations are needed:
68 /// On Unix, it's just byte-to-byte conversion. On Windows, it has to be
69 /// On Unix, it's just byte-to-byte conversion. On Windows, it has to be
69 /// decoded from MBCS to WTF-8. If WindowsUTF8Plan is implemented, the source
70 /// decoded from MBCS to WTF-8. If WindowsUTF8Plan is implemented, the source
70 /// character encoding will be determined on a per-repository basis.
71 /// character encoding will be determined on a per-repository basis.
71 //
72 //
72 // FIXME: (adapted from a comment in the stdlib)
73 // FIXME: (adapted from a comment in the stdlib)
73 // `HgPath::new()` current implementation relies on `Slice` being
74 // `HgPath::new()` current implementation relies on `Slice` being
74 // layout-compatible with `[u8]`.
75 // layout-compatible with `[u8]`.
75 // When attribute privacy is implemented, `Slice` should be annotated as
76 // When attribute privacy is implemented, `Slice` should be annotated as
76 // `#[repr(transparent)]`.
77 // `#[repr(transparent)]`.
77 // Anyway, `Slice` representation and layout are considered implementation
78 // Anyway, `Slice` representation and layout are considered implementation
78 // detail, are not documented and must not be relied upon.
79 // detail, are not documented and must not be relied upon.
79 #[derive(Eq, Ord, PartialEq, PartialOrd, Debug, Hash)]
80 #[derive(Eq, Ord, PartialEq, PartialOrd, Debug, Hash)]
80 pub struct HgPath {
81 pub struct HgPath {
81 inner: [u8],
82 inner: [u8],
82 }
83 }
83
84
84 impl HgPath {
85 impl HgPath {
85 pub fn new<S: AsRef<[u8]> + ?Sized>(s: &S) -> &Self {
86 pub fn new<S: AsRef<[u8]> + ?Sized>(s: &S) -> &Self {
86 unsafe { &*(s.as_ref() as *const [u8] as *const Self) }
87 unsafe { &*(s.as_ref() as *const [u8] as *const Self) }
87 }
88 }
88 pub fn is_empty(&self) -> bool {
89 pub fn is_empty(&self) -> bool {
89 self.inner.is_empty()
90 self.inner.is_empty()
90 }
91 }
91 pub fn len(&self) -> usize {
92 pub fn len(&self) -> usize {
92 self.inner.len()
93 self.inner.len()
93 }
94 }
94 fn to_hg_path_buf(&self) -> HgPathBuf {
95 fn to_hg_path_buf(&self) -> HgPathBuf {
95 HgPathBuf {
96 HgPathBuf {
96 inner: self.inner.to_owned(),
97 inner: self.inner.to_owned(),
97 }
98 }
98 }
99 }
99 pub fn bytes(&self) -> std::slice::Iter<u8> {
100 pub fn bytes(&self) -> std::slice::Iter<u8> {
100 self.inner.iter()
101 self.inner.iter()
101 }
102 }
102 pub fn to_ascii_uppercase(&self) -> HgPathBuf {
103 pub fn to_ascii_uppercase(&self) -> HgPathBuf {
103 HgPathBuf::from(self.inner.to_ascii_uppercase())
104 HgPathBuf::from(self.inner.to_ascii_uppercase())
104 }
105 }
105 pub fn to_ascii_lowercase(&self) -> HgPathBuf {
106 pub fn to_ascii_lowercase(&self) -> HgPathBuf {
106 HgPathBuf::from(self.inner.to_ascii_lowercase())
107 HgPathBuf::from(self.inner.to_ascii_lowercase())
107 }
108 }
108 pub fn as_bytes(&self) -> &[u8] {
109 pub fn as_bytes(&self) -> &[u8] {
109 &self.inner
110 &self.inner
110 }
111 }
111 pub fn contains(&self, other: u8) -> bool {
112 pub fn contains(&self, other: u8) -> bool {
112 self.inner.contains(&other)
113 self.inner.contains(&other)
113 }
114 }
114 pub fn join<T: ?Sized + AsRef<HgPath>>(&self, other: &T) -> HgPathBuf {
115 pub fn join<T: ?Sized + AsRef<HgPath>>(&self, other: &T) -> HgPathBuf {
115 let mut inner = self.inner.to_owned();
116 let mut inner = self.inner.to_owned();
116 if inner.len() != 0 && inner.last() != Some(&b'/') {
117 if inner.len() != 0 && inner.last() != Some(&b'/') {
117 inner.push(b'/');
118 inner.push(b'/');
118 }
119 }
119 inner.extend(other.as_ref().bytes());
120 inner.extend(other.as_ref().bytes());
120 HgPathBuf::from_bytes(&inner)
121 HgPathBuf::from_bytes(&inner)
121 }
122 }
122 /// Checks for errors in the path, short-circuiting at the first one.
123 /// Checks for errors in the path, short-circuiting at the first one.
123 /// This generates fine-grained errors useful for debugging.
124 /// This generates fine-grained errors useful for debugging.
124 /// To simply check if the path is valid during tests, use `is_valid`.
125 /// To simply check if the path is valid during tests, use `is_valid`.
125 pub fn check_state(&self) -> Result<(), HgPathError> {
126 pub fn check_state(&self) -> Result<(), HgPathError> {
126 if self.len() == 0 {
127 if self.len() == 0 {
127 return Ok(());
128 return Ok(());
128 }
129 }
129 let bytes = self.as_bytes();
130 let bytes = self.as_bytes();
130 let mut previous_byte = None;
131 let mut previous_byte = None;
131
132
132 if bytes[0] == b'/' {
133 if bytes[0] == b'/' {
133 return Err(HgPathError::LeadingSlash(bytes.to_vec()));
134 return Err(HgPathError::LeadingSlash(bytes.to_vec()));
134 }
135 }
135 for (index, byte) in bytes.iter().enumerate() {
136 for (index, byte) in bytes.iter().enumerate() {
136 match byte {
137 match byte {
137 0 => {
138 0 => {
138 return Err(HgPathError::ContainsNullByte(
139 return Err(HgPathError::ContainsNullByte(
139 bytes.to_vec(),
140 bytes.to_vec(),
140 index,
141 index,
141 ))
142 ))
142 }
143 }
143 b'/' => {
144 b'/' => {
144 if previous_byte.is_some() && previous_byte == Some(b'/') {
145 if previous_byte.is_some() && previous_byte == Some(b'/') {
145 return Err(HgPathError::ConsecutiveSlashes(
146 return Err(HgPathError::ConsecutiveSlashes(
146 bytes.to_vec(),
147 bytes.to_vec(),
147 index,
148 index,
148 ));
149 ));
149 }
150 }
150 }
151 }
151 _ => (),
152 _ => (),
152 };
153 };
153 previous_byte = Some(*byte);
154 previous_byte = Some(*byte);
154 }
155 }
155 Ok(())
156 Ok(())
156 }
157 }
157
158
158 #[cfg(test)]
159 #[cfg(test)]
159 /// Only usable during tests to force developers to handle invalid states
160 /// Only usable during tests to force developers to handle invalid states
160 fn is_valid(&self) -> bool {
161 fn is_valid(&self) -> bool {
161 self.check_state().is_ok()
162 self.check_state().is_ok()
162 }
163 }
163 }
164 }
164
165
166 impl fmt::Display for HgPath {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 write!(f, "{}", String::from_utf8_lossy(&self.inner))
169 }
170 }
171
165 #[derive(Eq, Ord, Clone, PartialEq, PartialOrd, Debug, Hash)]
172 #[derive(Eq, Ord, Clone, PartialEq, PartialOrd, Debug, Hash)]
166 pub struct HgPathBuf {
173 pub struct HgPathBuf {
167 inner: Vec<u8>,
174 inner: Vec<u8>,
168 }
175 }
169
176
170 impl HgPathBuf {
177 impl HgPathBuf {
171 pub fn new() -> Self {
178 pub fn new() -> Self {
172 Self { inner: Vec::new() }
179 Self { inner: Vec::new() }
173 }
180 }
174 pub fn push(&mut self, byte: u8) {
181 pub fn push(&mut self, byte: u8) {
175 self.inner.push(byte);
182 self.inner.push(byte);
176 }
183 }
177 pub fn from_bytes(s: &[u8]) -> HgPathBuf {
184 pub fn from_bytes(s: &[u8]) -> HgPathBuf {
178 HgPath::new(s).to_owned()
185 HgPath::new(s).to_owned()
179 }
186 }
180 pub fn into_vec(self) -> Vec<u8> {
187 pub fn into_vec(self) -> Vec<u8> {
181 self.inner
188 self.inner
182 }
189 }
183 pub fn as_ref(&self) -> &[u8] {
190 pub fn as_ref(&self) -> &[u8] {
184 self.inner.as_ref()
191 self.inner.as_ref()
185 }
192 }
186 }
193 }
187
194
195 impl fmt::Display for HgPathBuf {
196 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197 write!(f, "{}", String::from_utf8_lossy(&self.inner))
198 }
199 }
200
188 impl Deref for HgPathBuf {
201 impl Deref for HgPathBuf {
189 type Target = HgPath;
202 type Target = HgPath;
190
203
191 #[inline]
204 #[inline]
192 fn deref(&self) -> &HgPath {
205 fn deref(&self) -> &HgPath {
193 &HgPath::new(&self.inner)
206 &HgPath::new(&self.inner)
194 }
207 }
195 }
208 }
196
209
197 impl From<Vec<u8>> for HgPathBuf {
210 impl From<Vec<u8>> for HgPathBuf {
198 fn from(vec: Vec<u8>) -> Self {
211 fn from(vec: Vec<u8>) -> Self {
199 Self { inner: vec }
212 Self { inner: vec }
200 }
213 }
201 }
214 }
202
215
203 impl<T: ?Sized + AsRef<HgPath>> From<&T> for HgPathBuf {
216 impl<T: ?Sized + AsRef<HgPath>> From<&T> for HgPathBuf {
204 fn from(s: &T) -> HgPathBuf {
217 fn from(s: &T) -> HgPathBuf {
205 s.as_ref().to_owned()
218 s.as_ref().to_owned()
206 }
219 }
207 }
220 }
208
221
209 impl Into<Vec<u8>> for HgPathBuf {
222 impl Into<Vec<u8>> for HgPathBuf {
210 fn into(self) -> Vec<u8> {
223 fn into(self) -> Vec<u8> {
211 self.inner
224 self.inner
212 }
225 }
213 }
226 }
214
227
215 impl Borrow<HgPath> for HgPathBuf {
228 impl Borrow<HgPath> for HgPathBuf {
216 fn borrow(&self) -> &HgPath {
229 fn borrow(&self) -> &HgPath {
217 &HgPath::new(self.as_bytes())
230 &HgPath::new(self.as_bytes())
218 }
231 }
219 }
232 }
220
233
221 impl ToOwned for HgPath {
234 impl ToOwned for HgPath {
222 type Owned = HgPathBuf;
235 type Owned = HgPathBuf;
223
236
224 fn to_owned(&self) -> HgPathBuf {
237 fn to_owned(&self) -> HgPathBuf {
225 self.to_hg_path_buf()
238 self.to_hg_path_buf()
226 }
239 }
227 }
240 }
228
241
229 impl AsRef<HgPath> for HgPath {
242 impl AsRef<HgPath> for HgPath {
230 fn as_ref(&self) -> &HgPath {
243 fn as_ref(&self) -> &HgPath {
231 self
244 self
232 }
245 }
233 }
246 }
234
247
235 impl AsRef<HgPath> for HgPathBuf {
248 impl AsRef<HgPath> for HgPathBuf {
236 fn as_ref(&self) -> &HgPath {
249 fn as_ref(&self) -> &HgPath {
237 self
250 self
238 }
251 }
239 }
252 }
240
253
241 impl Extend<u8> for HgPathBuf {
254 impl Extend<u8> for HgPathBuf {
242 fn extend<T: IntoIterator<Item = u8>>(&mut self, iter: T) {
255 fn extend<T: IntoIterator<Item = u8>>(&mut self, iter: T) {
243 self.inner.extend(iter);
256 self.inner.extend(iter);
244 }
257 }
245 }
258 }
246
259
247 /// TODO: Once https://www.mercurial-scm.org/wiki/WindowsUTF8Plan is
260 /// TODO: Once https://www.mercurial-scm.org/wiki/WindowsUTF8Plan is
248 /// implemented, these conversion utils will have to work differently depending
261 /// implemented, these conversion utils will have to work differently depending
249 /// on the repository encoding: either `UTF-8` or `MBCS`.
262 /// on the repository encoding: either `UTF-8` or `MBCS`.
250
263
251 pub fn hg_path_to_os_string<P: AsRef<HgPath>>(
264 pub fn hg_path_to_os_string<P: AsRef<HgPath>>(
252 hg_path: P,
265 hg_path: P,
253 ) -> Result<OsString, HgPathError> {
266 ) -> Result<OsString, HgPathError> {
254 hg_path.as_ref().check_state()?;
267 hg_path.as_ref().check_state()?;
255 let os_str;
268 let os_str;
256 #[cfg(unix)]
269 #[cfg(unix)]
257 {
270 {
258 use std::os::unix::ffi::OsStrExt;
271 use std::os::unix::ffi::OsStrExt;
259 os_str = std::ffi::OsStr::from_bytes(&hg_path.as_ref().as_bytes());
272 os_str = std::ffi::OsStr::from_bytes(&hg_path.as_ref().as_bytes());
260 }
273 }
261 // TODO Handle other platforms
274 // TODO Handle other platforms
262 // TODO: convert from WTF8 to Windows MBCS (ANSI encoding).
275 // TODO: convert from WTF8 to Windows MBCS (ANSI encoding).
263 Ok(os_str.to_os_string())
276 Ok(os_str.to_os_string())
264 }
277 }
265
278
266 pub fn hg_path_to_path_buf<P: AsRef<HgPath>>(
279 pub fn hg_path_to_path_buf<P: AsRef<HgPath>>(
267 hg_path: P,
280 hg_path: P,
268 ) -> Result<PathBuf, HgPathError> {
281 ) -> Result<PathBuf, HgPathError> {
269 Ok(Path::new(&hg_path_to_os_string(hg_path)?).to_path_buf())
282 Ok(Path::new(&hg_path_to_os_string(hg_path)?).to_path_buf())
270 }
283 }
271
284
272 pub fn os_string_to_hg_path_buf<S: AsRef<OsStr>>(
285 pub fn os_string_to_hg_path_buf<S: AsRef<OsStr>>(
273 os_string: S,
286 os_string: S,
274 ) -> Result<HgPathBuf, HgPathError> {
287 ) -> Result<HgPathBuf, HgPathError> {
275 let buf;
288 let buf;
276 #[cfg(unix)]
289 #[cfg(unix)]
277 {
290 {
278 use std::os::unix::ffi::OsStrExt;
291 use std::os::unix::ffi::OsStrExt;
279 buf = HgPathBuf::from_bytes(&os_string.as_ref().as_bytes());
292 buf = HgPathBuf::from_bytes(&os_string.as_ref().as_bytes());
280 }
293 }
281 // TODO Handle other platforms
294 // TODO Handle other platforms
282 // TODO: convert from WTF8 to Windows MBCS (ANSI encoding).
295 // TODO: convert from WTF8 to Windows MBCS (ANSI encoding).
283
296
284 buf.check_state()?;
297 buf.check_state()?;
285 Ok(buf)
298 Ok(buf)
286 }
299 }
287
300
288 pub fn path_to_hg_path_buf<P: AsRef<Path>>(
301 pub fn path_to_hg_path_buf<P: AsRef<Path>>(
289 path: P,
302 path: P,
290 ) -> Result<HgPathBuf, HgPathError> {
303 ) -> Result<HgPathBuf, HgPathError> {
291 let buf;
304 let buf;
292 let os_str = path.as_ref().as_os_str();
305 let os_str = path.as_ref().as_os_str();
293 #[cfg(unix)]
306 #[cfg(unix)]
294 {
307 {
295 use std::os::unix::ffi::OsStrExt;
308 use std::os::unix::ffi::OsStrExt;
296 buf = HgPathBuf::from_bytes(&os_str.as_bytes());
309 buf = HgPathBuf::from_bytes(&os_str.as_bytes());
297 }
310 }
298 // TODO Handle other platforms
311 // TODO Handle other platforms
299 // TODO: convert from WTF8 to Windows MBCS (ANSI encoding).
312 // TODO: convert from WTF8 to Windows MBCS (ANSI encoding).
300
313
301 buf.check_state()?;
314 buf.check_state()?;
302 Ok(buf)
315 Ok(buf)
303 }
316 }
304
317
305 #[cfg(test)]
318 #[cfg(test)]
306 mod tests {
319 mod tests {
307 use super::*;
320 use super::*;
308
321
309 #[test]
322 #[test]
310 fn test_path_states() {
323 fn test_path_states() {
311 assert_eq!(
324 assert_eq!(
312 Err(HgPathError::LeadingSlash(b"/".to_vec())),
325 Err(HgPathError::LeadingSlash(b"/".to_vec())),
313 HgPath::new(b"/").check_state()
326 HgPath::new(b"/").check_state()
314 );
327 );
315 assert_eq!(
328 assert_eq!(
316 Err(HgPathError::ConsecutiveSlashes(b"a/b//c".to_vec(), 4)),
329 Err(HgPathError::ConsecutiveSlashes(b"a/b//c".to_vec(), 4)),
317 HgPath::new(b"a/b//c").check_state()
330 HgPath::new(b"a/b//c").check_state()
318 );
331 );
319 assert_eq!(
332 assert_eq!(
320 Err(HgPathError::ContainsNullByte(b"a/b/\0c".to_vec(), 4)),
333 Err(HgPathError::ContainsNullByte(b"a/b/\0c".to_vec(), 4)),
321 HgPath::new(b"a/b/\0c").check_state()
334 HgPath::new(b"a/b/\0c").check_state()
322 );
335 );
323 // TODO test HgPathError::DecodeError for the Windows implementation.
336 // TODO test HgPathError::DecodeError for the Windows implementation.
324 assert_eq!(true, HgPath::new(b"").is_valid());
337 assert_eq!(true, HgPath::new(b"").is_valid());
325 assert_eq!(true, HgPath::new(b"a/b/c").is_valid());
338 assert_eq!(true, HgPath::new(b"a/b/c").is_valid());
326 // Backslashes in paths are not significant, but allowed
339 // Backslashes in paths are not significant, but allowed
327 assert_eq!(true, HgPath::new(br"a\b/c").is_valid());
340 assert_eq!(true, HgPath::new(br"a\b/c").is_valid());
328 // Dots in paths are not significant, but allowed
341 // Dots in paths are not significant, but allowed
329 assert_eq!(true, HgPath::new(b"a/b/../c/").is_valid());
342 assert_eq!(true, HgPath::new(b"a/b/../c/").is_valid());
330 assert_eq!(true, HgPath::new(b"./a/b/../c/").is_valid());
343 assert_eq!(true, HgPath::new(b"./a/b/../c/").is_valid());
331 }
344 }
332
345
333 #[test]
346 #[test]
334 fn test_iter() {
347 fn test_iter() {
335 let path = HgPath::new(b"a");
348 let path = HgPath::new(b"a");
336 let mut iter = path.bytes();
349 let mut iter = path.bytes();
337 assert_eq!(Some(&b'a'), iter.next());
350 assert_eq!(Some(&b'a'), iter.next());
338 assert_eq!(None, iter.next_back());
351 assert_eq!(None, iter.next_back());
339 assert_eq!(None, iter.next());
352 assert_eq!(None, iter.next());
340
353
341 let path = HgPath::new(b"a");
354 let path = HgPath::new(b"a");
342 let mut iter = path.bytes();
355 let mut iter = path.bytes();
343 assert_eq!(Some(&b'a'), iter.next_back());
356 assert_eq!(Some(&b'a'), iter.next_back());
344 assert_eq!(None, iter.next_back());
357 assert_eq!(None, iter.next_back());
345 assert_eq!(None, iter.next());
358 assert_eq!(None, iter.next());
346
359
347 let path = HgPath::new(b"abc");
360 let path = HgPath::new(b"abc");
348 let mut iter = path.bytes();
361 let mut iter = path.bytes();
349 assert_eq!(Some(&b'a'), iter.next());
362 assert_eq!(Some(&b'a'), iter.next());
350 assert_eq!(Some(&b'c'), iter.next_back());
363 assert_eq!(Some(&b'c'), iter.next_back());
351 assert_eq!(Some(&b'b'), iter.next_back());
364 assert_eq!(Some(&b'b'), iter.next_back());
352 assert_eq!(None, iter.next_back());
365 assert_eq!(None, iter.next_back());
353 assert_eq!(None, iter.next());
366 assert_eq!(None, iter.next());
354
367
355 let path = HgPath::new(b"abc");
368 let path = HgPath::new(b"abc");
356 let mut iter = path.bytes();
369 let mut iter = path.bytes();
357 assert_eq!(Some(&b'a'), iter.next());
370 assert_eq!(Some(&b'a'), iter.next());
358 assert_eq!(Some(&b'b'), iter.next());
371 assert_eq!(Some(&b'b'), iter.next());
359 assert_eq!(Some(&b'c'), iter.next());
372 assert_eq!(Some(&b'c'), iter.next());
360 assert_eq!(None, iter.next_back());
373 assert_eq!(None, iter.next_back());
361 assert_eq!(None, iter.next());
374 assert_eq!(None, iter.next());
362
375
363 let path = HgPath::new(b"abc");
376 let path = HgPath::new(b"abc");
364 let iter = path.bytes();
377 let iter = path.bytes();
365 let mut vec = Vec::new();
378 let mut vec = Vec::new();
366 vec.extend(iter);
379 vec.extend(iter);
367 assert_eq!(vec![b'a', b'b', b'c'], vec);
380 assert_eq!(vec![b'a', b'b', b'c'], vec);
368
381
369 let path = HgPath::new(b"abc");
382 let path = HgPath::new(b"abc");
370 let mut iter = path.bytes();
383 let mut iter = path.bytes();
371 assert_eq!(Some(2), iter.rposition(|c| *c == b'c'));
384 assert_eq!(Some(2), iter.rposition(|c| *c == b'c'));
372
385
373 let path = HgPath::new(b"abc");
386 let path = HgPath::new(b"abc");
374 let mut iter = path.bytes();
387 let mut iter = path.bytes();
375 assert_eq!(None, iter.rposition(|c| *c == b'd'));
388 assert_eq!(None, iter.rposition(|c| *c == b'd'));
376 }
389 }
377
390
378 #[test]
391 #[test]
379 fn test_join() {
392 fn test_join() {
380 let path = HgPathBuf::from_bytes(b"a").join(HgPath::new(b"b"));
393 let path = HgPathBuf::from_bytes(b"a").join(HgPath::new(b"b"));
381 assert_eq!(b"a/b", path.as_bytes());
394 assert_eq!(b"a/b", path.as_bytes());
382
395
383 let path = HgPathBuf::from_bytes(b"a/").join(HgPath::new(b"b/c"));
396 let path = HgPathBuf::from_bytes(b"a/").join(HgPath::new(b"b/c"));
384 assert_eq!(b"a/b/c", path.as_bytes());
397 assert_eq!(b"a/b/c", path.as_bytes());
385
398
386 // No leading slash if empty before join
399 // No leading slash if empty before join
387 let path = HgPathBuf::new().join(HgPath::new(b"b/c"));
400 let path = HgPathBuf::new().join(HgPath::new(b"b/c"));
388 assert_eq!(b"b/c", path.as_bytes());
401 assert_eq!(b"b/c", path.as_bytes());
389
402
390 // The leading slash is an invalid representation of an `HgPath`, but
403 // The leading slash is an invalid representation of an `HgPath`, but
391 // it can happen. This creates another invalid representation of
404 // it can happen. This creates another invalid representation of
392 // consecutive bytes.
405 // consecutive bytes.
393 // TODO What should be done in this case? Should we silently remove
406 // TODO What should be done in this case? Should we silently remove
394 // the extra slash? Should we change the signature to a problematic
407 // the extra slash? Should we change the signature to a problematic
395 // `Result<HgPathBuf, HgPathError>`, or should we just keep it so and
408 // `Result<HgPathBuf, HgPathError>`, or should we just keep it so and
396 // let the error happen upon filesystem interaction?
409 // let the error happen upon filesystem interaction?
397 let path = HgPathBuf::from_bytes(b"a/").join(HgPath::new(b"/b"));
410 let path = HgPathBuf::from_bytes(b"a/").join(HgPath::new(b"/b"));
398 assert_eq!(b"a//b", path.as_bytes());
411 assert_eq!(b"a//b", path.as_bytes());
399 let path = HgPathBuf::from_bytes(b"a").join(HgPath::new(b"/b"));
412 let path = HgPathBuf::from_bytes(b"a").join(HgPath::new(b"/b"));
400 assert_eq!(b"a//b", path.as_bytes());
413 assert_eq!(b"a//b", path.as_bytes());
401 }
414 }
402 }
415 }
General Comments 0
You need to be logged in to leave comments. Login now