Debian Codegraph @

rust/hg-core/src/revlog/path_encode.rs

raw
1 use sha1::Digest;
2 use sha1::Sha1;
3
4 use crate::utils::strings::replace_slice;
5
6 #[derive(PartialEq, Debug)]
7 #[allow(non_camel_case_types)]
8 #[allow(clippy::upper_case_acronyms)]
9 enum path_state {
10 START, /* first byte of a path component */
11 A, /* "AUX" */
12 AU,
13 THIRD, /* third of a 3-byte sequence, e.g. "AUX", "NUL" */
14 C, /* "CON" or "COMn" */
15 CO,
16 COMLPT, /* "COM" or "LPT" */
17 COMLPTn,
18 L,
19 LP,
20 N,
21 NU,
22 P, /* "PRN" */
23 PR,
24 LDOT, /* leading '.' */
25 DOT, /* '.' in a non-leading position */
26 H, /* ".h" */
27 HGDI, /* ".hg", ".d", or ".i" */
28 SPACE,
29 DEFAULT, /* byte of a path component after the first */
30 }
31
32 /* state machine for dir-encoding */
33 #[allow(non_camel_case_types)]
34 #[allow(clippy::upper_case_acronyms)]
35 enum dir_state {
36 DDOT,
37 DH,
38 DHGDI,
39 DDEFAULT,
40 }
41
42 trait Sink {
43 fn write_byte(&mut self, c: u8);
44 fn write_bytes(&mut self, c: &[u8]);
45 }
46
47 fn inset(bitset: &[u32; 8], c: u8) -> bool {
48 bitset[(c as usize) >> 5] & (1 << (c & 31)) != 0
49 }
50
51 const MAXENCODE: usize = 4096 * 4;
52
53 struct DestArr<const N: usize> {
54 buf: [u8; N],
55 pub len: usize,
56 }
57
58 impl<const N: usize> DestArr<N> {
59 pub fn create() -> Self {
60 DestArr { buf: [0; N], len: 0 }
61 }
62
63 pub fn contents(&self) -> &[u8] {
64 &self.buf[..self.len]
65 }
66 }
67
68 impl<const N: usize> Sink for DestArr<N> {
69 fn write_byte(&mut self, c: u8) {
70 self.buf[self.len] = c;
71 self.len += 1;
72 }
73
74 fn write_bytes(&mut self, src: &[u8]) {
75 self.buf[self.len..self.len + src.len()].copy_from_slice(src);
76 self.len += src.len();
77 }
78 }
79
80 struct MeasureDest {
81 pub len: usize,
82 }
83
84 impl Sink for Vec<u8> {
85 fn write_byte(&mut self, c: u8) {
86 self.push(c)
87 }
88
89 fn write_bytes(&mut self, src: &[u8]) {
90 self.extend_from_slice(src)
91 }
92 }
93
94 impl MeasureDest {
95 fn create() -> Self {
96 Self { len: 0 }
97 }
98 }
99
100 impl Sink for MeasureDest {
101 fn write_byte(&mut self, _c: u8) {
102 self.len += 1;
103 }
104
105 fn write_bytes(&mut self, src: &[u8]) {
106 self.len += src.len();
107 }
108 }
109
110 fn hexencode(dest: &mut impl Sink, c: u8) {
111 let hexdigit = b"0123456789abcdef";
112 dest.write_byte(hexdigit[(c as usize) >> 4]);
113 dest.write_byte(hexdigit[(c as usize) & 15]);
114 }
115
116 /* 3-byte escape: tilde followed by two hex digits */
117 fn escape3(dest: &mut impl Sink, c: u8) {
118 dest.write_byte(b'~');
119 hexencode(dest, c);
120 }
121
122 fn encode_dir(dest: &mut impl Sink, src: &[u8]) {
123 let mut state = dir_state::DDEFAULT;
124 let mut i = 0;
125
126 while i < src.len() {
127 match state {
128 dir_state::DDOT => match src[i] {
129 b'd' | b'i' => {
130 state = dir_state::DHGDI;
131 dest.write_byte(src[i]);
132 i += 1;
133 }
134 b'h' => {
135 state = dir_state::DH;
136 dest.write_byte(src[i]);
137 i += 1;
138 }
139 _ => {
140 state = dir_state::DDEFAULT;
141 }
142 },
143 dir_state::DH => {
144 if src[i] == b'g' {
145 state = dir_state::DHGDI;
146 dest.write_byte(src[i]);
147 i += 1;
148 } else {
149 state = dir_state::DDEFAULT;
150 }
151 }
152 dir_state::DHGDI => {
153 if src[i] == b'/' {
154 dest.write_bytes(b".hg");
155 dest.write_byte(src[i]);
156 i += 1;
157 }
158 state = dir_state::DDEFAULT;
159 }
160 dir_state::DDEFAULT => {
161 if src[i] == b'.' {
162 state = dir_state::DDOT
163 }
164 dest.write_byte(src[i]);
165 i += 1;
166 }
167 }
168 }
169 }
170
171 fn _encode(
172 twobytes: &[u32; 8],
173 onebyte: &[u32; 8],
174 dest: &mut impl Sink,
175 src: &[u8],
176 encodedir: bool,
177 ) {
178 let mut state = path_state::START;
179 let mut i = 0;
180 let len = src.len();
181
182 while i < len {
183 match state {
184 path_state::START => match src[i] {
185 b'/' => {
186 dest.write_byte(src[i]);
187 i += 1;
188 }
189 b'.' => {
190 state = path_state::LDOT;
191 escape3(dest, src[i]);
192 i += 1;
193 }
194 b' ' => {
195 state = path_state::DEFAULT;
196 escape3(dest, src[i]);
197 i += 1;
198 }
199 b'a' => {
200 state = path_state::A;
201 dest.write_byte(src[i]);
202 i += 1;
203 }
204 b'c' => {
205 state = path_state::C;
206 dest.write_byte(src[i]);
207 i += 1;
208 }
209 b'l' => {
210 state = path_state::L;
211 dest.write_byte(src[i]);
212 i += 1;
213 }
214 b'n' => {
215 state = path_state::N;
216 dest.write_byte(src[i]);
217 i += 1;
218 }
219 b'p' => {
220 state = path_state::P;
221 dest.write_byte(src[i]);
222 i += 1;
223 }
224 _ => {
225 state = path_state::DEFAULT;
226 }
227 },
228 path_state::A => {
229 if src[i] == b'u' {
230 state = path_state::AU;
231 dest.write_byte(src[i]);
232 i += 1;
233 } else {
234 state = path_state::DEFAULT;
235 }
236 }
237 path_state::AU => {
238 if src[i] == b'x' {
239 state = path_state::THIRD;
240 i += 1;
241 } else {
242 state = path_state::DEFAULT;
243 }
244 }
245 path_state::THIRD => {
246 state = path_state::DEFAULT;
247 match src[i] {
248 b'.' | b'/' | b'\0' => escape3(dest, src[i - 1]),
249 _ => i -= 1,
250 }
251 }
252 path_state::C => {
253 if src[i] == b'o' {
254 state = path_state::CO;
255 dest.write_byte(src[i]);
256 i += 1;
257 } else {
258 state = path_state::DEFAULT;
259 }
260 }
261 path_state::CO => {
262 if src[i] == b'm' {
263 state = path_state::COMLPT;
264 i += 1;
265 } else if src[i] == b'n' {
266 state = path_state::THIRD;
267 i += 1;
268 } else {
269 state = path_state::DEFAULT;
270 }
271 }
272 path_state::COMLPT => {
273 if src[i] >= b'1' && src[i] <= b'9' {
274 state = path_state::COMLPTn;
275 i += 1;
276 } else {
277 state = path_state::DEFAULT;
278 dest.write_byte(src[i - 1]);
279 }
280 }
281 path_state::COMLPTn => {
282 state = path_state::DEFAULT;
283 match src[i] {
284 b'.' | b'/' | b'\0' => {
285 escape3(dest, src[i - 2]);
286 dest.write_byte(src[i - 1]);
287 }
288 _ => {
289 dest.write_bytes(&src[i - 2..i]);
290 }
291 }
292 }
293 path_state::L => {
294 if src[i] == b'p' {
295 state = path_state::LP;
296 dest.write_byte(src[i]);
297 i += 1;
298 } else {
299 state = path_state::DEFAULT;
300 }
301 }
302 path_state::LP => {
303 if src[i] == b't' {
304 state = path_state::COMLPT;
305 i += 1;
306 } else {
307 state = path_state::DEFAULT;
308 }
309 }
310 path_state::N => {
311 if src[i] == b'u' {
312 state = path_state::NU;
313 dest.write_byte(src[i]);
314 i += 1;
315 } else {
316 state = path_state::DEFAULT;
317 }
318 }
319 path_state::NU => {
320 if src[i] == b'l' {
321 state = path_state::THIRD;
322 i += 1;
323 } else {
324 state = path_state::DEFAULT;
325 }
326 }
327 path_state::P => {
328 if src[i] == b'r' {
329 state = path_state::PR;
330 dest.write_byte(src[i]);
331 i += 1;
332 } else {
333 state = path_state::DEFAULT;
334 }
335 }
336 path_state::PR => {
337 if src[i] == b'n' {
338 state = path_state::THIRD;
339 i += 1;
340 } else {
341 state = path_state::DEFAULT;
342 }
343 }
344 path_state::LDOT => match src[i] {
345 b'd' | b'i' => {
346 state = path_state::HGDI;
347 dest.write_byte(src[i]);
348 i += 1;
349 }
350 b'h' => {
351 state = path_state::H;
352 dest.write_byte(src[i]);
353 i += 1;
354 }
355 _ => {
356 state = path_state::DEFAULT;
357 }
358 },
359 path_state::DOT => match src[i] {
360 b'/' | b'\0' => {
361 state = path_state::START;
362 dest.write_bytes(b"~2e");
363 dest.write_byte(src[i]);
364 i += 1;
365 }
366 b'd' | b'i' => {
367 state = path_state::HGDI;
368 dest.write_byte(b'.');
369 dest.write_byte(src[i]);
370 i += 1;
371 }
372 b'h' => {
373 state = path_state::H;
374 dest.write_bytes(b".h");
375 i += 1;
376 }
377 _ => {
378 state = path_state::DEFAULT;
379 dest.write_byte(b'.');
380 }
381 },
382 path_state::H => {
383 if src[i] == b'g' {
384 state = path_state::HGDI;
385 dest.write_byte(src[i]);
386 i += 1;
387 } else {
388 state = path_state::DEFAULT;
389 }
390 }
391 path_state::HGDI => {
392 if src[i] == b'/' {
393 state = path_state::START;
394 if encodedir {
395 dest.write_bytes(b".hg");
396 }
397 dest.write_byte(src[i]);
398 i += 1
399 } else {
400 state = path_state::DEFAULT;
401 }
402 }
403 path_state::SPACE => match src[i] {
404 b'/' | b'\0' => {
405 state = path_state::START;
406 dest.write_bytes(b"~20");
407 dest.write_byte(src[i]);
408 i += 1;
409 }
410 _ => {
411 state = path_state::DEFAULT;
412 dest.write_byte(b' ');
413 }
414 },
415 path_state::DEFAULT => {
416 while i != len && inset(onebyte, src[i]) {
417 dest.write_byte(src[i]);
418 i += 1;
419 }
420 if i == len {
421 break;
422 }
423 match src[i] {
424 b'.' => {
425 state = path_state::DOT;
426 i += 1
427 }
428 b' ' => {
429 state = path_state::SPACE;
430 i += 1
431 }
432 b'/' => {
433 state = path_state::START;
434 dest.write_byte(b'/');
435 i += 1;
436 }
437 _ => {
438 if inset(onebyte, src[i]) {
439 loop {
440 dest.write_byte(src[i]);
441 i += 1;
442 if !(i < len && inset(onebyte, src[i])) {
443 break;
444 }
445 }
446 } else if inset(twobytes, src[i]) {
447 let c = src[i];
448 i += 1;
449 dest.write_byte(b'_');
450 dest.write_byte(if c == b'_' {
451 b'_'
452 } else {
453 c + 32
454 });
455 } else {
456 escape3(dest, src[i]);
457 i += 1;
458 }
459 }
460 }
461 }
462 }
463 }
464 match state {
465 path_state::START => (),
466 path_state::A => (),
467 path_state::AU => (),
468 path_state::THIRD => escape3(dest, src[i - 1]),
469 path_state::C => (),
470 path_state::CO => (),
471 path_state::COMLPT => dest.write_byte(src[i - 1]),
472 path_state::COMLPTn => {
473 escape3(dest, src[i - 2]);
474 dest.write_byte(src[i - 1]);
475 }
476 path_state::L => (),
477 path_state::LP => (),
478 path_state::N => (),
479 path_state::NU => (),
480 path_state::P => (),
481 path_state::PR => (),
482 path_state::LDOT => (),
483 path_state::DOT => {
484 dest.write_bytes(b"~2e");
485 }
486 path_state::H => (),
487 path_state::HGDI => (),
488 path_state::SPACE => {
489 dest.write_bytes(b"~20");
490 }
491 path_state::DEFAULT => (),
492 }
493 }
494
495 fn basic_encode(dest: &mut impl Sink, src: &[u8]) {
496 let twobytes: [u32; 8] = [0, 0, 0x87ff_fffe, 0, 0, 0, 0, 0];
497 let onebyte: [u32; 8] =
498 [1, 0x2bff_3bfa, 0x6800_0001, 0x2fff_ffff, 0, 0, 0, 0];
499 _encode(&twobytes, &onebyte, dest, src, true)
500 }
501
502 const MAXSTOREPATHLEN: usize = 120;
503
504 fn lower_encode(dest: &mut impl Sink, src: &[u8]) {
505 let onebyte: [u32; 8] =
506 [1, 0x2bff_fbfb, 0xe800_0001, 0x2fff_ffff, 0, 0, 0, 0];
507 let lower: [u32; 8] = [0, 0, 0x07ff_fffe, 0, 0, 0, 0, 0];
508 for c in src {
509 if inset(&onebyte, *c) {
510 dest.write_byte(*c)
511 } else if inset(&lower, *c) {
512 dest.write_byte(*c + 32)
513 } else {
514 escape3(dest, *c)
515 }
516 }
517 }
518
519 fn aux_encode(dest: &mut impl Sink, src: &[u8]) {
520 let twobytes = [0; 8];
521 let onebyte: [u32; 8] = [!0, 0xffff_3ffe, !0, !0, !0, !0, !0, !0];
522 _encode(&twobytes, &onebyte, dest, src, false)
523 }
524
525 fn hash_mangle(src: &[u8], sha: &[u8]) -> Vec<u8> {
526 let dirprefixlen = 8;
527 let maxshortdirslen = 68;
528
529 let last_slash = src.iter().rposition(|b| *b == b'/');
530 let basename_start = match last_slash {
531 Some(slash) => slash + 1,
532 None => 0,
533 };
534 let basename = &src[basename_start..];
535 let ext = match basename.iter().rposition(|b| *b == b'.') {
536 None => &[],
537 Some(dot) => &basename[dot..],
538 };
539
540 let mut dest = Vec::with_capacity(MAXSTOREPATHLEN);
541 dest.write_bytes(b"dh/");
542
543 if let Some(last_slash) = last_slash {
544 for slice in src[..last_slash].split(|b| *b == b'/') {
545 let slice = &slice[..std::cmp::min(slice.len(), dirprefixlen)];
546 if dest.len() + slice.len() > maxshortdirslen + 3 {
547 break;
548 }
549 if let Some(last_char) = slice.last() {
550 if *last_char == b'.' || *last_char == b' ' {
551 dest.write_bytes(&slice[0..slice.len() - 1]);
552 dest.write_byte(b'_');
553 } else {
554 dest.write_bytes(slice);
555 }
556 };
557 dest.write_byte(b'/');
558 }
559 }
560
561 let used = dest.len() + 40 + ext.len();
562
563 if MAXSTOREPATHLEN > used {
564 let slop = MAXSTOREPATHLEN - used;
565 let len = std::cmp::min(basename.len(), slop);
566 dest.write_bytes(&basename[..len])
567 }
568 for c in sha {
569 hexencode(&mut dest, *c);
570 }
571 dest.write_bytes(ext);
572 dest.shrink_to_fit();
573 dest
574 }
575
576 fn hash_encode(src: &[u8]) -> Vec<u8> {
577 let mut dired: DestArr<MAXENCODE> = DestArr::create();
578 let mut lowered: DestArr<MAXENCODE> = DestArr::create();
579 let mut auxed: DestArr<MAXENCODE> = DestArr::create();
580 let baselen = (src.len() - 5) * 3;
581 if baselen >= MAXENCODE {
582 panic!("path_encode::hash_encore: string too long: {}", baselen)
583 };
584 encode_dir(&mut dired, src);
585 let sha = Sha1::digest(dired.contents());
586 lower_encode(&mut lowered, &dired.contents()[5..]);
587 aux_encode(&mut auxed, lowered.contents());
588 hash_mangle(auxed.contents(), &sha)
589 }
590
591 fn plain_encode(src: &[u8]) -> Vec<u8> {
592 if src.starts_with(b"data/") {
593 [&b"data/"[..], &replace_slice(&src[5..], b"/", b"_/")].concat()
594 } else {
595 src.to_owned()
596 }
597 }
598
599 pub fn path_encode(path: &[u8], encoding: PathEncoding) -> Vec<u8> {
600 match encoding {
601 PathEncoding::Hybrid => unreachable!("hybrid encoding is unsupported"),
602 PathEncoding::Plain => return plain_encode(path),
603 PathEncoding::None => {
604 unreachable!("called path encode in a vfs that doesn't encode")
605 }
606 PathEncoding::DotEncode => {}
607 }
608 let newlen = if path.len() <= MAXSTOREPATHLEN {
609 let mut measure = MeasureDest::create();
610 basic_encode(&mut measure, path);
611 measure.len
612 } else {
613 return hash_encode(path);
614 };
615 if newlen <= MAXSTOREPATHLEN {
616 if newlen == path.len() {
617 path.to_vec()
618 } else {
619 let mut dest = Vec::with_capacity(newlen);
620 basic_encode(&mut dest, path);
621 assert!(dest.len() == newlen);
622 dest
623 }
624 } else {
625 hash_encode(path)
626 }
627 }
628
629 #[derive(Debug, Default, Copy, Clone)]
630 pub enum PathEncoding {
631 #[default]
632 DotEncode,
633 /// Unsupported in Rust code
634 Hybrid,
635 Plain,
636 /// Crutch used to define an encoding for non-store VFS while VfsImpl
637 /// still exists and hasn't been cleaned up
638 None,
639 }
640
641 #[cfg(test)]
642 mod tests {
643 use super::*;
644 use crate::utils::hg_path::HgPathBuf;
645
646 #[test]
647 fn test_dirname_ends_with_underscore() {
648 let input = b"data/dir1234.foo/ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJ.i";
649 let expected = b"dh/dir1234_/abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij.if2e9ce59e095eff5f8f334dc809e65606a0aa50b.i";
650 let res = path_encode(input, PathEncoding::DotEncode);
651 assert_eq!(
652 HgPathBuf::from_bytes(&res),
653 HgPathBuf::from_bytes(expected)
654 );
655 }
656
657 #[test]
658 fn test_long_filename_at_root() {
659 let input = b"data/ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJ.i";
660 let expected = b"dh/abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij.i708243a2237a7afae259ea3545a72a2ef11c247b.i";
661 let res = path_encode(input, PathEncoding::DotEncode);
662 assert_eq!(
663 HgPathBuf::from_bytes(&res),
664 HgPathBuf::from_bytes(expected)
665 );
666 }
667
668 #[test]
669 fn test_plain_encode() {
670 assert_eq!(plain_encode(b"foo"), b"foo");
671 assert_eq!(plain_encode(b"foo.txt"), b"foo.txt");
672 assert_eq!(plain_encode(b"bar/foo.txt"), b"bar/foo.txt");
673 dbg!(String::from_utf8_lossy(&plain_encode(b"data/bar/foo.txt")));
674 assert_eq!(plain_encode(b"data/bar/foo.txt"), b"data/bar_/foo.txt");
675 assert_eq!(
676 plain_encode(b"data/ b a r /fuz.d_/baz.i/foo.txt"),
677 b"data/ b a r _/fuz.d__/baz.i_/foo.txt",
678 );
679 }
680 }