Skip to content
Myr

path.go

This file

Path

path.go

203 lines · 4.7 KiB · Go

Last changed by

docs(path): fix malformed comment in cleanPath (#4723)Amirhfbefore adoptiondcaa429

History of this file

Take it

1// Copyright 2013 Julien Schmidt. All rights reserved.2// Based on the path package, Copyright 2009 The Go Authors.3// Use of this source code is governed by a BSD-style license that can be found4// at https://github.com/julienschmidt/httprouter/blob/master/LICENSE.56package gin78const stackBufSize = 128910// cleanPath is the URL version of path.Clean, it returns a canonical URL path11// for p, eliminating . and .. elements.12//13// The following rules are applied iteratively until no further processing can14// be done:15//  1. Replace multiple slashes with a single slash.16//  2. Eliminate each . path name element (the current directory).17//  3. Eliminate each inner .. path name element (the parent directory)18//     along with the non-.. element that precedes it.19//  4. Eliminate .. elements that begin a rooted path:20//     that is, replace "/.." by "/" at the beginning of a path.21//22// If the result of this process is an empty string, "/" is returned.23func cleanPath(p string) string {24	// Turn empty string into "/"25	if p == "" {26		return "/"27	}2829	// Reasonably sized buffer on stack to avoid allocations in the common case.30	// If a larger buffer is required, it gets allocated dynamically.31	buf := make([]byte, 0, stackBufSize)3233	n := len(p)3435	// Invariants:36	//      reading from path; r is index of next byte to process.37	//      writing to buf; w is index of next byte to write.3839	// path must start with '/'40	r := 141	w := 14243	if p[0] != '/' {44		r = 04546		if n+1 > stackBufSize {47			buf = make([]byte, n+1)48		} else {49			buf = buf[:n+1]50		}51		buf[0] = '/'52	}5354	trailing := n > 1 && p[n-1] == '/'5556	// A bit more clunky without a 'lazybuf' like the path package, but the loop57	// gets completely inlined (bufApp calls).58	// So in contrast to the path package this loop has no expensive function59	// calls (except make, if needed).6061	for r < n {62		switch {63		case p[r] == '/':64			// empty path element, trailing slash is added after the end65			r++6667		case p[r] == '.' && r+1 == n:68			trailing = true69			r++7071		case p[r] == '.' && p[r+1] == '/':72			// . element73			r += 27475		case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'):76			// .. element: remove to last /77			r += 37879			if w > 1 {80				// can backtrack81				w--8283				if len(buf) == 0 {84					for w > 1 && p[w] != '/' {85						w--86					}87				} else {88					for w > 1 && buf[w] != '/' {89						w--90					}91				}92			}9394		default:95			// Real path element.96			// Add slash if needed97			if w > 1 {98				bufApp(&buf, p, w, '/')99				w++100			}101102			// Copy element103			for r < n && p[r] != '/' {104				bufApp(&buf, p, w, p[r])105				w++106				r++107			}108		}109	}110111	// Re-append trailing slash112	if trailing && w > 1 {113		bufApp(&buf, p, w, '/')114		w++115	}116117	// If the original string was not modified (or only shortened at the end),118	// return the respective substring of the original string.119	// Otherwise return a new string from the buffer.120	if len(buf) == 0 {121		return p[:w]122	}123	return string(buf[:w])124}125126// Internal helper to lazily create a buffer if necessary.127// Calls to this function get inlined.128func bufApp(buf *[]byte, s string, w int, c byte) {129	b := *buf130	if len(b) == 0 {131		// No modification of the original string so far.132		// If the next character is the same as in the original string, we do133		// not yet have to allocate a buffer.134		if s[w] == c {135			return136		}137138		// Otherwise use either the stack buffer, if it is large enough, or139		// allocate a new buffer on the heap, and copy all previous characters.140		length := len(s)141		if length > cap(b) {142			*buf = make([]byte, length)143		} else {144			*buf = (*buf)[:length]145		}146		b = *buf147148		copy(b, s[:w])149	}150	b[w] = c151}152153// removeRepeatedChar removes multiple consecutive 'char's from a string.154// if s == "/a//b///c////" && char == '/', it returns "/a/b/c/"155func removeRepeatedChar(s string, char byte) string {156	// Check if there are any consecutive chars157	hasRepeatedChar := false158	for i := 1; i < len(s); i++ {159		if s[i] == char && s[i-1] == char {160			hasRepeatedChar = true161			break162		}163	}164	if !hasRepeatedChar {165		return s166	}167168	// Reasonably sized buffer on stack to avoid allocations in the common case.169	buf := make([]byte, 0, stackBufSize)170171	// Invariants:172	//      reading from s; r is index of next byte to process.173	//      writing to buf; w is index of next byte to write.174	r := 0175	w := 0176177	for n := len(s); r < n; {178		if s[r] == char {179			// Write the first char180			bufApp(&buf, s, w, char)181			w++182			r++183184			// Skip all consecutive chars185			for r < n && s[r] == char {186				r++187			}188		} else {189			// Copy non-char character190			bufApp(&buf, s, w, s[r])191			w++192			r++193		}194	}195196	// If the original string was not modified (or only shortened at the end),197	// return the respective substring of the original string.198	// Otherwise, return a new string from the buffer.199	if len(buf) == 0 {200		return s[:w]201	}202	return string(buf[:w])203}