repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/mxk/go-flowrate/flowrate/util.go
vendor/github.com/mxk/go-flowrate/flowrate/util.go
// // Written by Maxim Khitrov (November 2012) // package flowrate import ( "math" "strconv" "time" ) // clockRate is the resolution and precision of clock(). const clockRate = 20 * time.Millisecond // czero is the process start time rounded down to the nearest clockRate // increment. var czero = time.Duration(time.Now().UnixNano()) / clockRate * clockRate // clock returns a low resolution timestamp relative to the process start time. func clock() time.Duration { return time.Duration(time.Now().UnixNano())/clockRate*clockRate - czero } // clockToTime converts a clock() timestamp to an absolute time.Time value. func clockToTime(c time.Duration) time.Time { return time.Unix(0, int64(czero+c)) } // clockRound returns d rounded to the nearest clockRate increment. func clockRound(d time.Duration) time.Duration { return (d + clockRate>>1) / clockRate * clockRate } // round returns x rounded to the nearest int64 (non-negative values only). func round(x float64) int64 { if _, frac := math.Modf(x); frac >= 0.5 { return int64(math.Ceil(x)) } return int64(math.Floor(x)) } // Percent represents a percentage in increments of 1/1000th of a percent. type Percent uint32 // percentOf calculates what percent of the total is x. func percentOf(x, total float64) Percent { if x < 0 || total <= 0 { return 0 } else if p := round(x / total * 1e5); p <= math.MaxUint32 { return Percent(p) } return Percent(math.MaxUint32) } func (p Percent) Float() float64 { return float64(p) * 1e-3 } func (p Percent) String() string { var buf [12]byte b := strconv.AppendUint(buf[:0], uint64(p)/1000, 10) n := len(b) b = strconv.AppendUint(b, 1000+uint64(p)%1000, 10) b[n] = '.' return string(append(b, '%')) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/mxk/go-flowrate/flowrate/io.go
vendor/github.com/mxk/go-flowrate/flowrate/io.go
// // Written by Maxim Khitrov (November 2012) // package flowrate import ( "errors" "io" ) // ErrLimit is returned by the Writer when a non-blocking write is short due to // the transfer rate limit. var ErrLimit = errors.New("flowrate: flow rate limit exceeded") // Limiter is implemented by the Reader and Writer to provide a consistent // interface for monitoring and controlling data transfer. type Limiter interface { Done() int64 Status() Status SetTransferSize(bytes int64) SetLimit(new int64) (old int64) SetBlocking(new bool) (old bool) } // Reader implements io.ReadCloser with a restriction on the rate of data // transfer. type Reader struct { io.Reader // Data source *Monitor // Flow control monitor limit int64 // Rate limit in bytes per second (unlimited when <= 0) block bool // What to do when no new bytes can be read due to the limit } // NewReader restricts all Read operations on r to limit bytes per second. func NewReader(r io.Reader, limit int64) *Reader { return &Reader{r, New(0, 0), limit, true} } // Read reads up to len(p) bytes into p without exceeding the current transfer // rate limit. It returns (0, nil) immediately if r is non-blocking and no new // bytes can be read at this time. func (r *Reader) Read(p []byte) (n int, err error) { p = p[:r.Limit(len(p), r.limit, r.block)] if len(p) > 0 { n, err = r.IO(r.Reader.Read(p)) } return } // SetLimit changes the transfer rate limit to new bytes per second and returns // the previous setting. func (r *Reader) SetLimit(new int64) (old int64) { old, r.limit = r.limit, new return } // SetBlocking changes the blocking behavior and returns the previous setting. A // Read call on a non-blocking reader returns immediately if no additional bytes // may be read at this time due to the rate limit. func (r *Reader) SetBlocking(new bool) (old bool) { old, r.block = r.block, new return } // Close closes the underlying reader if it implements the io.Closer interface. func (r *Reader) Close() error { defer r.Done() if c, ok := r.Reader.(io.Closer); ok { return c.Close() } return nil } // Writer implements io.WriteCloser with a restriction on the rate of data // transfer. type Writer struct { io.Writer // Data destination *Monitor // Flow control monitor limit int64 // Rate limit in bytes per second (unlimited when <= 0) block bool // What to do when no new bytes can be written due to the limit } // NewWriter restricts all Write operations on w to limit bytes per second. The // transfer rate and the default blocking behavior (true) can be changed // directly on the returned *Writer. func NewWriter(w io.Writer, limit int64) *Writer { return &Writer{w, New(0, 0), limit, true} } // Write writes len(p) bytes from p to the underlying data stream without // exceeding the current transfer rate limit. It returns (n, ErrLimit) if w is // non-blocking and no additional bytes can be written at this time. func (w *Writer) Write(p []byte) (n int, err error) { var c int for len(p) > 0 && err == nil { s := p[:w.Limit(len(p), w.limit, w.block)] if len(s) > 0 { c, err = w.IO(w.Writer.Write(s)) } else { return n, ErrLimit } p = p[c:] n += c } return } // SetLimit changes the transfer rate limit to new bytes per second and returns // the previous setting. func (w *Writer) SetLimit(new int64) (old int64) { old, w.limit = w.limit, new return } // SetBlocking changes the blocking behavior and returns the previous setting. A // Write call on a non-blocking writer returns as soon as no additional bytes // may be written at this time due to the rate limit. func (w *Writer) SetBlocking(new bool) (old bool) { old, w.block = w.block, new return } // Close closes the underlying writer if it implements the io.Closer interface. func (w *Writer) Close() error { defer w.Done() if c, ok := w.Writer.(io.Closer); ok { return c.Close() } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/deprecated.go
vendor/github.com/gin-gonic/gin/deprecated.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "log" "github.com/gin-gonic/gin/binding" ) // BindWith binds the passed struct pointer using the specified binding engine. // See the binding package. // // Deprecated: Use MustBindWith or ShouldBindWith. func (c *Context) BindWith(obj any, b binding.Binding) error { log.Println(`BindWith(\"any, binding.Binding\") error is going to be deprecated, please check issue #662 and either use MustBindWith() if you want HTTP 400 to be automatically returned if any error occur, or use ShouldBindWith() if you need to manage the error.`) return c.MustBindWith(obj, b) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/tree.go
vendor/github.com/gin-gonic/gin/tree.go
// Copyright 2013 Julien Schmidt. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found // at https://github.com/julienschmidt/httprouter/blob/master/LICENSE package gin import ( "bytes" "net/url" "strings" "unicode" "unicode/utf8" "github.com/gin-gonic/gin/internal/bytesconv" ) var ( strColon = []byte(":") strStar = []byte("*") strSlash = []byte("/") ) // Param is a single URL parameter, consisting of a key and a value. type Param struct { Key string Value string } // Params is a Param-slice, as returned by the router. // The slice is ordered, the first URL parameter is also the first slice value. // It is therefore safe to read values by the index. type Params []Param // Get returns the value of the first Param which key matches the given name and a boolean true. // If no matching Param is found, an empty string is returned and a boolean false . func (ps Params) Get(name string) (string, bool) { for _, entry := range ps { if entry.Key == name { return entry.Value, true } } return "", false } // ByName returns the value of the first Param which key matches the given name. // If no matching Param is found, an empty string is returned. func (ps Params) ByName(name string) (va string) { va, _ = ps.Get(name) return } type methodTree struct { method string root *node } type methodTrees []methodTree func (trees methodTrees) get(method string) *node { for _, tree := range trees { if tree.method == method { return tree.root } } return nil } func min(a, b int) int { if a <= b { return a } return b } func longestCommonPrefix(a, b string) int { i := 0 max := min(len(a), len(b)) for i < max && a[i] == b[i] { i++ } return i } // addChild will add a child node, keeping wildcardChild at the end func (n *node) addChild(child *node) { if n.wildChild && len(n.children) > 0 { wildcardChild := n.children[len(n.children)-1] n.children = append(n.children[:len(n.children)-1], child, wildcardChild) } else { n.children = append(n.children, child) } } func countParams(path string) uint16 { var n uint16 s := bytesconv.StringToBytes(path) n += uint16(bytes.Count(s, strColon)) n += uint16(bytes.Count(s, strStar)) return n } func countSections(path string) uint16 { s := bytesconv.StringToBytes(path) return uint16(bytes.Count(s, strSlash)) } type nodeType uint8 const ( static nodeType = iota root param catchAll ) type node struct { path string indices string wildChild bool nType nodeType priority uint32 children []*node // child nodes, at most 1 :param style node at the end of the array handlers HandlersChain fullPath string } // Increments priority of the given child and reorders if necessary func (n *node) incrementChildPrio(pos int) int { cs := n.children cs[pos].priority++ prio := cs[pos].priority // Adjust position (move to front) newPos := pos for ; newPos > 0 && cs[newPos-1].priority < prio; newPos-- { // Swap node positions cs[newPos-1], cs[newPos] = cs[newPos], cs[newPos-1] } // Build new index char string if newPos != pos { n.indices = n.indices[:newPos] + // Unchanged prefix, might be empty n.indices[pos:pos+1] + // The index char we move n.indices[newPos:pos] + n.indices[pos+1:] // Rest without char at 'pos' } return newPos } // addRoute adds a node with the given handle to the path. // Not concurrency-safe! func (n *node) addRoute(path string, handlers HandlersChain) { fullPath := path n.priority++ // Empty tree if len(n.path) == 0 && len(n.children) == 0 { n.insertChild(path, fullPath, handlers) n.nType = root return } parentFullPathIndex := 0 walk: for { // Find the longest common prefix. // This also implies that the common prefix contains no ':' or '*' // since the existing key can't contain those chars. i := longestCommonPrefix(path, n.path) // Split edge if i < len(n.path) { child := node{ path: n.path[i:], wildChild: n.wildChild, nType: static, indices: n.indices, children: n.children, handlers: n.handlers, priority: n.priority - 1, fullPath: n.fullPath, } n.children = []*node{&child} // []byte for proper unicode char conversion, see #65 n.indices = bytesconv.BytesToString([]byte{n.path[i]}) n.path = path[:i] n.handlers = nil n.wildChild = false n.fullPath = fullPath[:parentFullPathIndex+i] } // Make new node a child of this node if i < len(path) { path = path[i:] c := path[0] // '/' after param if n.nType == param && c == '/' && len(n.children) == 1 { parentFullPathIndex += len(n.path) n = n.children[0] n.priority++ continue walk } // Check if a child with the next path byte exists for i, max := 0, len(n.indices); i < max; i++ { if c == n.indices[i] { parentFullPathIndex += len(n.path) i = n.incrementChildPrio(i) n = n.children[i] continue walk } } // Otherwise insert it if c != ':' && c != '*' && n.nType != catchAll { // []byte for proper unicode char conversion, see #65 n.indices += bytesconv.BytesToString([]byte{c}) child := &node{ fullPath: fullPath, } n.addChild(child) n.incrementChildPrio(len(n.indices) - 1) n = child } else if n.wildChild { // inserting a wildcard node, need to check if it conflicts with the existing wildcard n = n.children[len(n.children)-1] n.priority++ // Check if the wildcard matches if len(path) >= len(n.path) && n.path == path[:len(n.path)] && // Adding a child to a catchAll is not possible n.nType != catchAll && // Check for longer wildcard, e.g. :name and :names (len(n.path) >= len(path) || path[len(n.path)] == '/') { continue walk } // Wildcard conflict pathSeg := path if n.nType != catchAll { pathSeg = strings.SplitN(pathSeg, "/", 2)[0] } prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.path panic("'" + pathSeg + "' in new path '" + fullPath + "' conflicts with existing wildcard '" + n.path + "' in existing prefix '" + prefix + "'") } n.insertChild(path, fullPath, handlers) return } // Otherwise add handle to current node if n.handlers != nil { panic("handlers are already registered for path '" + fullPath + "'") } n.handlers = handlers n.fullPath = fullPath return } } // Search for a wildcard segment and check the name for invalid characters. // Returns -1 as index, if no wildcard was found. func findWildcard(path string) (wildcard string, i int, valid bool) { // Find start for start, c := range []byte(path) { // A wildcard starts with ':' (param) or '*' (catch-all) if c != ':' && c != '*' { continue } // Find end and check for invalid characters valid = true for end, c := range []byte(path[start+1:]) { switch c { case '/': return path[start : start+1+end], start, valid case ':', '*': valid = false } } return path[start:], start, valid } return "", -1, false } func (n *node) insertChild(path string, fullPath string, handlers HandlersChain) { for { // Find prefix until first wildcard wildcard, i, valid := findWildcard(path) if i < 0 { // No wildcard found break } // The wildcard name must only contain one ':' or '*' character if !valid { panic("only one wildcard per path segment is allowed, has: '" + wildcard + "' in path '" + fullPath + "'") } // check if the wildcard has a name if len(wildcard) < 2 { panic("wildcards must be named with a non-empty name in path '" + fullPath + "'") } if wildcard[0] == ':' { // param if i > 0 { // Insert prefix before the current wildcard n.path = path[:i] path = path[i:] } child := &node{ nType: param, path: wildcard, fullPath: fullPath, } n.addChild(child) n.wildChild = true n = child n.priority++ // if the path doesn't end with the wildcard, then there // will be another subpath starting with '/' if len(wildcard) < len(path) { path = path[len(wildcard):] child := &node{ priority: 1, fullPath: fullPath, } n.addChild(child) n = child continue } // Otherwise we're done. Insert the handle in the new leaf n.handlers = handlers return } // catchAll if i+len(wildcard) != len(path) { panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'") } if len(n.path) > 0 && n.path[len(n.path)-1] == '/' { pathSeg := "" if len(n.children) != 0 { pathSeg = strings.SplitN(n.children[0].path, "/", 2)[0] } panic("catch-all wildcard '" + path + "' in new path '" + fullPath + "' conflicts with existing path segment '" + pathSeg + "' in existing prefix '" + n.path + pathSeg + "'") } // currently fixed width 1 for '/' i-- if path[i] != '/' { panic("no / before catch-all in path '" + fullPath + "'") } n.path = path[:i] // First node: catchAll node with empty path child := &node{ wildChild: true, nType: catchAll, fullPath: fullPath, } n.addChild(child) n.indices = string('/') n = child n.priority++ // second node: node holding the variable child = &node{ path: path[i:], nType: catchAll, handlers: handlers, priority: 1, fullPath: fullPath, } n.children = []*node{child} return } // If no wildcard was found, simply insert the path and handle n.path = path n.handlers = handlers n.fullPath = fullPath } // nodeValue holds return values of (*Node).getValue method type nodeValue struct { handlers HandlersChain params *Params tsr bool fullPath string } type skippedNode struct { path string node *node paramsCount int16 } // Returns the handle registered with the given path (key). The values of // wildcards are saved to a map. // If no handle can be found, a TSR (trailing slash redirect) recommendation is // made if a handle exists with an extra (without the) trailing slash for the // given path. func (n *node) getValue(path string, params *Params, skippedNodes *[]skippedNode, unescape bool) (value nodeValue) { var globalParamsCount int16 walk: // Outer loop for walking the tree for { prefix := n.path if len(path) > len(prefix) { if path[:len(prefix)] == prefix { path = path[len(prefix):] // Try all the non-wildcard children first by matching the indices idxc := path[0] for i, c := range []byte(n.indices) { if c == idxc { // strings.HasPrefix(n.children[len(n.children)-1].path, ":") == n.wildChild if n.wildChild { index := len(*skippedNodes) *skippedNodes = (*skippedNodes)[:index+1] (*skippedNodes)[index] = skippedNode{ path: prefix + path, node: &node{ path: n.path, wildChild: n.wildChild, nType: n.nType, priority: n.priority, children: n.children, handlers: n.handlers, fullPath: n.fullPath, }, paramsCount: globalParamsCount, } } n = n.children[i] continue walk } } if !n.wildChild { // If the path at the end of the loop is not equal to '/' and the current node has no child nodes // the current node needs to roll back to last valid skippedNode if path != "/" { for length := len(*skippedNodes); length > 0; length-- { skippedNode := (*skippedNodes)[length-1] *skippedNodes = (*skippedNodes)[:length-1] if strings.HasSuffix(skippedNode.path, path) { path = skippedNode.path n = skippedNode.node if value.params != nil { *value.params = (*value.params)[:skippedNode.paramsCount] } globalParamsCount = skippedNode.paramsCount continue walk } } } // Nothing found. // We can recommend to redirect to the same URL without a // trailing slash if a leaf exists for that path. value.tsr = path == "/" && n.handlers != nil return value } // Handle wildcard child, which is always at the end of the array n = n.children[len(n.children)-1] globalParamsCount++ switch n.nType { case param: // fix truncate the parameter // tree_test.go line: 204 // Find param end (either '/' or path end) end := 0 for end < len(path) && path[end] != '/' { end++ } // Save param value if params != nil { // Preallocate capacity if necessary if cap(*params) < int(globalParamsCount) { newParams := make(Params, len(*params), globalParamsCount) copy(newParams, *params) *params = newParams } if value.params == nil { value.params = params } // Expand slice within preallocated capacity i := len(*value.params) *value.params = (*value.params)[:i+1] val := path[:end] if unescape { if v, err := url.QueryUnescape(val); err == nil { val = v } } (*value.params)[i] = Param{ Key: n.path[1:], Value: val, } } // we need to go deeper! if end < len(path) { if len(n.children) > 0 { path = path[end:] n = n.children[0] continue walk } // ... but we can't value.tsr = len(path) == end+1 return value } if value.handlers = n.handlers; value.handlers != nil { value.fullPath = n.fullPath return value } if len(n.children) == 1 { // No handle found. Check if a handle for this path + a // trailing slash exists for TSR recommendation n = n.children[0] value.tsr = (n.path == "/" && n.handlers != nil) || (n.path == "" && n.indices == "/") } return value case catchAll: // Save param value if params != nil { // Preallocate capacity if necessary if cap(*params) < int(globalParamsCount) { newParams := make(Params, len(*params), globalParamsCount) copy(newParams, *params) *params = newParams } if value.params == nil { value.params = params } // Expand slice within preallocated capacity i := len(*value.params) *value.params = (*value.params)[:i+1] val := path if unescape { if v, err := url.QueryUnescape(path); err == nil { val = v } } (*value.params)[i] = Param{ Key: n.path[2:], Value: val, } } value.handlers = n.handlers value.fullPath = n.fullPath return value default: panic("invalid node type") } } } if path == prefix { // If the current path does not equal '/' and the node does not have a registered handle and the most recently matched node has a child node // the current node needs to roll back to last valid skippedNode if n.handlers == nil && path != "/" { for length := len(*skippedNodes); length > 0; length-- { skippedNode := (*skippedNodes)[length-1] *skippedNodes = (*skippedNodes)[:length-1] if strings.HasSuffix(skippedNode.path, path) { path = skippedNode.path n = skippedNode.node if value.params != nil { *value.params = (*value.params)[:skippedNode.paramsCount] } globalParamsCount = skippedNode.paramsCount continue walk } } // n = latestNode.children[len(latestNode.children)-1] } // We should have reached the node containing the handle. // Check if this node has a handle registered. if value.handlers = n.handlers; value.handlers != nil { value.fullPath = n.fullPath return value } // If there is no handle for this route, but this route has a // wildcard child, there must be a handle for this path with an // additional trailing slash if path == "/" && n.wildChild && n.nType != root { value.tsr = true return value } if path == "/" && n.nType == static { value.tsr = true return value } // No handle found. Check if a handle for this path + a // trailing slash exists for trailing slash recommendation for i, c := range []byte(n.indices) { if c == '/' { n = n.children[i] value.tsr = (len(n.path) == 1 && n.handlers != nil) || (n.nType == catchAll && n.children[0].handlers != nil) return value } } return value } // Nothing found. We can recommend to redirect to the same URL with an // extra trailing slash if a leaf exists for that path value.tsr = path == "/" || (len(prefix) == len(path)+1 && prefix[len(path)] == '/' && path == prefix[:len(prefix)-1] && n.handlers != nil) // roll back to last valid skippedNode if !value.tsr && path != "/" { for length := len(*skippedNodes); length > 0; length-- { skippedNode := (*skippedNodes)[length-1] *skippedNodes = (*skippedNodes)[:length-1] if strings.HasSuffix(skippedNode.path, path) { path = skippedNode.path n = skippedNode.node if value.params != nil { *value.params = (*value.params)[:skippedNode.paramsCount] } globalParamsCount = skippedNode.paramsCount continue walk } } } return value } } // Makes a case-insensitive lookup of the given path and tries to find a handler. // It can optionally also fix trailing slashes. // It returns the case-corrected path and a bool indicating whether the lookup // was successful. func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) ([]byte, bool) { const stackBufSize = 128 // Use a static sized buffer on the stack in the common case. // If the path is too long, allocate a buffer on the heap instead. buf := make([]byte, 0, stackBufSize) if length := len(path) + 1; length > stackBufSize { buf = make([]byte, 0, length) } ciPath := n.findCaseInsensitivePathRec( path, buf, // Preallocate enough memory for new path [4]byte{}, // Empty rune buffer fixTrailingSlash, ) return ciPath, ciPath != nil } // Shift bytes in array by n bytes left func shiftNRuneBytes(rb [4]byte, n int) [4]byte { switch n { case 0: return rb case 1: return [4]byte{rb[1], rb[2], rb[3], 0} case 2: return [4]byte{rb[2], rb[3]} case 3: return [4]byte{rb[3]} default: return [4]byte{} } } // Recursive case-insensitive lookup function used by n.findCaseInsensitivePath func (n *node) findCaseInsensitivePathRec(path string, ciPath []byte, rb [4]byte, fixTrailingSlash bool) []byte { npLen := len(n.path) walk: // Outer loop for walking the tree for len(path) >= npLen && (npLen == 0 || strings.EqualFold(path[1:npLen], n.path[1:])) { // Add common prefix to result oldPath := path path = path[npLen:] ciPath = append(ciPath, n.path...) if len(path) == 0 { // We should have reached the node containing the handle. // Check if this node has a handle registered. if n.handlers != nil { return ciPath } // No handle found. // Try to fix the path by adding a trailing slash if fixTrailingSlash { for i, c := range []byte(n.indices) { if c == '/' { n = n.children[i] if (len(n.path) == 1 && n.handlers != nil) || (n.nType == catchAll && n.children[0].handlers != nil) { return append(ciPath, '/') } return nil } } } return nil } // If this node does not have a wildcard (param or catchAll) child, // we can just look up the next child node and continue to walk down // the tree if !n.wildChild { // Skip rune bytes already processed rb = shiftNRuneBytes(rb, npLen) if rb[0] != 0 { // Old rune not finished idxc := rb[0] for i, c := range []byte(n.indices) { if c == idxc { // continue with child node n = n.children[i] npLen = len(n.path) continue walk } } } else { // Process a new rune var rv rune // Find rune start. // Runes are up to 4 byte long, // -4 would definitely be another rune. var off int for max := min(npLen, 3); off < max; off++ { if i := npLen - off; utf8.RuneStart(oldPath[i]) { // read rune from cached path rv, _ = utf8.DecodeRuneInString(oldPath[i:]) break } } // Calculate lowercase bytes of current rune lo := unicode.ToLower(rv) utf8.EncodeRune(rb[:], lo) // Skip already processed bytes rb = shiftNRuneBytes(rb, off) idxc := rb[0] for i, c := range []byte(n.indices) { // Lowercase matches if c == idxc { // must use a recursive approach since both the // uppercase byte and the lowercase byte might exist // as an index if out := n.children[i].findCaseInsensitivePathRec( path, ciPath, rb, fixTrailingSlash, ); out != nil { return out } break } } // If we found no match, the same for the uppercase rune, // if it differs if up := unicode.ToUpper(rv); up != lo { utf8.EncodeRune(rb[:], up) rb = shiftNRuneBytes(rb, off) idxc := rb[0] for i, c := range []byte(n.indices) { // Uppercase matches if c == idxc { // Continue with child node n = n.children[i] npLen = len(n.path) continue walk } } } } // Nothing found. We can recommend to redirect to the same URL // without a trailing slash if a leaf exists for that path if fixTrailingSlash && path == "/" && n.handlers != nil { return ciPath } return nil } n = n.children[0] switch n.nType { case param: // Find param end (either '/' or path end) end := 0 for end < len(path) && path[end] != '/' { end++ } // Add param value to case insensitive path ciPath = append(ciPath, path[:end]...) // We need to go deeper! if end < len(path) { if len(n.children) > 0 { // Continue with child node n = n.children[0] npLen = len(n.path) path = path[end:] continue } // ... but we can't if fixTrailingSlash && len(path) == end+1 { return ciPath } return nil } if n.handlers != nil { return ciPath } if fixTrailingSlash && len(n.children) == 1 { // No handle found. Check if a handle for this path + a // trailing slash exists n = n.children[0] if n.path == "/" && n.handlers != nil { return append(ciPath, '/') } } return nil case catchAll: return append(ciPath, path...) default: panic("invalid node type") } } // Nothing found. // Try to fix the path by adding / removing a trailing slash if fixTrailingSlash { if path == "/" { return ciPath } if len(path)+1 == npLen && n.path[len(path)] == '/' && strings.EqualFold(path[1:], n.path[1:len(path)]) && n.handlers != nil { return append(ciPath, n.path...) } } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/test_helpers.go
vendor/github.com/gin-gonic/gin/test_helpers.go
// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import "net/http" // CreateTestContext returns a fresh engine and context for testing purposes func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) { r = New() c = r.allocateContext(0) c.reset() c.writermem.reset(w) return } // CreateTestContextOnly returns a fresh context base on the engine for testing purposes func CreateTestContextOnly(w http.ResponseWriter, r *Engine) (c *Context) { c = r.allocateContext(r.maxParams) c.reset() c.writermem.reset(w) return }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/path.go
vendor/github.com/gin-gonic/gin/path.go
// Copyright 2013 Julien Schmidt. All rights reserved. // Based on the path package, Copyright 2009 The Go Authors. // Use of this source code is governed by a BSD-style license that can be found // at https://github.com/julienschmidt/httprouter/blob/master/LICENSE. package gin // cleanPath is the URL version of path.Clean, it returns a canonical URL path // for p, eliminating . and .. elements. // // The following rules are applied iteratively until no further processing can // be done: // 1. Replace multiple slashes with a single slash. // 2. Eliminate each . path name element (the current directory). // 3. Eliminate each inner .. path name element (the parent directory) // along with the non-.. element that precedes it. // 4. Eliminate .. elements that begin a rooted path: // that is, replace "/.." by "/" at the beginning of a path. // // If the result of this process is an empty string, "/" is returned. func cleanPath(p string) string { const stackBufSize = 128 // Turn empty string into "/" if p == "" { return "/" } // Reasonably sized buffer on stack to avoid allocations in the common case. // If a larger buffer is required, it gets allocated dynamically. buf := make([]byte, 0, stackBufSize) n := len(p) // Invariants: // reading from path; r is index of next byte to process. // writing to buf; w is index of next byte to write. // path must start with '/' r := 1 w := 1 if p[0] != '/' { r = 0 if n+1 > stackBufSize { buf = make([]byte, n+1) } else { buf = buf[:n+1] } buf[0] = '/' } trailing := n > 1 && p[n-1] == '/' // A bit more clunky without a 'lazybuf' like the path package, but the loop // gets completely inlined (bufApp calls). // loop has no expensive function calls (except 1x make) // So in contrast to the path package this loop has no expensive function // calls (except make, if needed). for r < n { switch { case p[r] == '/': // empty path element, trailing slash is added after the end r++ case p[r] == '.' && r+1 == n: trailing = true r++ case p[r] == '.' && p[r+1] == '/': // . element r += 2 case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'): // .. element: remove to last / r += 3 if w > 1 { // can backtrack w-- if len(buf) == 0 { for w > 1 && p[w] != '/' { w-- } } else { for w > 1 && buf[w] != '/' { w-- } } } default: // Real path element. // Add slash if needed if w > 1 { bufApp(&buf, p, w, '/') w++ } // Copy element for r < n && p[r] != '/' { bufApp(&buf, p, w, p[r]) w++ r++ } } } // Re-append trailing slash if trailing && w > 1 { bufApp(&buf, p, w, '/') w++ } // If the original string was not modified (or only shortened at the end), // return the respective substring of the original string. // Otherwise return a new string from the buffer. if len(buf) == 0 { return p[:w] } return string(buf[:w]) } // Internal helper to lazily create a buffer if necessary. // Calls to this function get inlined. func bufApp(buf *[]byte, s string, w int, c byte) { b := *buf if len(b) == 0 { // No modification of the original string so far. // If the next character is the same as in the original string, we do // not yet have to allocate a buffer. if s[w] == c { return } // Otherwise use either the stack buffer, if it is large enough, or // allocate a new buffer on the heap, and copy all previous characters. length := len(s) if length > cap(b) { *buf = make([]byte, length) } else { *buf = (*buf)[:length] } b = *buf copy(b, s[:w]) } b[w] = c }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/recovery.go
vendor/github.com/gin-gonic/gin/recovery.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "errors" "fmt" "io" "log" "net" "net/http" "net/http/httputil" "os" "runtime" "strings" "time" ) var ( dunno = []byte("???") centerDot = []byte("·") dot = []byte(".") slash = []byte("/") ) // RecoveryFunc defines the function passable to CustomRecovery. type RecoveryFunc func(c *Context, err any) // Recovery returns a middleware that recovers from any panics and writes a 500 if there was one. func Recovery() HandlerFunc { return RecoveryWithWriter(DefaultErrorWriter) } // CustomRecovery returns a middleware that recovers from any panics and calls the provided handle func to handle it. func CustomRecovery(handle RecoveryFunc) HandlerFunc { return RecoveryWithWriter(DefaultErrorWriter, handle) } // RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one. func RecoveryWithWriter(out io.Writer, recovery ...RecoveryFunc) HandlerFunc { if len(recovery) > 0 { return CustomRecoveryWithWriter(out, recovery[0]) } return CustomRecoveryWithWriter(out, defaultHandleRecovery) } // CustomRecoveryWithWriter returns a middleware for a given writer that recovers from any panics and calls the provided handle func to handle it. func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc { var logger *log.Logger if out != nil { logger = log.New(out, "\n\n\x1b[31m", log.LstdFlags) } return func(c *Context) { defer func() { if err := recover(); err != nil { // Check for a broken connection, as it is not really a // condition that warrants a panic stack trace. var brokenPipe bool if ne, ok := err.(*net.OpError); ok { var se *os.SyscallError if errors.As(ne, &se) { seStr := strings.ToLower(se.Error()) if strings.Contains(seStr, "broken pipe") || strings.Contains(seStr, "connection reset by peer") { brokenPipe = true } } } if logger != nil { stack := stack(3) httpRequest, _ := httputil.DumpRequest(c.Request, false) headers := strings.Split(string(httpRequest), "\r\n") for idx, header := range headers { current := strings.Split(header, ":") if current[0] == "Authorization" { headers[idx] = current[0] + ": *" } } headersToStr := strings.Join(headers, "\r\n") if brokenPipe { logger.Printf("%s\n%s%s", err, headersToStr, reset) } else if IsDebugging() { logger.Printf("[Recovery] %s panic recovered:\n%s\n%s\n%s%s", timeFormat(time.Now()), headersToStr, err, stack, reset) } else { logger.Printf("[Recovery] %s panic recovered:\n%s\n%s%s", timeFormat(time.Now()), err, stack, reset) } } if brokenPipe { // If the connection is dead, we can't write a status to it. c.Error(err.(error)) //nolint: errcheck c.Abort() } else { handle(c, err) } } }() c.Next() } } func defaultHandleRecovery(c *Context, _ any) { c.AbortWithStatus(http.StatusInternalServerError) } // stack returns a nicely formatted stack frame, skipping skip frames. func stack(skip int) []byte { buf := new(bytes.Buffer) // the returned data // As we loop, we open files and read them. These variables record the currently // loaded file. var lines [][]byte var lastFile string for i := skip; ; i++ { // Skip the expected number of frames pc, file, line, ok := runtime.Caller(i) if !ok { break } // Print this much at least. If we can't find the source, it won't show. fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc) if file != lastFile { data, err := os.ReadFile(file) if err != nil { continue } lines = bytes.Split(data, []byte{'\n'}) lastFile = file } fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line)) } return buf.Bytes() } // source returns a space-trimmed slice of the n'th line. func source(lines [][]byte, n int) []byte { n-- // in stack trace, lines are 1-indexed but our array is 0-indexed if n < 0 || n >= len(lines) { return dunno } return bytes.TrimSpace(lines[n]) } // function returns, if possible, the name of the function containing the PC. func function(pc uintptr) []byte { fn := runtime.FuncForPC(pc) if fn == nil { return dunno } name := []byte(fn.Name()) // The name includes the path name to the package, which is unnecessary // since the file name is already included. Plus, it has center dots. // That is, we see // runtime/debug.*T·ptrmethod // and want // *T.ptrmethod // Also the package path might contain dot (e.g. code.google.com/...), // so first eliminate the path prefix if lastSlash := bytes.LastIndex(name, slash); lastSlash >= 0 { name = name[lastSlash+1:] } if period := bytes.Index(name, dot); period >= 0 { name = name[period+1:] } name = bytes.ReplaceAll(name, centerDot, dot) return name } // timeFormat returns a customized time string for logger. func timeFormat(t time.Time) string { return t.Format("2006/01/02 - 15:04:05") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/errors.go
vendor/github.com/gin-gonic/gin/errors.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "reflect" "strings" "github.com/gin-gonic/gin/internal/json" ) // ErrorType is an unsigned 64-bit error code as defined in the gin spec. type ErrorType uint64 const ( // ErrorTypeBind is used when Context.Bind() fails. ErrorTypeBind ErrorType = 1 << 63 // ErrorTypeRender is used when Context.Render() fails. ErrorTypeRender ErrorType = 1 << 62 // ErrorTypePrivate indicates a private error. ErrorTypePrivate ErrorType = 1 << 0 // ErrorTypePublic indicates a public error. ErrorTypePublic ErrorType = 1 << 1 // ErrorTypeAny indicates any other error. ErrorTypeAny ErrorType = 1<<64 - 1 // ErrorTypeNu indicates any other error. ErrorTypeNu = 2 ) // Error represents a error's specification. type Error struct { Err error Type ErrorType Meta any } type errorMsgs []*Error var _ error = (*Error)(nil) // SetType sets the error's type. func (msg *Error) SetType(flags ErrorType) *Error { msg.Type = flags return msg } // SetMeta sets the error's meta data. func (msg *Error) SetMeta(data any) *Error { msg.Meta = data return msg } // JSON creates a properly formatted JSON func (msg *Error) JSON() any { jsonData := H{} if msg.Meta != nil { value := reflect.ValueOf(msg.Meta) switch value.Kind() { case reflect.Struct: return msg.Meta case reflect.Map: for _, key := range value.MapKeys() { jsonData[key.String()] = value.MapIndex(key).Interface() } default: jsonData["meta"] = msg.Meta } } if _, ok := jsonData["error"]; !ok { jsonData["error"] = msg.Error() } return jsonData } // MarshalJSON implements the json.Marshaller interface. func (msg *Error) MarshalJSON() ([]byte, error) { return json.Marshal(msg.JSON()) } // Error implements the error interface. func (msg Error) Error() string { return msg.Err.Error() } // IsType judges one error. func (msg *Error) IsType(flags ErrorType) bool { return (msg.Type & flags) > 0 } // Unwrap returns the wrapped error, to allow interoperability with errors.Is(), errors.As() and errors.Unwrap() func (msg *Error) Unwrap() error { return msg.Err } // ByType returns a readonly copy filtered the byte. // ie ByType(gin.ErrorTypePublic) returns a slice of errors with type=ErrorTypePublic. func (a errorMsgs) ByType(typ ErrorType) errorMsgs { if len(a) == 0 { return nil } if typ == ErrorTypeAny { return a } var result errorMsgs for _, msg := range a { if msg.IsType(typ) { result = append(result, msg) } } return result } // Last returns the last error in the slice. It returns nil if the array is empty. // Shortcut for errors[len(errors)-1]. func (a errorMsgs) Last() *Error { if length := len(a); length > 0 { return a[length-1] } return nil } // Errors returns an array with all the error messages. // Example: // // c.Error(errors.New("first")) // c.Error(errors.New("second")) // c.Error(errors.New("third")) // c.Errors.Errors() // == []string{"first", "second", "third"} func (a errorMsgs) Errors() []string { if len(a) == 0 { return nil } errorStrings := make([]string, len(a)) for i, err := range a { errorStrings[i] = err.Error() } return errorStrings } func (a errorMsgs) JSON() any { switch length := len(a); length { case 0: return nil case 1: return a.Last().JSON() default: jsonData := make([]any, length) for i, err := range a { jsonData[i] = err.JSON() } return jsonData } } // MarshalJSON implements the json.Marshaller interface. func (a errorMsgs) MarshalJSON() ([]byte, error) { return json.Marshal(a.JSON()) } func (a errorMsgs) String() string { if len(a) == 0 { return "" } var buffer strings.Builder for i, msg := range a { fmt.Fprintf(&buffer, "Error #%02d: %s\n", i+1, msg.Err) if msg.Meta != nil { fmt.Fprintf(&buffer, " Meta: %v\n", msg.Meta) } } return buffer.String() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/utils.go
vendor/github.com/gin-gonic/gin/utils.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "encoding/xml" "net/http" "os" "path" "reflect" "runtime" "strings" "unicode" ) // BindKey indicates a default bind key. const BindKey = "_gin-gonic/gin/bindkey" // Bind is a helper function for given interface object and returns a Gin middleware. func Bind(val any) HandlerFunc { value := reflect.ValueOf(val) if value.Kind() == reflect.Ptr { panic(`Bind struct can not be a pointer. Example: Use: gin.Bind(Struct{}) instead of gin.Bind(&Struct{}) `) } typ := value.Type() return func(c *Context) { obj := reflect.New(typ).Interface() if c.Bind(obj) == nil { c.Set(BindKey, obj) } } } // WrapF is a helper function for wrapping http.HandlerFunc and returns a Gin middleware. func WrapF(f http.HandlerFunc) HandlerFunc { return func(c *Context) { f(c.Writer, c.Request) } } // WrapH is a helper function for wrapping http.Handler and returns a Gin middleware. func WrapH(h http.Handler) HandlerFunc { return func(c *Context) { h.ServeHTTP(c.Writer, c.Request) } } // H is a shortcut for map[string]any type H map[string]any // MarshalXML allows type H to be used with xml.Marshal. func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error { start.Name = xml.Name{ Space: "", Local: "map", } if err := e.EncodeToken(start); err != nil { return err } for key, value := range h { elem := xml.StartElement{ Name: xml.Name{Space: "", Local: key}, Attr: []xml.Attr{}, } if err := e.EncodeElement(value, elem); err != nil { return err } } return e.EncodeToken(xml.EndElement{Name: start.Name}) } func assert1(guard bool, text string) { if !guard { panic(text) } } func filterFlags(content string) string { for i, char := range content { if char == ' ' || char == ';' { return content[:i] } } return content } func chooseData(custom, wildcard any) any { if custom != nil { return custom } if wildcard != nil { return wildcard } panic("negotiation config is invalid") } func parseAccept(acceptHeader string) []string { parts := strings.Split(acceptHeader, ",") out := make([]string, 0, len(parts)) for _, part := range parts { if i := strings.IndexByte(part, ';'); i > 0 { part = part[:i] } if part = strings.TrimSpace(part); part != "" { out = append(out, part) } } return out } func lastChar(str string) uint8 { if str == "" { panic("The length of the string can't be 0") } return str[len(str)-1] } func nameOfFunction(f any) string { return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name() } func joinPaths(absolutePath, relativePath string) string { if relativePath == "" { return absolutePath } finalPath := path.Join(absolutePath, relativePath) if lastChar(relativePath) == '/' && lastChar(finalPath) != '/' { return finalPath + "/" } return finalPath } func resolveAddress(addr []string) string { switch len(addr) { case 0: if port := os.Getenv("PORT"); port != "" { debugPrint("Environment variable PORT=\"%s\"", port) return ":" + port } debugPrint("Environment variable PORT is undefined. Using port :8080 by default") return ":8080" case 1: return addr[0] default: panic("too many parameters") } } // https://stackoverflow.com/questions/53069040/checking-a-string-contains-only-ascii-characters func isASCII(s string) bool { for i := 0; i < len(s); i++ { if s[i] > unicode.MaxASCII { return false } } return true }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/routergroup.go
vendor/github.com/gin-gonic/gin/routergroup.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "net/http" "path" "regexp" "strings" ) var ( // regEnLetter matches english letters for http method name regEnLetter = regexp.MustCompile("^[A-Z]+$") // anyMethods for RouterGroup Any method anyMethods = []string{ http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodHead, http.MethodOptions, http.MethodDelete, http.MethodConnect, http.MethodTrace, } ) // IRouter defines all router handle interface includes single and group router. type IRouter interface { IRoutes Group(string, ...HandlerFunc) *RouterGroup } // IRoutes defines all router handle interface. type IRoutes interface { Use(...HandlerFunc) IRoutes Handle(string, string, ...HandlerFunc) IRoutes Any(string, ...HandlerFunc) IRoutes GET(string, ...HandlerFunc) IRoutes POST(string, ...HandlerFunc) IRoutes DELETE(string, ...HandlerFunc) IRoutes PATCH(string, ...HandlerFunc) IRoutes PUT(string, ...HandlerFunc) IRoutes OPTIONS(string, ...HandlerFunc) IRoutes HEAD(string, ...HandlerFunc) IRoutes Match([]string, string, ...HandlerFunc) IRoutes StaticFile(string, string) IRoutes StaticFileFS(string, string, http.FileSystem) IRoutes Static(string, string) IRoutes StaticFS(string, http.FileSystem) IRoutes } // RouterGroup is used internally to configure router, a RouterGroup is associated with // a prefix and an array of handlers (middleware). type RouterGroup struct { Handlers HandlersChain basePath string engine *Engine root bool } var _ IRouter = (*RouterGroup)(nil) // Use adds middleware to the group, see example code in GitHub. func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes { group.Handlers = append(group.Handlers, middleware...) return group.returnObj() } // Group creates a new router group. You should add all the routes that have common middlewares or the same path prefix. // For example, all the routes that use a common middleware for authorization could be grouped. func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup { return &RouterGroup{ Handlers: group.combineHandlers(handlers), basePath: group.calculateAbsolutePath(relativePath), engine: group.engine, } } // BasePath returns the base path of router group. // For example, if v := router.Group("/rest/n/v1/api"), v.BasePath() is "/rest/n/v1/api". func (group *RouterGroup) BasePath() string { return group.basePath } func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes { absolutePath := group.calculateAbsolutePath(relativePath) handlers = group.combineHandlers(handlers) group.engine.addRoute(httpMethod, absolutePath, handlers) return group.returnObj() } // Handle registers a new request handle and middleware with the given path and method. // The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes. // See the example code in GitHub. // // For GET, POST, PUT, PATCH and DELETE requests the respective shortcut // functions can be used. // // This function is intended for bulk loading and to allow the usage of less // frequently used, non-standardized or custom methods (e.g. for internal // communication with a proxy). func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes { if matched := regEnLetter.MatchString(httpMethod); !matched { panic("http method " + httpMethod + " is not valid") } return group.handle(httpMethod, relativePath, handlers) } // POST is a shortcut for router.Handle("POST", path, handlers). func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodPost, relativePath, handlers) } // GET is a shortcut for router.Handle("GET", path, handlers). func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodGet, relativePath, handlers) } // DELETE is a shortcut for router.Handle("DELETE", path, handlers). func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodDelete, relativePath, handlers) } // PATCH is a shortcut for router.Handle("PATCH", path, handlers). func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodPatch, relativePath, handlers) } // PUT is a shortcut for router.Handle("PUT", path, handlers). func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodPut, relativePath, handlers) } // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handlers). func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodOptions, relativePath, handlers) } // HEAD is a shortcut for router.Handle("HEAD", path, handlers). func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodHead, relativePath, handlers) } // Any registers a route that matches all the HTTP methods. // GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE. func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes { for _, method := range anyMethods { group.handle(method, relativePath, handlers) } return group.returnObj() } // Match registers a route that matches the specified methods that you declared. func (group *RouterGroup) Match(methods []string, relativePath string, handlers ...HandlerFunc) IRoutes { for _, method := range methods { group.handle(method, relativePath, handlers) } return group.returnObj() } // StaticFile registers a single route in order to serve a single file of the local filesystem. // router.StaticFile("favicon.ico", "./resources/favicon.ico") func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes { return group.staticFileHandler(relativePath, func(c *Context) { c.File(filepath) }) } // StaticFileFS works just like `StaticFile` but a custom `http.FileSystem` can be used instead.. // router.StaticFileFS("favicon.ico", "./resources/favicon.ico", Dir{".", false}) // Gin by default uses: gin.Dir() func (group *RouterGroup) StaticFileFS(relativePath, filepath string, fs http.FileSystem) IRoutes { return group.staticFileHandler(relativePath, func(c *Context) { c.FileFromFS(filepath, fs) }) } func (group *RouterGroup) staticFileHandler(relativePath string, handler HandlerFunc) IRoutes { if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") { panic("URL parameters can not be used when serving a static file") } group.GET(relativePath, handler) group.HEAD(relativePath, handler) return group.returnObj() } // Static serves files from the given file system root. // Internally a http.FileServer is used, therefore http.NotFound is used instead // of the Router's NotFound handler. // To use the operating system's file system implementation, // use : // // router.Static("/static", "/var/www") func (group *RouterGroup) Static(relativePath, root string) IRoutes { return group.StaticFS(relativePath, Dir(root, false)) } // StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead. // Gin by default uses: gin.Dir() func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes { if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") { panic("URL parameters can not be used when serving a static folder") } handler := group.createStaticHandler(relativePath, fs) urlPattern := path.Join(relativePath, "/*filepath") // Register GET and HEAD handlers group.GET(urlPattern, handler) group.HEAD(urlPattern, handler) return group.returnObj() } func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc { absolutePath := group.calculateAbsolutePath(relativePath) fileServer := http.StripPrefix(absolutePath, http.FileServer(fs)) return func(c *Context) { if _, noListing := fs.(*onlyFilesFS); noListing { c.Writer.WriteHeader(http.StatusNotFound) } file := c.Param("filepath") // Check if file exists and/or if we have permission to access it f, err := fs.Open(file) if err != nil { c.Writer.WriteHeader(http.StatusNotFound) c.handlers = group.engine.noRoute // Reset index c.index = -1 return } f.Close() fileServer.ServeHTTP(c.Writer, c.Request) } } func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain { finalSize := len(group.Handlers) + len(handlers) assert1(finalSize < int(abortIndex), "too many handlers") mergedHandlers := make(HandlersChain, finalSize) copy(mergedHandlers, group.Handlers) copy(mergedHandlers[len(group.Handlers):], handlers) return mergedHandlers } func (group *RouterGroup) calculateAbsolutePath(relativePath string) string { return joinPaths(group.basePath, relativePath) } func (group *RouterGroup) returnObj() IRoutes { if group.root { return group.engine } return group }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/mode.go
vendor/github.com/gin-gonic/gin/mode.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "flag" "io" "os" "github.com/gin-gonic/gin/binding" ) // EnvGinMode indicates environment name for gin mode. const EnvGinMode = "GIN_MODE" const ( // DebugMode indicates gin mode is debug. DebugMode = "debug" // ReleaseMode indicates gin mode is release. ReleaseMode = "release" // TestMode indicates gin mode is test. TestMode = "test" ) const ( debugCode = iota releaseCode testCode ) // DefaultWriter is the default io.Writer used by Gin for debug output and // middleware output like Logger() or Recovery(). // Note that both Logger and Recovery provides custom ways to configure their // output io.Writer. // To support coloring in Windows use: // // import "github.com/mattn/go-colorable" // gin.DefaultWriter = colorable.NewColorableStdout() var DefaultWriter io.Writer = os.Stdout // DefaultErrorWriter is the default io.Writer used by Gin to debug errors var DefaultErrorWriter io.Writer = os.Stderr var ( ginMode = debugCode modeName = DebugMode ) func init() { mode := os.Getenv(EnvGinMode) SetMode(mode) } // SetMode sets gin mode according to input string. func SetMode(value string) { if value == "" { if flag.Lookup("test.v") != nil { value = TestMode } else { value = DebugMode } } switch value { case DebugMode: ginMode = debugCode case ReleaseMode: ginMode = releaseCode case TestMode: ginMode = testCode default: panic("gin mode unknown: " + value + " (available mode: debug release test)") } modeName = value } // DisableBindValidation closes the default validator. func DisableBindValidation() { binding.Validator = nil } // EnableJsonDecoderUseNumber sets true for binding.EnableDecoderUseNumber to // call the UseNumber method on the JSON Decoder instance. func EnableJsonDecoderUseNumber() { binding.EnableDecoderUseNumber = true } // EnableJsonDecoderDisallowUnknownFields sets true for binding.EnableDecoderDisallowUnknownFields to // call the DisallowUnknownFields method on the JSON Decoder instance. func EnableJsonDecoderDisallowUnknownFields() { binding.EnableDecoderDisallowUnknownFields = true } // Mode returns current gin mode. func Mode() string { return modeName }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/context_appengine.go
vendor/github.com/gin-gonic/gin/context_appengine.go
// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build appengine package gin func init() { defaultPlatform = PlatformGoogleAppEngine }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/debug.go
vendor/github.com/gin-gonic/gin/debug.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "html/template" "runtime" "strconv" "strings" ) const ginSupportMinGoVer = 18 // IsDebugging returns true if the framework is running in debug mode. // Use SetMode(gin.ReleaseMode) to disable debug mode. func IsDebugging() bool { return ginMode == debugCode } // DebugPrintRouteFunc indicates debug log output format. var DebugPrintRouteFunc func(httpMethod, absolutePath, handlerName string, nuHandlers int) // DebugPrintFunc indicates debug log output format. var DebugPrintFunc func(format string, values ...interface{}) func debugPrintRoute(httpMethod, absolutePath string, handlers HandlersChain) { if IsDebugging() { nuHandlers := len(handlers) handlerName := nameOfFunction(handlers.Last()) if DebugPrintRouteFunc == nil { debugPrint("%-6s %-25s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers) } else { DebugPrintRouteFunc(httpMethod, absolutePath, handlerName, nuHandlers) } } } func debugPrintLoadTemplate(tmpl *template.Template) { if IsDebugging() { var buf strings.Builder for _, tmpl := range tmpl.Templates() { buf.WriteString("\t- ") buf.WriteString(tmpl.Name()) buf.WriteString("\n") } debugPrint("Loaded HTML Templates (%d): \n%s\n", len(tmpl.Templates()), buf.String()) } } func debugPrint(format string, values ...any) { if !IsDebugging() { return } if DebugPrintFunc != nil { DebugPrintFunc(format, values...) return } if !strings.HasSuffix(format, "\n") { format += "\n" } fmt.Fprintf(DefaultWriter, "[GIN-debug] "+format, values...) } func getMinVer(v string) (uint64, error) { first := strings.IndexByte(v, '.') last := strings.LastIndexByte(v, '.') if first == last { return strconv.ParseUint(v[first+1:], 10, 64) } return strconv.ParseUint(v[first+1:last], 10, 64) } func debugPrintWARNINGDefault() { if v, e := getMinVer(runtime.Version()); e == nil && v < ginSupportMinGoVer { debugPrint(`[WARNING] Now Gin requires Go 1.18+. `) } debugPrint(`[WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached. `) } func debugPrintWARNINGNew() { debugPrint(`[WARNING] Running in "debug" mode. Switch to "release" mode in production. - using env: export GIN_MODE=release - using code: gin.SetMode(gin.ReleaseMode) `) } func debugPrintWARNINGSetHTMLTemplate() { debugPrint(`[WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called at initialization. ie. before any route is registered or the router is listening in a socket: router := gin.Default() router.SetHTMLTemplate(template) // << good place `) } func debugPrintError(err error) { if err != nil && IsDebugging() { fmt.Fprintf(DefaultErrorWriter, "[GIN-debug] [ERROR] %v\n", err) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/gin.go
vendor/github.com/gin-gonic/gin/gin.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "html/template" "net" "net/http" "os" "path" "regexp" "strings" "sync" "github.com/gin-gonic/gin/internal/bytesconv" "github.com/gin-gonic/gin/render" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" ) const defaultMultipartMemory = 32 << 20 // 32 MB var ( default404Body = []byte("404 page not found") default405Body = []byte("405 method not allowed") ) var defaultPlatform string var defaultTrustedCIDRs = []*net.IPNet{ { // 0.0.0.0/0 (IPv4) IP: net.IP{0x0, 0x0, 0x0, 0x0}, Mask: net.IPMask{0x0, 0x0, 0x0, 0x0}, }, { // ::/0 (IPv6) IP: net.IP{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, Mask: net.IPMask{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, }, } var regSafePrefix = regexp.MustCompile("[^a-zA-Z0-9/-]+") var regRemoveRepeatedChar = regexp.MustCompile("/{2,}") // HandlerFunc defines the handler used by gin middleware as return value. type HandlerFunc func(*Context) // OptionFunc defines the function to change the default configuration type OptionFunc func(*Engine) // HandlersChain defines a HandlerFunc slice. type HandlersChain []HandlerFunc // Last returns the last handler in the chain. i.e. the last handler is the main one. func (c HandlersChain) Last() HandlerFunc { if length := len(c); length > 0 { return c[length-1] } return nil } // RouteInfo represents a request route's specification which contains method and path and its handler. type RouteInfo struct { Method string Path string Handler string HandlerFunc HandlerFunc } // RoutesInfo defines a RouteInfo slice. type RoutesInfo []RouteInfo // Trusted platforms const ( // PlatformGoogleAppEngine when running on Google App Engine. Trust X-Appengine-Remote-Addr // for determining the client's IP PlatformGoogleAppEngine = "X-Appengine-Remote-Addr" // PlatformCloudflare when using Cloudflare's CDN. Trust CF-Connecting-IP for determining // the client's IP PlatformCloudflare = "CF-Connecting-IP" // PlatformFlyIO when running on Fly.io. Trust Fly-Client-IP for determining the client's IP PlatformFlyIO = "Fly-Client-IP" ) // Engine is the framework's instance, it contains the muxer, middleware and configuration settings. // Create an instance of Engine, by using New() or Default() type Engine struct { RouterGroup // RedirectTrailingSlash enables automatic redirection if the current route can't be matched but a // handler for the path with (without) the trailing slash exists. // For example if /foo/ is requested but a route only exists for /foo, the // client is redirected to /foo with http status code 301 for GET requests // and 307 for all other request methods. RedirectTrailingSlash bool // RedirectFixedPath if enabled, the router tries to fix the current request path, if no // handle is registered for it. // First superfluous path elements like ../ or // are removed. // Afterwards the router does a case-insensitive lookup of the cleaned path. // If a handle can be found for this route, the router makes a redirection // to the corrected path with status code 301 for GET requests and 307 for // all other request methods. // For example /FOO and /..//Foo could be redirected to /foo. // RedirectTrailingSlash is independent of this option. RedirectFixedPath bool // HandleMethodNotAllowed if enabled, the router checks if another method is allowed for the // current route, if the current request can not be routed. // If this is the case, the request is answered with 'Method Not Allowed' // and HTTP status code 405. // If no other Method is allowed, the request is delegated to the NotFound // handler. HandleMethodNotAllowed bool // ForwardedByClientIP if enabled, client IP will be parsed from the request's headers that // match those stored at `(*gin.Engine).RemoteIPHeaders`. If no IP was // fetched, it falls back to the IP obtained from // `(*gin.Context).Request.RemoteAddr`. ForwardedByClientIP bool // AppEngine was deprecated. // Deprecated: USE `TrustedPlatform` WITH VALUE `gin.PlatformGoogleAppEngine` INSTEAD // #726 #755 If enabled, it will trust some headers starting with // 'X-AppEngine...' for better integration with that PaaS. AppEngine bool // UseRawPath if enabled, the url.RawPath will be used to find parameters. UseRawPath bool // UnescapePathValues if true, the path value will be unescaped. // If UseRawPath is false (by default), the UnescapePathValues effectively is true, // as url.Path gonna be used, which is already unescaped. UnescapePathValues bool // RemoveExtraSlash a parameter can be parsed from the URL even with extra slashes. // See the PR #1817 and issue #1644 RemoveExtraSlash bool // RemoteIPHeaders list of headers used to obtain the client IP when // `(*gin.Engine).ForwardedByClientIP` is `true` and // `(*gin.Context).Request.RemoteAddr` is matched by at least one of the // network origins of list defined by `(*gin.Engine).SetTrustedProxies()`. RemoteIPHeaders []string // TrustedPlatform if set to a constant of value gin.Platform*, trusts the headers set by // that platform, for example to determine the client IP TrustedPlatform string // MaxMultipartMemory value of 'maxMemory' param that is given to http.Request's ParseMultipartForm // method call. MaxMultipartMemory int64 // UseH2C enable h2c support. UseH2C bool // ContextWithFallback enable fallback Context.Deadline(), Context.Done(), Context.Err() and Context.Value() when Context.Request.Context() is not nil. ContextWithFallback bool delims render.Delims secureJSONPrefix string HTMLRender render.HTMLRender FuncMap template.FuncMap allNoRoute HandlersChain allNoMethod HandlersChain noRoute HandlersChain noMethod HandlersChain pool sync.Pool trees methodTrees maxParams uint16 maxSections uint16 trustedProxies []string trustedCIDRs []*net.IPNet } var _ IRouter = (*Engine)(nil) // New returns a new blank Engine instance without any middleware attached. // By default, the configuration is: // - RedirectTrailingSlash: true // - RedirectFixedPath: false // - HandleMethodNotAllowed: false // - ForwardedByClientIP: true // - UseRawPath: false // - UnescapePathValues: true func New(opts ...OptionFunc) *Engine { debugPrintWARNINGNew() engine := &Engine{ RouterGroup: RouterGroup{ Handlers: nil, basePath: "/", root: true, }, FuncMap: template.FuncMap{}, RedirectTrailingSlash: true, RedirectFixedPath: false, HandleMethodNotAllowed: false, ForwardedByClientIP: true, RemoteIPHeaders: []string{"X-Forwarded-For", "X-Real-IP"}, TrustedPlatform: defaultPlatform, UseRawPath: false, RemoveExtraSlash: false, UnescapePathValues: true, MaxMultipartMemory: defaultMultipartMemory, trees: make(methodTrees, 0, 9), delims: render.Delims{Left: "{{", Right: "}}"}, secureJSONPrefix: "while(1);", trustedProxies: []string{"0.0.0.0/0", "::/0"}, trustedCIDRs: defaultTrustedCIDRs, } engine.RouterGroup.engine = engine engine.pool.New = func() any { return engine.allocateContext(engine.maxParams) } return engine.With(opts...) } // Default returns an Engine instance with the Logger and Recovery middleware already attached. func Default(opts ...OptionFunc) *Engine { debugPrintWARNINGDefault() engine := New() engine.Use(Logger(), Recovery()) return engine.With(opts...) } func (engine *Engine) Handler() http.Handler { if !engine.UseH2C { return engine } h2s := &http2.Server{} return h2c.NewHandler(engine, h2s) } func (engine *Engine) allocateContext(maxParams uint16) *Context { v := make(Params, 0, maxParams) skippedNodes := make([]skippedNode, 0, engine.maxSections) return &Context{engine: engine, params: &v, skippedNodes: &skippedNodes} } // Delims sets template left and right delims and returns an Engine instance. func (engine *Engine) Delims(left, right string) *Engine { engine.delims = render.Delims{Left: left, Right: right} return engine } // SecureJsonPrefix sets the secureJSONPrefix used in Context.SecureJSON. func (engine *Engine) SecureJsonPrefix(prefix string) *Engine { engine.secureJSONPrefix = prefix return engine } // LoadHTMLGlob loads HTML files identified by glob pattern // and associates the result with HTML renderer. func (engine *Engine) LoadHTMLGlob(pattern string) { left := engine.delims.Left right := engine.delims.Right templ := template.Must(template.New("").Delims(left, right).Funcs(engine.FuncMap).ParseGlob(pattern)) if IsDebugging() { debugPrintLoadTemplate(templ) engine.HTMLRender = render.HTMLDebug{Glob: pattern, FuncMap: engine.FuncMap, Delims: engine.delims} return } engine.SetHTMLTemplate(templ) } // LoadHTMLFiles loads a slice of HTML files // and associates the result with HTML renderer. func (engine *Engine) LoadHTMLFiles(files ...string) { if IsDebugging() { engine.HTMLRender = render.HTMLDebug{Files: files, FuncMap: engine.FuncMap, Delims: engine.delims} return } templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFiles(files...)) engine.SetHTMLTemplate(templ) } // SetHTMLTemplate associate a template with HTML renderer. func (engine *Engine) SetHTMLTemplate(templ *template.Template) { if len(engine.trees) > 0 { debugPrintWARNINGSetHTMLTemplate() } engine.HTMLRender = render.HTMLProduction{Template: templ.Funcs(engine.FuncMap)} } // SetFuncMap sets the FuncMap used for template.FuncMap. func (engine *Engine) SetFuncMap(funcMap template.FuncMap) { engine.FuncMap = funcMap } // NoRoute adds handlers for NoRoute. It returns a 404 code by default. func (engine *Engine) NoRoute(handlers ...HandlerFunc) { engine.noRoute = handlers engine.rebuild404Handlers() } // NoMethod sets the handlers called when Engine.HandleMethodNotAllowed = true. func (engine *Engine) NoMethod(handlers ...HandlerFunc) { engine.noMethod = handlers engine.rebuild405Handlers() } // Use attaches a global middleware to the router. i.e. the middleware attached through Use() will be // included in the handlers chain for every single request. Even 404, 405, static files... // For example, this is the right place for a logger or error management middleware. func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes { engine.RouterGroup.Use(middleware...) engine.rebuild404Handlers() engine.rebuild405Handlers() return engine } // With returns a new Engine instance with the provided options. func (engine *Engine) With(opts ...OptionFunc) *Engine { for _, opt := range opts { opt(engine) } return engine } func (engine *Engine) rebuild404Handlers() { engine.allNoRoute = engine.combineHandlers(engine.noRoute) } func (engine *Engine) rebuild405Handlers() { engine.allNoMethod = engine.combineHandlers(engine.noMethod) } func (engine *Engine) addRoute(method, path string, handlers HandlersChain) { assert1(path[0] == '/', "path must begin with '/'") assert1(method != "", "HTTP method can not be empty") assert1(len(handlers) > 0, "there must be at least one handler") debugPrintRoute(method, path, handlers) root := engine.trees.get(method) if root == nil { root = new(node) root.fullPath = "/" engine.trees = append(engine.trees, methodTree{method: method, root: root}) } root.addRoute(path, handlers) if paramsCount := countParams(path); paramsCount > engine.maxParams { engine.maxParams = paramsCount } if sectionsCount := countSections(path); sectionsCount > engine.maxSections { engine.maxSections = sectionsCount } } // Routes returns a slice of registered routes, including some useful information, such as: // the http method, path and the handler name. func (engine *Engine) Routes() (routes RoutesInfo) { for _, tree := range engine.trees { routes = iterate("", tree.method, routes, tree.root) } return routes } func iterate(path, method string, routes RoutesInfo, root *node) RoutesInfo { path += root.path if len(root.handlers) > 0 { handlerFunc := root.handlers.Last() routes = append(routes, RouteInfo{ Method: method, Path: path, Handler: nameOfFunction(handlerFunc), HandlerFunc: handlerFunc, }) } for _, child := range root.children { routes = iterate(path, method, routes, child) } return routes } // Run attaches the router to a http.Server and starts listening and serving HTTP requests. // It is a shortcut for http.ListenAndServe(addr, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) Run(addr ...string) (err error) { defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } address := resolveAddress(addr) debugPrint("Listening and serving HTTP on %s\n", address) err = http.ListenAndServe(address, engine.Handler()) return } func (engine *Engine) prepareTrustedCIDRs() ([]*net.IPNet, error) { if engine.trustedProxies == nil { return nil, nil } cidr := make([]*net.IPNet, 0, len(engine.trustedProxies)) for _, trustedProxy := range engine.trustedProxies { if !strings.Contains(trustedProxy, "/") { ip := parseIP(trustedProxy) if ip == nil { return cidr, &net.ParseError{Type: "IP address", Text: trustedProxy} } switch len(ip) { case net.IPv4len: trustedProxy += "/32" case net.IPv6len: trustedProxy += "/128" } } _, cidrNet, err := net.ParseCIDR(trustedProxy) if err != nil { return cidr, err } cidr = append(cidr, cidrNet) } return cidr, nil } // SetTrustedProxies set a list of network origins (IPv4 addresses, // IPv4 CIDRs, IPv6 addresses or IPv6 CIDRs) from which to trust // request's headers that contain alternative client IP when // `(*gin.Engine).ForwardedByClientIP` is `true`. `TrustedProxies` // feature is enabled by default, and it also trusts all proxies // by default. If you want to disable this feature, use // Engine.SetTrustedProxies(nil), then Context.ClientIP() will // return the remote address directly. func (engine *Engine) SetTrustedProxies(trustedProxies []string) error { engine.trustedProxies = trustedProxies return engine.parseTrustedProxies() } // isUnsafeTrustedProxies checks if Engine.trustedCIDRs contains all IPs, it's not safe if it has (returns true) func (engine *Engine) isUnsafeTrustedProxies() bool { return engine.isTrustedProxy(net.ParseIP("0.0.0.0")) || engine.isTrustedProxy(net.ParseIP("::")) } // parseTrustedProxies parse Engine.trustedProxies to Engine.trustedCIDRs func (engine *Engine) parseTrustedProxies() error { trustedCIDRs, err := engine.prepareTrustedCIDRs() engine.trustedCIDRs = trustedCIDRs return err } // isTrustedProxy will check whether the IP address is included in the trusted list according to Engine.trustedCIDRs func (engine *Engine) isTrustedProxy(ip net.IP) bool { if engine.trustedCIDRs == nil { return false } for _, cidr := range engine.trustedCIDRs { if cidr.Contains(ip) { return true } } return false } // validateHeader will parse X-Forwarded-For header and return the trusted client IP address func (engine *Engine) validateHeader(header string) (clientIP string, valid bool) { if header == "" { return "", false } items := strings.Split(header, ",") for i := len(items) - 1; i >= 0; i-- { ipStr := strings.TrimSpace(items[i]) ip := net.ParseIP(ipStr) if ip == nil { break } // X-Forwarded-For is appended by proxy // Check IPs in reverse order and stop when find untrusted proxy if (i == 0) || (!engine.isTrustedProxy(ip)) { return ipStr, true } } return "", false } // parseIP parse a string representation of an IP and returns a net.IP with the // minimum byte representation or nil if input is invalid. func parseIP(ip string) net.IP { parsedIP := net.ParseIP(ip) if ipv4 := parsedIP.To4(); ipv4 != nil { // return ip in a 4-byte representation return ipv4 } // return ip in a 16-byte representation or nil return parsedIP } // RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests. // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunTLS(addr, certFile, keyFile string) (err error) { debugPrint("Listening and serving HTTPS on %s\n", addr) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } err = http.ListenAndServeTLS(addr, certFile, keyFile, engine.Handler()) return } // RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified unix socket (i.e. a file). // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunUnix(file string) (err error) { debugPrint("Listening and serving HTTP on unix:/%s", file) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.") } listener, err := net.Listen("unix", file) if err != nil { return } defer listener.Close() defer os.Remove(file) err = http.Serve(listener, engine.Handler()) return } // RunFd attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified file descriptor. // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunFd(fd int) (err error) { debugPrint("Listening and serving HTTP on fd@%d", fd) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.") } f := os.NewFile(uintptr(fd), fmt.Sprintf("fd@%d", fd)) listener, err := net.FileListener(f) if err != nil { return } defer listener.Close() err = engine.RunListener(listener) return } // RunListener attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified net.Listener func (engine *Engine) RunListener(listener net.Listener) (err error) { debugPrint("Listening and serving HTTP on listener what's bind with address@%s", listener.Addr()) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.") } err = http.Serve(listener, engine.Handler()) return } // ServeHTTP conforms to the http.Handler interface. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) { c := engine.pool.Get().(*Context) c.writermem.reset(w) c.Request = req c.reset() engine.handleHTTPRequest(c) engine.pool.Put(c) } // HandleContext re-enters a context that has been rewritten. // This can be done by setting c.Request.URL.Path to your new target. // Disclaimer: You can loop yourself to deal with this, use wisely. func (engine *Engine) HandleContext(c *Context) { oldIndexValue := c.index c.reset() engine.handleHTTPRequest(c) c.index = oldIndexValue } func (engine *Engine) handleHTTPRequest(c *Context) { httpMethod := c.Request.Method rPath := c.Request.URL.Path unescape := false if engine.UseRawPath && len(c.Request.URL.RawPath) > 0 { rPath = c.Request.URL.RawPath unescape = engine.UnescapePathValues } if engine.RemoveExtraSlash { rPath = cleanPath(rPath) } // Find root of the tree for the given HTTP method t := engine.trees for i, tl := 0, len(t); i < tl; i++ { if t[i].method != httpMethod { continue } root := t[i].root // Find route in tree value := root.getValue(rPath, c.params, c.skippedNodes, unescape) if value.params != nil { c.Params = *value.params } if value.handlers != nil { c.handlers = value.handlers c.fullPath = value.fullPath c.Next() c.writermem.WriteHeaderNow() return } if httpMethod != http.MethodConnect && rPath != "/" { if value.tsr && engine.RedirectTrailingSlash { redirectTrailingSlash(c) return } if engine.RedirectFixedPath && redirectFixedPath(c, root, engine.RedirectFixedPath) { return } } break } if engine.HandleMethodNotAllowed { // According to RFC 7231 section 6.5.5, MUST generate an Allow header field in response // containing a list of the target resource's currently supported methods. allowed := make([]string, 0, len(t)-1) for _, tree := range engine.trees { if tree.method == httpMethod { continue } if value := tree.root.getValue(rPath, nil, c.skippedNodes, unescape); value.handlers != nil { allowed = append(allowed, tree.method) } } if len(allowed) > 0 { c.handlers = engine.allNoMethod c.writermem.Header().Set("Allow", strings.Join(allowed, ", ")) serveError(c, http.StatusMethodNotAllowed, default405Body) return } } c.handlers = engine.allNoRoute serveError(c, http.StatusNotFound, default404Body) } var mimePlain = []string{MIMEPlain} func serveError(c *Context, code int, defaultMessage []byte) { c.writermem.status = code c.Next() if c.writermem.Written() { return } if c.writermem.Status() == code { c.writermem.Header()["Content-Type"] = mimePlain _, err := c.Writer.Write(defaultMessage) if err != nil { debugPrint("cannot write message to writer during serve error: %v", err) } return } c.writermem.WriteHeaderNow() } func redirectTrailingSlash(c *Context) { req := c.Request p := req.URL.Path if prefix := path.Clean(c.Request.Header.Get("X-Forwarded-Prefix")); prefix != "." { prefix = regSafePrefix.ReplaceAllString(prefix, "") prefix = regRemoveRepeatedChar.ReplaceAllString(prefix, "/") p = prefix + "/" + req.URL.Path } req.URL.Path = p + "/" if length := len(p); length > 1 && p[length-1] == '/' { req.URL.Path = p[:length-1] } redirectRequest(c) } func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool { req := c.Request rPath := req.URL.Path if fixedPath, ok := root.findCaseInsensitivePath(cleanPath(rPath), trailingSlash); ok { req.URL.Path = bytesconv.BytesToString(fixedPath) redirectRequest(c) return true } return false } func redirectRequest(c *Context) { req := c.Request rPath := req.URL.Path rURL := req.URL.String() code := http.StatusMovedPermanently // Permanent redirect, request with GET method if req.Method != http.MethodGet { code = http.StatusTemporaryRedirect } debugPrint("redirecting request %d: %s --> %s", code, rPath, rURL) http.Redirect(c.Writer, req, rURL, code) c.writermem.WriteHeaderNow() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/auth.go
vendor/github.com/gin-gonic/gin/auth.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "crypto/subtle" "encoding/base64" "net/http" "strconv" "github.com/gin-gonic/gin/internal/bytesconv" ) // AuthUserKey is the cookie name for user credential in basic auth. const AuthUserKey = "user" // AuthProxyUserKey is the cookie name for proxy_user credential in basic auth for proxy. const AuthProxyUserKey = "proxy_user" // Accounts defines a key/value for user/pass list of authorized logins. type Accounts map[string]string type authPair struct { value string user string } type authPairs []authPair func (a authPairs) searchCredential(authValue string) (string, bool) { if authValue == "" { return "", false } for _, pair := range a { if subtle.ConstantTimeCompare(bytesconv.StringToBytes(pair.value), bytesconv.StringToBytes(authValue)) == 1 { return pair.user, true } } return "", false } // BasicAuthForRealm returns a Basic HTTP Authorization middleware. It takes as arguments a map[string]string where // the key is the user name and the value is the password, as well as the name of the Realm. // If the realm is empty, "Authorization Required" will be used by default. // (see http://tools.ietf.org/html/rfc2617#section-1.2) func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc { if realm == "" { realm = "Authorization Required" } realm = "Basic realm=" + strconv.Quote(realm) pairs := processAccounts(accounts) return func(c *Context) { // Search user in the slice of allowed credentials user, found := pairs.searchCredential(c.requestHeader("Authorization")) if !found { // Credentials doesn't match, we return 401 and abort handlers chain. c.Header("WWW-Authenticate", realm) c.AbortWithStatus(http.StatusUnauthorized) return } // The user credentials was found, set user's id to key AuthUserKey in this context, the user's id can be read later using // c.MustGet(gin.AuthUserKey). c.Set(AuthUserKey, user) } } // BasicAuth returns a Basic HTTP Authorization middleware. It takes as argument a map[string]string where // the key is the user name and the value is the password. func BasicAuth(accounts Accounts) HandlerFunc { return BasicAuthForRealm(accounts, "") } func processAccounts(accounts Accounts) authPairs { length := len(accounts) assert1(length > 0, "Empty list of authorized credentials") pairs := make(authPairs, 0, length) for user, password := range accounts { assert1(user != "", "User can not be empty") value := authorizationHeader(user, password) pairs = append(pairs, authPair{ value: value, user: user, }) } return pairs } func authorizationHeader(user, password string) string { base := user + ":" + password return "Basic " + base64.StdEncoding.EncodeToString(bytesconv.StringToBytes(base)) } // BasicAuthForProxy returns a Basic HTTP Proxy-Authorization middleware. // If the realm is empty, "Proxy Authorization Required" will be used by default. func BasicAuthForProxy(accounts Accounts, realm string) HandlerFunc { if realm == "" { realm = "Proxy Authorization Required" } realm = "Basic realm=" + strconv.Quote(realm) pairs := processAccounts(accounts) return func(c *Context) { proxyUser, found := pairs.searchCredential(c.requestHeader("Proxy-Authorization")) if !found { // Credentials doesn't match, we return 407 and abort handlers chain. c.Header("Proxy-Authenticate", realm) c.AbortWithStatus(http.StatusProxyAuthRequired) return } // The proxy_user credentials was found, set proxy_user's id to key AuthProxyUserKey in this context, the proxy_user's id can be read later using // c.MustGet(gin.AuthProxyUserKey). c.Set(AuthProxyUserKey, proxyUser) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/context.go
vendor/github.com/gin-gonic/gin/context.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "errors" "io" "log" "math" "mime/multipart" "net" "net/http" "net/url" "os" "path/filepath" "strings" "sync" "time" "github.com/gin-contrib/sse" "github.com/gin-gonic/gin/binding" "github.com/gin-gonic/gin/render" ) // Content-Type MIME of the most common data formats. const ( MIMEJSON = binding.MIMEJSON MIMEHTML = binding.MIMEHTML MIMEXML = binding.MIMEXML MIMEXML2 = binding.MIMEXML2 MIMEPlain = binding.MIMEPlain MIMEPOSTForm = binding.MIMEPOSTForm MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm MIMEYAML = binding.MIMEYAML MIMETOML = binding.MIMETOML ) // BodyBytesKey indicates a default body bytes key. const BodyBytesKey = "_gin-gonic/gin/bodybyteskey" // ContextKey is the key that a Context returns itself for. const ContextKey = "_gin-gonic/gin/contextkey" type ContextKeyType int const ContextRequestKey ContextKeyType = 0 // abortIndex represents a typical value used in abort functions. const abortIndex int8 = math.MaxInt8 >> 1 // Context is the most important part of gin. It allows us to pass variables between middleware, // manage the flow, validate the JSON of a request and render a JSON response for example. type Context struct { writermem responseWriter Request *http.Request Writer ResponseWriter Params Params handlers HandlersChain index int8 fullPath string engine *Engine params *Params skippedNodes *[]skippedNode // This mutex protects Keys map. mu sync.RWMutex // Keys is a key/value pair exclusively for the context of each request. Keys map[string]any // Errors is a list of errors attached to all the handlers/middlewares who used this context. Errors errorMsgs // Accepted defines a list of manually accepted formats for content negotiation. Accepted []string // queryCache caches the query result from c.Request.URL.Query(). queryCache url.Values // formCache caches c.Request.PostForm, which contains the parsed form data from POST, PATCH, // or PUT body parameters. formCache url.Values // SameSite allows a server to define a cookie attribute making it impossible for // the browser to send this cookie along with cross-site requests. sameSite http.SameSite } /************************************/ /********** CONTEXT CREATION ********/ /************************************/ func (c *Context) reset() { c.Writer = &c.writermem c.Params = c.Params[:0] c.handlers = nil c.index = -1 c.fullPath = "" c.Keys = nil c.Errors = c.Errors[:0] c.Accepted = nil c.queryCache = nil c.formCache = nil c.sameSite = 0 *c.params = (*c.params)[:0] *c.skippedNodes = (*c.skippedNodes)[:0] } // Copy returns a copy of the current context that can be safely used outside the request's scope. // This has to be used when the context has to be passed to a goroutine. func (c *Context) Copy() *Context { cp := Context{ writermem: c.writermem, Request: c.Request, engine: c.engine, } cp.writermem.ResponseWriter = nil cp.Writer = &cp.writermem cp.index = abortIndex cp.handlers = nil cp.fullPath = c.fullPath cKeys := c.Keys cp.Keys = make(map[string]any, len(cKeys)) c.mu.RLock() for k, v := range cKeys { cp.Keys[k] = v } c.mu.RUnlock() cParams := c.Params cp.Params = make([]Param, len(cParams)) copy(cp.Params, cParams) return &cp } // HandlerName returns the main handler's name. For example if the handler is "handleGetUsers()", // this function will return "main.handleGetUsers". func (c *Context) HandlerName() string { return nameOfFunction(c.handlers.Last()) } // HandlerNames returns a list of all registered handlers for this context in descending order, // following the semantics of HandlerName() func (c *Context) HandlerNames() []string { hn := make([]string, 0, len(c.handlers)) for _, val := range c.handlers { hn = append(hn, nameOfFunction(val)) } return hn } // Handler returns the main handler. func (c *Context) Handler() HandlerFunc { return c.handlers.Last() } // FullPath returns a matched route full path. For not found routes // returns an empty string. // // router.GET("/user/:id", func(c *gin.Context) { // c.FullPath() == "/user/:id" // true // }) func (c *Context) FullPath() string { return c.fullPath } /************************************/ /*********** FLOW CONTROL ***********/ /************************************/ // Next should be used only inside middleware. // It executes the pending handlers in the chain inside the calling handler. // See example in GitHub. func (c *Context) Next() { c.index++ for c.index < int8(len(c.handlers)) { c.handlers[c.index](c) c.index++ } } // IsAborted returns true if the current context was aborted. func (c *Context) IsAborted() bool { return c.index >= abortIndex } // Abort prevents pending handlers from being called. Note that this will not stop the current handler. // Let's say you have an authorization middleware that validates that the current request is authorized. // If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers // for this request are not called. func (c *Context) Abort() { c.index = abortIndex } // AbortWithStatus calls `Abort()` and writes the headers with the specified status code. // For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401). func (c *Context) AbortWithStatus(code int) { c.Status(code) c.Writer.WriteHeaderNow() c.Abort() } // AbortWithStatusJSON calls `Abort()` and then `JSON` internally. // This method stops the chain, writes the status code and return a JSON body. // It also sets the Content-Type as "application/json". func (c *Context) AbortWithStatusJSON(code int, jsonObj any) { c.Abort() c.JSON(code, jsonObj) } // AbortWithError calls `AbortWithStatus()` and `Error()` internally. // This method stops the chain, writes the status code and pushes the specified error to `c.Errors`. // See Context.Error() for more details. func (c *Context) AbortWithError(code int, err error) *Error { c.AbortWithStatus(code) return c.Error(err) } /************************************/ /********* ERROR MANAGEMENT *********/ /************************************/ // Error attaches an error to the current context. The error is pushed to a list of errors. // It's a good idea to call Error for each error that occurred during the resolution of a request. // A middleware can be used to collect all the errors and push them to a database together, // print a log, or append it in the HTTP response. // Error will panic if err is nil. func (c *Context) Error(err error) *Error { if err == nil { panic("err is nil") } var parsedError *Error ok := errors.As(err, &parsedError) if !ok { parsedError = &Error{ Err: err, Type: ErrorTypePrivate, } } c.Errors = append(c.Errors, parsedError) return parsedError } /************************************/ /******** METADATA MANAGEMENT********/ /************************************/ // Set is used to store a new key/value pair exclusively for this context. // It also lazy initializes c.Keys if it was not used previously. func (c *Context) Set(key string, value any) { c.mu.Lock() defer c.mu.Unlock() if c.Keys == nil { c.Keys = make(map[string]any) } c.Keys[key] = value } // Get returns the value for the given key, ie: (value, true). // If the value does not exist it returns (nil, false) func (c *Context) Get(key string) (value any, exists bool) { c.mu.RLock() defer c.mu.RUnlock() value, exists = c.Keys[key] return } // MustGet returns the value for the given key if it exists, otherwise it panics. func (c *Context) MustGet(key string) any { if value, exists := c.Get(key); exists { return value } panic("Key \"" + key + "\" does not exist") } // GetString returns the value associated with the key as a string. func (c *Context) GetString(key string) (s string) { if val, ok := c.Get(key); ok && val != nil { s, _ = val.(string) } return } // GetBool returns the value associated with the key as a boolean. func (c *Context) GetBool(key string) (b bool) { if val, ok := c.Get(key); ok && val != nil { b, _ = val.(bool) } return } // GetInt returns the value associated with the key as an integer. func (c *Context) GetInt(key string) (i int) { if val, ok := c.Get(key); ok && val != nil { i, _ = val.(int) } return } // GetInt64 returns the value associated with the key as an integer. func (c *Context) GetInt64(key string) (i64 int64) { if val, ok := c.Get(key); ok && val != nil { i64, _ = val.(int64) } return } // GetUint returns the value associated with the key as an unsigned integer. func (c *Context) GetUint(key string) (ui uint) { if val, ok := c.Get(key); ok && val != nil { ui, _ = val.(uint) } return } // GetUint64 returns the value associated with the key as an unsigned integer. func (c *Context) GetUint64(key string) (ui64 uint64) { if val, ok := c.Get(key); ok && val != nil { ui64, _ = val.(uint64) } return } // GetFloat64 returns the value associated with the key as a float64. func (c *Context) GetFloat64(key string) (f64 float64) { if val, ok := c.Get(key); ok && val != nil { f64, _ = val.(float64) } return } // GetTime returns the value associated with the key as time. func (c *Context) GetTime(key string) (t time.Time) { if val, ok := c.Get(key); ok && val != nil { t, _ = val.(time.Time) } return } // GetDuration returns the value associated with the key as a duration. func (c *Context) GetDuration(key string) (d time.Duration) { if val, ok := c.Get(key); ok && val != nil { d, _ = val.(time.Duration) } return } // GetStringSlice returns the value associated with the key as a slice of strings. func (c *Context) GetStringSlice(key string) (ss []string) { if val, ok := c.Get(key); ok && val != nil { ss, _ = val.([]string) } return } // GetStringMap returns the value associated with the key as a map of interfaces. func (c *Context) GetStringMap(key string) (sm map[string]any) { if val, ok := c.Get(key); ok && val != nil { sm, _ = val.(map[string]any) } return } // GetStringMapString returns the value associated with the key as a map of strings. func (c *Context) GetStringMapString(key string) (sms map[string]string) { if val, ok := c.Get(key); ok && val != nil { sms, _ = val.(map[string]string) } return } // GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings. func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string) { if val, ok := c.Get(key); ok && val != nil { smss, _ = val.(map[string][]string) } return } /************************************/ /************ INPUT DATA ************/ /************************************/ // Param returns the value of the URL param. // It is a shortcut for c.Params.ByName(key) // // router.GET("/user/:id", func(c *gin.Context) { // // a GET request to /user/john // id := c.Param("id") // id == "john" // // a GET request to /user/john/ // id := c.Param("id") // id == "/john/" // }) func (c *Context) Param(key string) string { return c.Params.ByName(key) } // AddParam adds param to context and // replaces path param key with given value for e2e testing purposes // Example Route: "/user/:id" // AddParam("id", 1) // Result: "/user/1" func (c *Context) AddParam(key, value string) { c.Params = append(c.Params, Param{Key: key, Value: value}) } // Query returns the keyed url query value if it exists, // otherwise it returns an empty string `("")`. // It is shortcut for `c.Request.URL.Query().Get(key)` // // GET /path?id=1234&name=Manu&value= // c.Query("id") == "1234" // c.Query("name") == "Manu" // c.Query("value") == "" // c.Query("wtf") == "" func (c *Context) Query(key string) (value string) { value, _ = c.GetQuery(key) return } // DefaultQuery returns the keyed url query value if it exists, // otherwise it returns the specified defaultValue string. // See: Query() and GetQuery() for further information. // // GET /?name=Manu&lastname= // c.DefaultQuery("name", "unknown") == "Manu" // c.DefaultQuery("id", "none") == "none" // c.DefaultQuery("lastname", "none") == "" func (c *Context) DefaultQuery(key, defaultValue string) string { if value, ok := c.GetQuery(key); ok { return value } return defaultValue } // GetQuery is like Query(), it returns the keyed url query value // if it exists `(value, true)` (even when the value is an empty string), // otherwise it returns `("", false)`. // It is shortcut for `c.Request.URL.Query().Get(key)` // // GET /?name=Manu&lastname= // ("Manu", true) == c.GetQuery("name") // ("", false) == c.GetQuery("id") // ("", true) == c.GetQuery("lastname") func (c *Context) GetQuery(key string) (string, bool) { if values, ok := c.GetQueryArray(key); ok { return values[0], ok } return "", false } // QueryArray returns a slice of strings for a given query key. // The length of the slice depends on the number of params with the given key. func (c *Context) QueryArray(key string) (values []string) { values, _ = c.GetQueryArray(key) return } func (c *Context) initQueryCache() { if c.queryCache == nil { if c.Request != nil { c.queryCache = c.Request.URL.Query() } else { c.queryCache = url.Values{} } } } // GetQueryArray returns a slice of strings for a given query key, plus // a boolean value whether at least one value exists for the given key. func (c *Context) GetQueryArray(key string) (values []string, ok bool) { c.initQueryCache() values, ok = c.queryCache[key] return } // QueryMap returns a map for a given query key. func (c *Context) QueryMap(key string) (dicts map[string]string) { dicts, _ = c.GetQueryMap(key) return } // GetQueryMap returns a map for a given query key, plus a boolean value // whether at least one value exists for the given key. func (c *Context) GetQueryMap(key string) (map[string]string, bool) { c.initQueryCache() return c.get(c.queryCache, key) } // PostForm returns the specified key from a POST urlencoded form or multipart form // when it exists, otherwise it returns an empty string `("")`. func (c *Context) PostForm(key string) (value string) { value, _ = c.GetPostForm(key) return } // DefaultPostForm returns the specified key from a POST urlencoded form or multipart form // when it exists, otherwise it returns the specified defaultValue string. // See: PostForm() and GetPostForm() for further information. func (c *Context) DefaultPostForm(key, defaultValue string) string { if value, ok := c.GetPostForm(key); ok { return value } return defaultValue } // GetPostForm is like PostForm(key). It returns the specified key from a POST urlencoded // form or multipart form when it exists `(value, true)` (even when the value is an empty string), // otherwise it returns ("", false). // For example, during a PATCH request to update the user's email: // // email=mail@example.com --> ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com" // email= --> ("", true) := GetPostForm("email") // set email to "" // --> ("", false) := GetPostForm("email") // do nothing with email func (c *Context) GetPostForm(key string) (string, bool) { if values, ok := c.GetPostFormArray(key); ok { return values[0], ok } return "", false } // PostFormArray returns a slice of strings for a given form key. // The length of the slice depends on the number of params with the given key. func (c *Context) PostFormArray(key string) (values []string) { values, _ = c.GetPostFormArray(key) return } func (c *Context) initFormCache() { if c.formCache == nil { c.formCache = make(url.Values) req := c.Request if err := req.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil { if !errors.Is(err, http.ErrNotMultipart) { debugPrint("error on parse multipart form array: %v", err) } } c.formCache = req.PostForm } } // GetPostFormArray returns a slice of strings for a given form key, plus // a boolean value whether at least one value exists for the given key. func (c *Context) GetPostFormArray(key string) (values []string, ok bool) { c.initFormCache() values, ok = c.formCache[key] return } // PostFormMap returns a map for a given form key. func (c *Context) PostFormMap(key string) (dicts map[string]string) { dicts, _ = c.GetPostFormMap(key) return } // GetPostFormMap returns a map for a given form key, plus a boolean value // whether at least one value exists for the given key. func (c *Context) GetPostFormMap(key string) (map[string]string, bool) { c.initFormCache() return c.get(c.formCache, key) } // get is an internal method and returns a map which satisfies conditions. func (c *Context) get(m map[string][]string, key string) (map[string]string, bool) { dicts := make(map[string]string) exist := false for k, v := range m { if i := strings.IndexByte(k, '['); i >= 1 && k[0:i] == key { if j := strings.IndexByte(k[i+1:], ']'); j >= 1 { exist = true dicts[k[i+1:][:j]] = v[0] } } } return dicts, exist } // FormFile returns the first file for the provided form key. func (c *Context) FormFile(name string) (*multipart.FileHeader, error) { if c.Request.MultipartForm == nil { if err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil { return nil, err } } f, fh, err := c.Request.FormFile(name) if err != nil { return nil, err } f.Close() return fh, err } // MultipartForm is the parsed multipart form, including file uploads. func (c *Context) MultipartForm() (*multipart.Form, error) { err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory) return c.Request.MultipartForm, err } // SaveUploadedFile uploads the form file to specific dst. func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error { src, err := file.Open() if err != nil { return err } defer src.Close() if err = os.MkdirAll(filepath.Dir(dst), 0750); err != nil { return err } out, err := os.Create(dst) if err != nil { return err } defer out.Close() _, err = io.Copy(out, src) return err } // Bind checks the Method and Content-Type to select a binding engine automatically, // Depending on the "Content-Type" header different bindings are used, for example: // // "application/json" --> JSON binding // "application/xml" --> XML binding // // It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. // It decodes the json payload into the struct specified as a pointer. // It writes a 400 error and sets Content-Type header "text/plain" in the response if input is not valid. func (c *Context) Bind(obj any) error { b := binding.Default(c.Request.Method, c.ContentType()) return c.MustBindWith(obj, b) } // BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON). func (c *Context) BindJSON(obj any) error { return c.MustBindWith(obj, binding.JSON) } // BindXML is a shortcut for c.MustBindWith(obj, binding.BindXML). func (c *Context) BindXML(obj any) error { return c.MustBindWith(obj, binding.XML) } // BindQuery is a shortcut for c.MustBindWith(obj, binding.Query). func (c *Context) BindQuery(obj any) error { return c.MustBindWith(obj, binding.Query) } // BindYAML is a shortcut for c.MustBindWith(obj, binding.YAML). func (c *Context) BindYAML(obj any) error { return c.MustBindWith(obj, binding.YAML) } // BindTOML is a shortcut for c.MustBindWith(obj, binding.TOML). func (c *Context) BindTOML(obj any) error { return c.MustBindWith(obj, binding.TOML) } // BindHeader is a shortcut for c.MustBindWith(obj, binding.Header). func (c *Context) BindHeader(obj any) error { return c.MustBindWith(obj, binding.Header) } // BindUri binds the passed struct pointer using binding.Uri. // It will abort the request with HTTP 400 if any error occurs. func (c *Context) BindUri(obj any) error { if err := c.ShouldBindUri(obj); err != nil { c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) //nolint: errcheck return err } return nil } // MustBindWith binds the passed struct pointer using the specified binding engine. // It will abort the request with HTTP 400 if any error occurs. // See the binding package. func (c *Context) MustBindWith(obj any, b binding.Binding) error { if err := c.ShouldBindWith(obj, b); err != nil { c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) //nolint: errcheck return err } return nil } // ShouldBind checks the Method and Content-Type to select a binding engine automatically, // Depending on the "Content-Type" header different bindings are used, for example: // // "application/json" --> JSON binding // "application/xml" --> XML binding // // It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. // It decodes the json payload into the struct specified as a pointer. // Like c.Bind() but this method does not set the response status code to 400 or abort if input is not valid. func (c *Context) ShouldBind(obj any) error { b := binding.Default(c.Request.Method, c.ContentType()) return c.ShouldBindWith(obj, b) } // ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON). func (c *Context) ShouldBindJSON(obj any) error { return c.ShouldBindWith(obj, binding.JSON) } // ShouldBindXML is a shortcut for c.ShouldBindWith(obj, binding.XML). func (c *Context) ShouldBindXML(obj any) error { return c.ShouldBindWith(obj, binding.XML) } // ShouldBindQuery is a shortcut for c.ShouldBindWith(obj, binding.Query). func (c *Context) ShouldBindQuery(obj any) error { return c.ShouldBindWith(obj, binding.Query) } // ShouldBindYAML is a shortcut for c.ShouldBindWith(obj, binding.YAML). func (c *Context) ShouldBindYAML(obj any) error { return c.ShouldBindWith(obj, binding.YAML) } // ShouldBindTOML is a shortcut for c.ShouldBindWith(obj, binding.TOML). func (c *Context) ShouldBindTOML(obj any) error { return c.ShouldBindWith(obj, binding.TOML) } // ShouldBindHeader is a shortcut for c.ShouldBindWith(obj, binding.Header). func (c *Context) ShouldBindHeader(obj any) error { return c.ShouldBindWith(obj, binding.Header) } // ShouldBindUri binds the passed struct pointer using the specified binding engine. func (c *Context) ShouldBindUri(obj any) error { m := make(map[string][]string, len(c.Params)) for _, v := range c.Params { m[v.Key] = []string{v.Value} } return binding.Uri.BindUri(m, obj) } // ShouldBindWith binds the passed struct pointer using the specified binding engine. // See the binding package. func (c *Context) ShouldBindWith(obj any, b binding.Binding) error { return b.Bind(c.Request, obj) } // ShouldBindBodyWith is similar with ShouldBindWith, but it stores the request // body into the context, and reuse when it is called again. // // NOTE: This method reads the body before binding. So you should use // ShouldBindWith for better performance if you need to call only once. func (c *Context) ShouldBindBodyWith(obj any, bb binding.BindingBody) (err error) { var body []byte if cb, ok := c.Get(BodyBytesKey); ok { if cbb, ok := cb.([]byte); ok { body = cbb } } if body == nil { body, err = io.ReadAll(c.Request.Body) if err != nil { return err } c.Set(BodyBytesKey, body) } return bb.BindBody(body, obj) } // ShouldBindBodyWithJSON is a shortcut for c.ShouldBindBodyWith(obj, binding.JSON). func (c *Context) ShouldBindBodyWithJSON(obj any) error { return c.ShouldBindBodyWith(obj, binding.JSON) } // ShouldBindBodyWithXML is a shortcut for c.ShouldBindBodyWith(obj, binding.XML). func (c *Context) ShouldBindBodyWithXML(obj any) error { return c.ShouldBindBodyWith(obj, binding.XML) } // ShouldBindBodyWithYAML is a shortcut for c.ShouldBindBodyWith(obj, binding.YAML). func (c *Context) ShouldBindBodyWithYAML(obj any) error { return c.ShouldBindBodyWith(obj, binding.YAML) } // ShouldBindBodyWithTOML is a shortcut for c.ShouldBindBodyWith(obj, binding.TOML). func (c *Context) ShouldBindBodyWithTOML(obj any) error { return c.ShouldBindBodyWith(obj, binding.TOML) } // ClientIP implements one best effort algorithm to return the real client IP. // It calls c.RemoteIP() under the hood, to check if the remote IP is a trusted proxy or not. // If it is it will then try to parse the headers defined in Engine.RemoteIPHeaders (defaulting to [X-Forwarded-For, X-Real-Ip]). // If the headers are not syntactically valid OR the remote IP does not correspond to a trusted proxy, // the remote IP (coming from Request.RemoteAddr) is returned. func (c *Context) ClientIP() string { // Check if we're running on a trusted platform, continue running backwards if error if c.engine.TrustedPlatform != "" { // Developers can define their own header of Trusted Platform or use predefined constants if addr := c.requestHeader(c.engine.TrustedPlatform); addr != "" { return addr } } // Legacy "AppEngine" flag if c.engine.AppEngine { log.Println(`The AppEngine flag is going to be deprecated. Please check issues #2723 and #2739 and use 'TrustedPlatform: gin.PlatformGoogleAppEngine' instead.`) if addr := c.requestHeader("X-Appengine-Remote-Addr"); addr != "" { return addr } } // It also checks if the remoteIP is a trusted proxy or not. // In order to perform this validation, it will see if the IP is contained within at least one of the CIDR blocks // defined by Engine.SetTrustedProxies() remoteIP := net.ParseIP(c.RemoteIP()) if remoteIP == nil { return "" } trusted := c.engine.isTrustedProxy(remoteIP) if trusted && c.engine.ForwardedByClientIP && c.engine.RemoteIPHeaders != nil { for _, headerName := range c.engine.RemoteIPHeaders { ip, valid := c.engine.validateHeader(c.requestHeader(headerName)) if valid { return ip } } } return remoteIP.String() } // RemoteIP parses the IP from Request.RemoteAddr, normalizes and returns the IP (without the port). func (c *Context) RemoteIP() string { ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)) if err != nil { return "" } return ip } // ContentType returns the Content-Type header of the request. func (c *Context) ContentType() string { return filterFlags(c.requestHeader("Content-Type")) } // IsWebsocket returns true if the request headers indicate that a websocket // handshake is being initiated by the client. func (c *Context) IsWebsocket() bool { if strings.Contains(strings.ToLower(c.requestHeader("Connection")), "upgrade") && strings.EqualFold(c.requestHeader("Upgrade"), "websocket") { return true } return false } func (c *Context) requestHeader(key string) string { return c.Request.Header.Get(key) } /************************************/ /******** RESPONSE RENDERING ********/ /************************************/ // bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function. func bodyAllowedForStatus(status int) bool { switch { case status >= 100 && status <= 199: return false case status == http.StatusNoContent: return false case status == http.StatusNotModified: return false } return true } // Status sets the HTTP response code. func (c *Context) Status(code int) { c.Writer.WriteHeader(code) } // Header is an intelligent shortcut for c.Writer.Header().Set(key, value). // It writes a header in the response. // If value == "", this method removes the header `c.Writer.Header().Del(key)` func (c *Context) Header(key, value string) { if value == "" { c.Writer.Header().Del(key) return } c.Writer.Header().Set(key, value) } // GetHeader returns value from request headers. func (c *Context) GetHeader(key string) string { return c.requestHeader(key) } // GetRawData returns stream data. func (c *Context) GetRawData() ([]byte, error) { if c.Request.Body == nil { return nil, errors.New("cannot read nil body") } return io.ReadAll(c.Request.Body) } // SetSameSite with cookie func (c *Context) SetSameSite(samesite http.SameSite) { c.sameSite = samesite } // SetCookie adds a Set-Cookie header to the ResponseWriter's headers. // The provided cookie must have a valid Name. Invalid cookies may be // silently dropped. func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool) { if path == "" { path = "/" } http.SetCookie(c.Writer, &http.Cookie{ Name: name, Value: url.QueryEscape(value), MaxAge: maxAge, Path: path, Domain: domain, SameSite: c.sameSite, Secure: secure, HttpOnly: httpOnly, }) } // Cookie returns the named cookie provided in the request or // ErrNoCookie if not found. And return the named cookie is unescaped. // If multiple cookies match the given name, only one cookie will // be returned. func (c *Context) Cookie(name string) (string, error) { cookie, err := c.Request.Cookie(name) if err != nil { return "", err } val, _ := url.QueryUnescape(cookie.Value) return val, nil } // Render writes the response headers and calls render.Render to render data. func (c *Context) Render(code int, r render.Render) { c.Status(code) if !bodyAllowedForStatus(code) { r.WriteContentType(c.Writer) c.Writer.WriteHeaderNow() return } if err := r.Render(c.Writer); err != nil { // Pushing error to c.Errors _ = c.Error(err) c.Abort() } } // HTML renders the HTTP template specified by its file name. // It also updates the HTTP code and sets the Content-Type as "text/html". // See http://golang.org/doc/articles/wiki/ func (c *Context) HTML(code int, name string, obj any) { instance := c.engine.HTMLRender.Instance(name, obj) c.Render(code, instance) } // IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body. // It also sets the Content-Type as "application/json". // WARNING: we recommend using this only for development purposes since printing pretty JSON is // more CPU and bandwidth consuming. Use Context.JSON() instead. func (c *Context) IndentedJSON(code int, obj any) { c.Render(code, render.IndentedJSON{Data: obj}) } // SecureJSON serializes the given struct as Secure JSON into the response body. // Default prepends "while(1)," to response body if the given struct is array values. // It also sets the Content-Type as "application/json". func (c *Context) SecureJSON(code int, obj any) { c.Render(code, render.SecureJSON{Prefix: c.engine.secureJSONPrefix, Data: obj}) } // JSONP serializes the given struct as JSON into the response body. // It adds padding to response body to request data from a server residing in a different domain than the client. // It also sets the Content-Type as "application/javascript". func (c *Context) JSONP(code int, obj any) { callback := c.DefaultQuery("callback", "") if callback == "" { c.Render(code, render.JSON{Data: obj}) return } c.Render(code, render.JsonpJSON{Callback: callback, Data: obj}) } // JSON serializes the given struct as JSON into the response body. // It also sets the Content-Type as "application/json". func (c *Context) JSON(code int, obj any) { c.Render(code, render.JSON{Data: obj}) } // AsciiJSON serializes the given struct as JSON into the response body with unicode to ASCII string. // It also sets the Content-Type as "application/json". func (c *Context) AsciiJSON(code int, obj any) { c.Render(code, render.AsciiJSON{Data: obj}) } // PureJSON serializes the given struct as JSON into the response body. // PureJSON, unlike JSON, does not replace special html characters with their unicode entities. func (c *Context) PureJSON(code int, obj any) { c.Render(code, render.PureJSON{Data: obj}) } // XML serializes the given struct as XML into the response body. // It also sets the Content-Type as "application/xml". func (c *Context) XML(code int, obj any) { c.Render(code, render.XML{Data: obj}) } // YAML serializes the given struct as YAML into the response body. func (c *Context) YAML(code int, obj any) { c.Render(code, render.YAML{Data: obj}) } // TOML serializes the given struct as TOML into the response body. func (c *Context) TOML(code int, obj any) { c.Render(code, render.TOML{Data: obj}) } // ProtoBuf serializes the given struct as ProtoBuf into the response body. func (c *Context) ProtoBuf(code int, obj any) { c.Render(code, render.ProtoBuf{Data: obj}) } // String writes the given string into the response body.
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/version.go
vendor/github.com/gin-gonic/gin/version.go
// Copyright 2018 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin // Version is the current gin framework's version. const Version = "v1.10.0"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/response_writer.go
vendor/github.com/gin-gonic/gin/response_writer.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bufio" "io" "net" "net/http" ) const ( noWritten = -1 defaultStatus = http.StatusOK ) // ResponseWriter ... type ResponseWriter interface { http.ResponseWriter http.Hijacker http.Flusher http.CloseNotifier // Status returns the HTTP response status code of the current request. Status() int // Size returns the number of bytes already written into the response http body. // See Written() Size() int // WriteString writes the string into the response body. WriteString(string) (int, error) // Written returns true if the response body was already written. Written() bool // WriteHeaderNow forces to write the http header (status code + headers). WriteHeaderNow() // Pusher get the http.Pusher for server push Pusher() http.Pusher } type responseWriter struct { http.ResponseWriter size int status int } var _ ResponseWriter = (*responseWriter)(nil) func (w *responseWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } func (w *responseWriter) reset(writer http.ResponseWriter) { w.ResponseWriter = writer w.size = noWritten w.status = defaultStatus } func (w *responseWriter) WriteHeader(code int) { if code > 0 && w.status != code { if w.Written() { debugPrint("[WARNING] Headers were already written. Wanted to override status code %d with %d", w.status, code) return } w.status = code } } func (w *responseWriter) WriteHeaderNow() { if !w.Written() { w.size = 0 w.ResponseWriter.WriteHeader(w.status) } } func (w *responseWriter) Write(data []byte) (n int, err error) { w.WriteHeaderNow() n, err = w.ResponseWriter.Write(data) w.size += n return } func (w *responseWriter) WriteString(s string) (n int, err error) { w.WriteHeaderNow() n, err = io.WriteString(w.ResponseWriter, s) w.size += n return } func (w *responseWriter) Status() int { return w.status } func (w *responseWriter) Size() int { return w.size } func (w *responseWriter) Written() bool { return w.size != noWritten } // Hijack implements the http.Hijacker interface. func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { if w.size < 0 { w.size = 0 } return w.ResponseWriter.(http.Hijacker).Hijack() } // CloseNotify implements the http.CloseNotifier interface. func (w *responseWriter) CloseNotify() <-chan bool { return w.ResponseWriter.(http.CloseNotifier).CloseNotify() } // Flush implements the http.Flusher interface. func (w *responseWriter) Flush() { w.WriteHeaderNow() w.ResponseWriter.(http.Flusher).Flush() } func (w *responseWriter) Pusher() (pusher http.Pusher) { if pusher, ok := w.ResponseWriter.(http.Pusher); ok { return pusher } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/doc.go
vendor/github.com/gin-gonic/gin/doc.go
/* Package gin implements a HTTP web framework called gin. See https://gin-gonic.com/ for more information about gin. */ package gin // import "github.com/gin-gonic/gin"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/logger.go
vendor/github.com/gin-gonic/gin/logger.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "io" "net/http" "os" "time" "github.com/mattn/go-isatty" ) type consoleColorModeValue int const ( autoColor consoleColorModeValue = iota disableColor forceColor ) const ( green = "\033[97;42m" white = "\033[90;47m" yellow = "\033[90;43m" red = "\033[97;41m" blue = "\033[97;44m" magenta = "\033[97;45m" cyan = "\033[97;46m" reset = "\033[0m" ) var consoleColorMode = autoColor // LoggerConfig defines the config for Logger middleware. type LoggerConfig struct { // Optional. Default value is gin.defaultLogFormatter Formatter LogFormatter // Output is a writer where logs are written. // Optional. Default value is gin.DefaultWriter. Output io.Writer // SkipPaths is an url path array which logs are not written. // Optional. SkipPaths []string // Skip is a Skipper that indicates which logs should not be written. // Optional. Skip Skipper } // Skipper is a function to skip logs based on provided Context type Skipper func(c *Context) bool // LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter type LogFormatter func(params LogFormatterParams) string // LogFormatterParams is the structure any formatter will be handed when time to log comes type LogFormatterParams struct { Request *http.Request // TimeStamp shows the time after the server returns a response. TimeStamp time.Time // StatusCode is HTTP response code. StatusCode int // Latency is how much time the server cost to process a certain request. Latency time.Duration // ClientIP equals Context's ClientIP method. ClientIP string // Method is the HTTP method given to the request. Method string // Path is a path the client requests. Path string // ErrorMessage is set if error has occurred in processing the request. ErrorMessage string // isTerm shows whether gin's output descriptor refers to a terminal. isTerm bool // BodySize is the size of the Response Body BodySize int // Keys are the keys set on the request's context. Keys map[string]any } // StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal. func (p *LogFormatterParams) StatusCodeColor() string { code := p.StatusCode switch { case code >= http.StatusContinue && code < http.StatusOK: return white case code >= http.StatusOK && code < http.StatusMultipleChoices: return green case code >= http.StatusMultipleChoices && code < http.StatusBadRequest: return white case code >= http.StatusBadRequest && code < http.StatusInternalServerError: return yellow default: return red } } // MethodColor is the ANSI color for appropriately logging http method to a terminal. func (p *LogFormatterParams) MethodColor() string { method := p.Method switch method { case http.MethodGet: return blue case http.MethodPost: return cyan case http.MethodPut: return yellow case http.MethodDelete: return red case http.MethodPatch: return green case http.MethodHead: return magenta case http.MethodOptions: return white default: return reset } } // ResetColor resets all escape attributes. func (p *LogFormatterParams) ResetColor() string { return reset } // IsOutputColor indicates whether can colors be outputted to the log. func (p *LogFormatterParams) IsOutputColor() bool { return consoleColorMode == forceColor || (consoleColorMode == autoColor && p.isTerm) } // defaultLogFormatter is the default log format function Logger middleware uses. var defaultLogFormatter = func(param LogFormatterParams) string { var statusColor, methodColor, resetColor string if param.IsOutputColor() { statusColor = param.StatusCodeColor() methodColor = param.MethodColor() resetColor = param.ResetColor() } if param.Latency > time.Minute { param.Latency = param.Latency.Truncate(time.Second) } return fmt.Sprintf("[GIN] %v |%s %3d %s| %13v | %15s |%s %-7s %s %#v\n%s", param.TimeStamp.Format("2006/01/02 - 15:04:05"), statusColor, param.StatusCode, resetColor, param.Latency, param.ClientIP, methodColor, param.Method, resetColor, param.Path, param.ErrorMessage, ) } // DisableConsoleColor disables color output in the console. func DisableConsoleColor() { consoleColorMode = disableColor } // ForceConsoleColor force color output in the console. func ForceConsoleColor() { consoleColorMode = forceColor } // ErrorLogger returns a HandlerFunc for any error type. func ErrorLogger() HandlerFunc { return ErrorLoggerT(ErrorTypeAny) } // ErrorLoggerT returns a HandlerFunc for a given error type. func ErrorLoggerT(typ ErrorType) HandlerFunc { return func(c *Context) { c.Next() errors := c.Errors.ByType(typ) if len(errors) > 0 { c.JSON(-1, errors) } } } // Logger instances a Logger middleware that will write the logs to gin.DefaultWriter. // By default, gin.DefaultWriter = os.Stdout. func Logger() HandlerFunc { return LoggerWithConfig(LoggerConfig{}) } // LoggerWithFormatter instance a Logger middleware with the specified log format function. func LoggerWithFormatter(f LogFormatter) HandlerFunc { return LoggerWithConfig(LoggerConfig{ Formatter: f, }) } // LoggerWithWriter instance a Logger middleware with the specified writer buffer. // Example: os.Stdout, a file opened in write mode, a socket... func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc { return LoggerWithConfig(LoggerConfig{ Output: out, SkipPaths: notlogged, }) } // LoggerWithConfig instance a Logger middleware with config. func LoggerWithConfig(conf LoggerConfig) HandlerFunc { formatter := conf.Formatter if formatter == nil { formatter = defaultLogFormatter } out := conf.Output if out == nil { out = DefaultWriter } notlogged := conf.SkipPaths isTerm := true if w, ok := out.(*os.File); !ok || os.Getenv("TERM") == "dumb" || (!isatty.IsTerminal(w.Fd()) && !isatty.IsCygwinTerminal(w.Fd())) { isTerm = false } var skip map[string]struct{} if length := len(notlogged); length > 0 { skip = make(map[string]struct{}, length) for _, path := range notlogged { skip[path] = struct{}{} } } return func(c *Context) { // Start timer start := time.Now() path := c.Request.URL.Path raw := c.Request.URL.RawQuery // Process request c.Next() // Log only when it is not being skipped if _, ok := skip[path]; ok || (conf.Skip != nil && conf.Skip(c)) { return } param := LogFormatterParams{ Request: c.Request, isTerm: isTerm, Keys: c.Keys, } // Stop timer param.TimeStamp = time.Now() param.Latency = param.TimeStamp.Sub(start) param.ClientIP = c.ClientIP() param.Method = c.Request.Method param.StatusCode = c.Writer.Status() param.ErrorMessage = c.Errors.ByType(ErrorTypePrivate).String() param.BodySize = c.Writer.Size() if raw != "" { path = path + "?" + raw } param.Path = path fmt.Fprint(out, formatter(param)) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/fs.go
vendor/github.com/gin-gonic/gin/fs.go
// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "net/http" "os" ) type onlyFilesFS struct { fs http.FileSystem } type neuteredReaddirFile struct { http.File } // Dir returns a http.FileSystem that can be used by http.FileServer(). It is used internally // in router.Static(). // if listDirectory == true, then it works the same as http.Dir() otherwise it returns // a filesystem that prevents http.FileServer() to list the directory files. func Dir(root string, listDirectory bool) http.FileSystem { fs := http.Dir(root) if listDirectory { return fs } return &onlyFilesFS{fs} } // Open conforms to http.Filesystem. func (fs onlyFilesFS) Open(name string) (http.File, error) { f, err := fs.fs.Open(name) if err != nil { return nil, err } return neuteredReaddirFile{f}, nil } // Readdir overrides the http.File default implementation. func (f neuteredReaddirFile) Readdir(_ int) ([]os.FileInfo, error) { // this disables directory listing return nil, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/internal/json/json.go
vendor/github.com/gin-gonic/gin/internal/json/json.go
// Copyright 2017 Bo-Yi Wu. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !jsoniter && !go_json && !(sonic && avx && (linux || windows || darwin) && amd64) package json import "encoding/json" var ( // Marshal is exported by gin/json package. Marshal = json.Marshal // Unmarshal is exported by gin/json package. Unmarshal = json.Unmarshal // MarshalIndent is exported by gin/json package. MarshalIndent = json.MarshalIndent // NewDecoder is exported by gin/json package. NewDecoder = json.NewDecoder // NewEncoder is exported by gin/json package. NewEncoder = json.NewEncoder )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/internal/json/jsoniter.go
vendor/github.com/gin-gonic/gin/internal/json/jsoniter.go
// Copyright 2017 Bo-Yi Wu. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build jsoniter package json import jsoniter "github.com/json-iterator/go" var ( json = jsoniter.ConfigCompatibleWithStandardLibrary // Marshal is exported by gin/json package. Marshal = json.Marshal // Unmarshal is exported by gin/json package. Unmarshal = json.Unmarshal // MarshalIndent is exported by gin/json package. MarshalIndent = json.MarshalIndent // NewDecoder is exported by gin/json package. NewDecoder = json.NewDecoder // NewEncoder is exported by gin/json package. NewEncoder = json.NewEncoder )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/internal/json/sonic.go
vendor/github.com/gin-gonic/gin/internal/json/sonic.go
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build sonic && avx && (linux || windows || darwin) && amd64 package json import "github.com/bytedance/sonic" var ( json = sonic.ConfigStd // Marshal is exported by gin/json package. Marshal = json.Marshal // Unmarshal is exported by gin/json package. Unmarshal = json.Unmarshal // MarshalIndent is exported by gin/json package. MarshalIndent = json.MarshalIndent // NewDecoder is exported by gin/json package. NewDecoder = json.NewDecoder // NewEncoder is exported by gin/json package. NewEncoder = json.NewEncoder )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/internal/json/go_json.go
vendor/github.com/gin-gonic/gin/internal/json/go_json.go
// Copyright 2017 Bo-Yi Wu. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build go_json package json import json "github.com/goccy/go-json" var ( // Marshal is exported by gin/json package. Marshal = json.Marshal // Unmarshal is exported by gin/json package. Unmarshal = json.Unmarshal // MarshalIndent is exported by gin/json package. MarshalIndent = json.MarshalIndent // NewDecoder is exported by gin/json package. NewDecoder = json.NewDecoder // NewEncoder is exported by gin/json package. NewEncoder = json.NewEncoder )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/internal/bytesconv/bytesconv_1.20.go
vendor/github.com/gin-gonic/gin/internal/bytesconv/bytesconv_1.20.go
// Copyright 2023 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build go1.20 package bytesconv import ( "unsafe" ) // StringToBytes converts string to byte slice without a memory allocation. // For more details, see https://github.com/golang/go/issues/53003#issuecomment-1140276077. func StringToBytes(s string) []byte { return unsafe.Slice(unsafe.StringData(s), len(s)) } // BytesToString converts byte slice to string without a memory allocation. // For more details, see https://github.com/golang/go/issues/53003#issuecomment-1140276077. func BytesToString(b []byte) string { return unsafe.String(unsafe.SliceData(b), len(b)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/internal/bytesconv/bytesconv_1.19.go
vendor/github.com/gin-gonic/gin/internal/bytesconv/bytesconv_1.19.go
// Copyright 2020 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !go1.20 package bytesconv import ( "unsafe" ) // StringToBytes converts string to byte slice without a memory allocation. func StringToBytes(s string) []byte { return *(*[]byte)(unsafe.Pointer( &struct { string Cap int }{s, len(s)}, )) } // BytesToString converts byte slice to string without a memory allocation. func BytesToString(b []byte) string { return *(*string)(unsafe.Pointer(&b)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/render/json.go
vendor/github.com/gin-gonic/gin/render/json.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "bytes" "fmt" "html/template" "net/http" "github.com/gin-gonic/gin/internal/bytesconv" "github.com/gin-gonic/gin/internal/json" ) // JSON contains the given interface object. type JSON struct { Data any } // IndentedJSON contains the given interface object. type IndentedJSON struct { Data any } // SecureJSON contains the given interface object and its prefix. type SecureJSON struct { Prefix string Data any } // JsonpJSON contains the given interface object its callback. type JsonpJSON struct { Callback string Data any } // AsciiJSON contains the given interface object. type AsciiJSON struct { Data any } // PureJSON contains the given interface object. type PureJSON struct { Data any } var ( jsonContentType = []string{"application/json; charset=utf-8"} jsonpContentType = []string{"application/javascript; charset=utf-8"} jsonASCIIContentType = []string{"application/json"} ) // Render (JSON) writes data with custom ContentType. func (r JSON) Render(w http.ResponseWriter) error { return WriteJSON(w, r.Data) } // WriteContentType (JSON) writes JSON ContentType. func (r JSON) WriteContentType(w http.ResponseWriter) { writeContentType(w, jsonContentType) } // WriteJSON marshals the given interface object and writes it with custom ContentType. func WriteJSON(w http.ResponseWriter, obj any) error { writeContentType(w, jsonContentType) jsonBytes, err := json.Marshal(obj) if err != nil { return err } _, err = w.Write(jsonBytes) return err } // Render (IndentedJSON) marshals the given interface object and writes it with custom ContentType. func (r IndentedJSON) Render(w http.ResponseWriter) error { r.WriteContentType(w) jsonBytes, err := json.MarshalIndent(r.Data, "", " ") if err != nil { return err } _, err = w.Write(jsonBytes) return err } // WriteContentType (IndentedJSON) writes JSON ContentType. func (r IndentedJSON) WriteContentType(w http.ResponseWriter) { writeContentType(w, jsonContentType) } // Render (SecureJSON) marshals the given interface object and writes it with custom ContentType. func (r SecureJSON) Render(w http.ResponseWriter) error { r.WriteContentType(w) jsonBytes, err := json.Marshal(r.Data) if err != nil { return err } // if the jsonBytes is array values if bytes.HasPrefix(jsonBytes, bytesconv.StringToBytes("[")) && bytes.HasSuffix(jsonBytes, bytesconv.StringToBytes("]")) { if _, err = w.Write(bytesconv.StringToBytes(r.Prefix)); err != nil { return err } } _, err = w.Write(jsonBytes) return err } // WriteContentType (SecureJSON) writes JSON ContentType. func (r SecureJSON) WriteContentType(w http.ResponseWriter) { writeContentType(w, jsonContentType) } // Render (JsonpJSON) marshals the given interface object and writes it and its callback with custom ContentType. func (r JsonpJSON) Render(w http.ResponseWriter) (err error) { r.WriteContentType(w) ret, err := json.Marshal(r.Data) if err != nil { return err } if r.Callback == "" { _, err = w.Write(ret) return err } callback := template.JSEscapeString(r.Callback) if _, err = w.Write(bytesconv.StringToBytes(callback)); err != nil { return err } if _, err = w.Write(bytesconv.StringToBytes("(")); err != nil { return err } if _, err = w.Write(ret); err != nil { return err } if _, err = w.Write(bytesconv.StringToBytes(");")); err != nil { return err } return nil } // WriteContentType (JsonpJSON) writes Javascript ContentType. func (r JsonpJSON) WriteContentType(w http.ResponseWriter) { writeContentType(w, jsonpContentType) } // Render (AsciiJSON) marshals the given interface object and writes it with custom ContentType. func (r AsciiJSON) Render(w http.ResponseWriter) (err error) { r.WriteContentType(w) ret, err := json.Marshal(r.Data) if err != nil { return err } var buffer bytes.Buffer for _, r := range bytesconv.BytesToString(ret) { cvt := string(r) if r >= 128 { cvt = fmt.Sprintf("\\u%04x", int64(r)) } buffer.WriteString(cvt) } _, err = w.Write(buffer.Bytes()) return err } // WriteContentType (AsciiJSON) writes JSON ContentType. func (r AsciiJSON) WriteContentType(w http.ResponseWriter) { writeContentType(w, jsonASCIIContentType) } // Render (PureJSON) writes custom ContentType and encodes the given interface object. func (r PureJSON) Render(w http.ResponseWriter) error { r.WriteContentType(w) encoder := json.NewEncoder(w) encoder.SetEscapeHTML(false) return encoder.Encode(r.Data) } // WriteContentType (PureJSON) writes custom ContentType. func (r PureJSON) WriteContentType(w http.ResponseWriter) { writeContentType(w, jsonContentType) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/render/text.go
vendor/github.com/gin-gonic/gin/render/text.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "fmt" "net/http" "github.com/gin-gonic/gin/internal/bytesconv" ) // String contains the given interface object slice and its format. type String struct { Format string Data []any } var plainContentType = []string{"text/plain; charset=utf-8"} // Render (String) writes data with custom ContentType. func (r String) Render(w http.ResponseWriter) error { return WriteString(w, r.Format, r.Data) } // WriteContentType (String) writes Plain ContentType. func (r String) WriteContentType(w http.ResponseWriter) { writeContentType(w, plainContentType) } // WriteString writes data according to its format and write custom ContentType. func WriteString(w http.ResponseWriter, format string, data []any) (err error) { writeContentType(w, plainContentType) if len(data) > 0 { _, err = fmt.Fprintf(w, format, data...) return } _, err = w.Write(bytesconv.StringToBytes(format)) return }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/render/data.go
vendor/github.com/gin-gonic/gin/render/data.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import "net/http" // Data contains ContentType and bytes data. type Data struct { ContentType string Data []byte } // Render (Data) writes data with custom ContentType. func (r Data) Render(w http.ResponseWriter) (err error) { r.WriteContentType(w) _, err = w.Write(r.Data) return } // WriteContentType (Data) writes custom ContentType. func (r Data) WriteContentType(w http.ResponseWriter) { writeContentType(w, []string{r.ContentType}) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/render/xml.go
vendor/github.com/gin-gonic/gin/render/xml.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "encoding/xml" "net/http" ) // XML contains the given interface object. type XML struct { Data any } var xmlContentType = []string{"application/xml; charset=utf-8"} // Render (XML) encodes the given interface object and writes data with custom ContentType. func (r XML) Render(w http.ResponseWriter) error { r.WriteContentType(w) return xml.NewEncoder(w).Encode(r.Data) } // WriteContentType (XML) writes XML ContentType for response. func (r XML) WriteContentType(w http.ResponseWriter) { writeContentType(w, xmlContentType) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/render/msgpack.go
vendor/github.com/gin-gonic/gin/render/msgpack.go
// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !nomsgpack package render import ( "net/http" "github.com/ugorji/go/codec" ) // Check interface implemented here to support go build tag nomsgpack. // See: https://github.com/gin-gonic/gin/pull/1852/ var ( _ Render = MsgPack{} ) // MsgPack contains the given interface object. type MsgPack struct { Data any } var msgpackContentType = []string{"application/msgpack; charset=utf-8"} // WriteContentType (MsgPack) writes MsgPack ContentType. func (r MsgPack) WriteContentType(w http.ResponseWriter) { writeContentType(w, msgpackContentType) } // Render (MsgPack) encodes the given interface object and writes data with custom ContentType. func (r MsgPack) Render(w http.ResponseWriter) error { return WriteMsgPack(w, r.Data) } // WriteMsgPack writes MsgPack ContentType and encodes the given interface object. func WriteMsgPack(w http.ResponseWriter, obj any) error { writeContentType(w, msgpackContentType) var mh codec.MsgpackHandle return codec.NewEncoder(w, &mh).Encode(obj) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/render/render.go
vendor/github.com/gin-gonic/gin/render/render.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import "net/http" // Render interface is to be implemented by JSON, XML, HTML, YAML and so on. type Render interface { // Render writes data with custom ContentType. Render(http.ResponseWriter) error // WriteContentType writes custom ContentType. WriteContentType(w http.ResponseWriter) } var ( _ Render = (*JSON)(nil) _ Render = (*IndentedJSON)(nil) _ Render = (*SecureJSON)(nil) _ Render = (*JsonpJSON)(nil) _ Render = (*XML)(nil) _ Render = (*String)(nil) _ Render = (*Redirect)(nil) _ Render = (*Data)(nil) _ Render = (*HTML)(nil) _ HTMLRender = (*HTMLDebug)(nil) _ HTMLRender = (*HTMLProduction)(nil) _ Render = (*YAML)(nil) _ Render = (*Reader)(nil) _ Render = (*AsciiJSON)(nil) _ Render = (*ProtoBuf)(nil) _ Render = (*TOML)(nil) ) func writeContentType(w http.ResponseWriter, value []string) { header := w.Header() if val := header["Content-Type"]; len(val) == 0 { header["Content-Type"] = value } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/render/reader.go
vendor/github.com/gin-gonic/gin/render/reader.go
// Copyright 2018 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "io" "net/http" "strconv" ) // Reader contains the IO reader and its length, and custom ContentType and other headers. type Reader struct { ContentType string ContentLength int64 Reader io.Reader Headers map[string]string } // Render (Reader) writes data with custom ContentType and headers. func (r Reader) Render(w http.ResponseWriter) (err error) { r.WriteContentType(w) if r.ContentLength >= 0 { if r.Headers == nil { r.Headers = map[string]string{} } r.Headers["Content-Length"] = strconv.FormatInt(r.ContentLength, 10) } r.writeHeaders(w, r.Headers) _, err = io.Copy(w, r.Reader) return } // WriteContentType (Reader) writes custom ContentType. func (r Reader) WriteContentType(w http.ResponseWriter) { writeContentType(w, []string{r.ContentType}) } // writeHeaders writes custom Header. func (r Reader) writeHeaders(w http.ResponseWriter, headers map[string]string) { header := w.Header() for k, v := range headers { if header.Get(k) == "" { header.Set(k, v) } } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/render/yaml.go
vendor/github.com/gin-gonic/gin/render/yaml.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "net/http" "gopkg.in/yaml.v3" ) // YAML contains the given interface object. type YAML struct { Data any } var yamlContentType = []string{"application/yaml; charset=utf-8"} // Render (YAML) marshals the given interface object and writes data with custom ContentType. func (r YAML) Render(w http.ResponseWriter) error { r.WriteContentType(w) bytes, err := yaml.Marshal(r.Data) if err != nil { return err } _, err = w.Write(bytes) return err } // WriteContentType (YAML) writes YAML ContentType for response. func (r YAML) WriteContentType(w http.ResponseWriter) { writeContentType(w, yamlContentType) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/render/protobuf.go
vendor/github.com/gin-gonic/gin/render/protobuf.go
// Copyright 2018 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "net/http" "google.golang.org/protobuf/proto" ) // ProtoBuf contains the given interface object. type ProtoBuf struct { Data any } var protobufContentType = []string{"application/x-protobuf"} // Render (ProtoBuf) marshals the given interface object and writes data with custom ContentType. func (r ProtoBuf) Render(w http.ResponseWriter) error { r.WriteContentType(w) bytes, err := proto.Marshal(r.Data.(proto.Message)) if err != nil { return err } _, err = w.Write(bytes) return err } // WriteContentType (ProtoBuf) writes ProtoBuf ContentType. func (r ProtoBuf) WriteContentType(w http.ResponseWriter) { writeContentType(w, protobufContentType) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/render/html.go
vendor/github.com/gin-gonic/gin/render/html.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "html/template" "net/http" ) // Delims represents a set of Left and Right delimiters for HTML template rendering. type Delims struct { // Left delimiter, defaults to {{. Left string // Right delimiter, defaults to }}. Right string } // HTMLRender interface is to be implemented by HTMLProduction and HTMLDebug. type HTMLRender interface { // Instance returns an HTML instance. Instance(string, any) Render } // HTMLProduction contains template reference and its delims. type HTMLProduction struct { Template *template.Template Delims Delims } // HTMLDebug contains template delims and pattern and function with file list. type HTMLDebug struct { Files []string Glob string Delims Delims FuncMap template.FuncMap } // HTML contains template reference and its name with given interface object. type HTML struct { Template *template.Template Name string Data any } var htmlContentType = []string{"text/html; charset=utf-8"} // Instance (HTMLProduction) returns an HTML instance which it realizes Render interface. func (r HTMLProduction) Instance(name string, data any) Render { return HTML{ Template: r.Template, Name: name, Data: data, } } // Instance (HTMLDebug) returns an HTML instance which it realizes Render interface. func (r HTMLDebug) Instance(name string, data any) Render { return HTML{ Template: r.loadTemplate(), Name: name, Data: data, } } func (r HTMLDebug) loadTemplate() *template.Template { if r.FuncMap == nil { r.FuncMap = template.FuncMap{} } if len(r.Files) > 0 { return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseFiles(r.Files...)) } if r.Glob != "" { return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseGlob(r.Glob)) } panic("the HTML debug render was created without files or glob pattern") } // Render (HTML) executes template and writes its result with custom ContentType for response. func (r HTML) Render(w http.ResponseWriter) error { r.WriteContentType(w) if r.Name == "" { return r.Template.Execute(w, r.Data) } return r.Template.ExecuteTemplate(w, r.Name, r.Data) } // WriteContentType (HTML) writes HTML ContentType. func (r HTML) WriteContentType(w http.ResponseWriter) { writeContentType(w, htmlContentType) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/render/redirect.go
vendor/github.com/gin-gonic/gin/render/redirect.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "fmt" "net/http" ) // Redirect contains the http request reference and redirects status code and location. type Redirect struct { Code int Request *http.Request Location string } // Render (Redirect) redirects the http request to new location and writes redirect response. func (r Redirect) Render(w http.ResponseWriter) error { if (r.Code < http.StatusMultipleChoices || r.Code > http.StatusPermanentRedirect) && r.Code != http.StatusCreated { panic(fmt.Sprintf("Cannot redirect with status code %d", r.Code)) } http.Redirect(w, r.Request, r.Location, r.Code) return nil } // WriteContentType (Redirect) don't write any ContentType. func (r Redirect) WriteContentType(http.ResponseWriter) {}
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/render/toml.go
vendor/github.com/gin-gonic/gin/render/toml.go
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "net/http" "github.com/pelletier/go-toml/v2" ) // TOML contains the given interface object. type TOML struct { Data any } var TOMLContentType = []string{"application/toml; charset=utf-8"} // Render (TOML) marshals the given interface object and writes data with custom ContentType. func (r TOML) Render(w http.ResponseWriter) error { r.WriteContentType(w) bytes, err := toml.Marshal(r.Data) if err != nil { return err } _, err = w.Write(bytes) return err } // WriteContentType (TOML) writes TOML ContentType for response. func (r TOML) WriteContentType(w http.ResponseWriter) { writeContentType(w, TOMLContentType) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/binding/json.go
vendor/github.com/gin-gonic/gin/binding/json.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "bytes" "errors" "io" "net/http" "github.com/gin-gonic/gin/internal/json" ) // EnableDecoderUseNumber is used to call the UseNumber method on the JSON // Decoder instance. UseNumber causes the Decoder to unmarshal a number into an // any as a Number instead of as a float64. var EnableDecoderUseNumber = false // EnableDecoderDisallowUnknownFields is used to call the DisallowUnknownFields method // on the JSON Decoder instance. DisallowUnknownFields causes the Decoder to // return an error when the destination is a struct and the input contains object // keys which do not match any non-ignored, exported fields in the destination. var EnableDecoderDisallowUnknownFields = false type jsonBinding struct{} func (jsonBinding) Name() string { return "json" } func (jsonBinding) Bind(req *http.Request, obj any) error { if req == nil || req.Body == nil { return errors.New("invalid request") } return decodeJSON(req.Body, obj) } func (jsonBinding) BindBody(body []byte, obj any) error { return decodeJSON(bytes.NewReader(body), obj) } func decodeJSON(r io.Reader, obj any) error { decoder := json.NewDecoder(r) if EnableDecoderUseNumber { decoder.UseNumber() } if EnableDecoderDisallowUnknownFields { decoder.DisallowUnknownFields() } if err := decoder.Decode(obj); err != nil { return err } return validate(obj) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/binding/form.go
vendor/github.com/gin-gonic/gin/binding/form.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "errors" "net/http" ) const defaultMemory = 32 << 20 type formBinding struct{} type formPostBinding struct{} type formMultipartBinding struct{} func (formBinding) Name() string { return "form" } func (formBinding) Bind(req *http.Request, obj any) error { if err := req.ParseForm(); err != nil { return err } if err := req.ParseMultipartForm(defaultMemory); err != nil && !errors.Is(err, http.ErrNotMultipart) { return err } if err := mapForm(obj, req.Form); err != nil { return err } return validate(obj) } func (formPostBinding) Name() string { return "form-urlencoded" } func (formPostBinding) Bind(req *http.Request, obj any) error { if err := req.ParseForm(); err != nil { return err } if err := mapForm(obj, req.PostForm); err != nil { return err } return validate(obj) } func (formMultipartBinding) Name() string { return "multipart/form-data" } func (formMultipartBinding) Bind(req *http.Request, obj any) error { if err := req.ParseMultipartForm(defaultMemory); err != nil { return err } if err := mappingByPtr(obj, (*multipartRequest)(req), "form"); err != nil { return err } return validate(obj) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/binding/xml.go
vendor/github.com/gin-gonic/gin/binding/xml.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "bytes" "encoding/xml" "io" "net/http" ) type xmlBinding struct{} func (xmlBinding) Name() string { return "xml" } func (xmlBinding) Bind(req *http.Request, obj any) error { return decodeXML(req.Body, obj) } func (xmlBinding) BindBody(body []byte, obj any) error { return decodeXML(bytes.NewReader(body), obj) } func decodeXML(r io.Reader, obj any) error { decoder := xml.NewDecoder(r) if err := decoder.Decode(obj); err != nil { return err } return validate(obj) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/binding/uri.go
vendor/github.com/gin-gonic/gin/binding/uri.go
// Copyright 2018 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding type uriBinding struct{} func (uriBinding) Name() string { return "uri" } func (uriBinding) BindUri(m map[string][]string, obj any) error { if err := mapURI(obj, m); err != nil { return err } return validate(obj) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/binding/binding.go
vendor/github.com/gin-gonic/gin/binding/binding.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !nomsgpack package binding import "net/http" // Content-Type MIME of the most common data formats. const ( MIMEJSON = "application/json" MIMEHTML = "text/html" MIMEXML = "application/xml" MIMEXML2 = "text/xml" MIMEPlain = "text/plain" MIMEPOSTForm = "application/x-www-form-urlencoded" MIMEMultipartPOSTForm = "multipart/form-data" MIMEPROTOBUF = "application/x-protobuf" MIMEMSGPACK = "application/x-msgpack" MIMEMSGPACK2 = "application/msgpack" MIMEYAML = "application/x-yaml" MIMEYAML2 = "application/yaml" MIMETOML = "application/toml" ) // Binding describes the interface which needs to be implemented for binding the // data present in the request such as JSON request body, query parameters or // the form POST. type Binding interface { Name() string Bind(*http.Request, any) error } // BindingBody adds BindBody method to Binding. BindBody is similar with Bind, // but it reads the body from supplied bytes instead of req.Body. type BindingBody interface { Binding BindBody([]byte, any) error } // BindingUri adds BindUri method to Binding. BindUri is similar with Bind, // but it reads the Params. type BindingUri interface { Name() string BindUri(map[string][]string, any) error } // StructValidator is the minimal interface which needs to be implemented in // order for it to be used as the validator engine for ensuring the correctness // of the request. Gin provides a default implementation for this using // https://github.com/go-playground/validator/tree/v10.6.1. type StructValidator interface { // ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right. // If the received type is a slice|array, the validation should be performed travel on every element. // If the received type is not a struct or slice|array, any validation should be skipped and nil must be returned. // If the received type is a struct or pointer to a struct, the validation should be performed. // If the struct is not valid or the validation itself fails, a descriptive error should be returned. // Otherwise nil must be returned. ValidateStruct(any) error // Engine returns the underlying validator engine which powers the // StructValidator implementation. Engine() any } // Validator is the default validator which implements the StructValidator // interface. It uses https://github.com/go-playground/validator/tree/v10.6.1 // under the hood. var Validator StructValidator = &defaultValidator{} // These implement the Binding interface and can be used to bind the data // present in the request to struct instances. var ( JSON BindingBody = jsonBinding{} XML BindingBody = xmlBinding{} Form Binding = formBinding{} Query Binding = queryBinding{} FormPost Binding = formPostBinding{} FormMultipart Binding = formMultipartBinding{} ProtoBuf BindingBody = protobufBinding{} MsgPack BindingBody = msgpackBinding{} YAML BindingBody = yamlBinding{} Uri BindingUri = uriBinding{} Header Binding = headerBinding{} TOML BindingBody = tomlBinding{} ) // Default returns the appropriate Binding instance based on the HTTP method // and the content type. func Default(method, contentType string) Binding { if method == http.MethodGet { return Form } switch contentType { case MIMEJSON: return JSON case MIMEXML, MIMEXML2: return XML case MIMEPROTOBUF: return ProtoBuf case MIMEMSGPACK, MIMEMSGPACK2: return MsgPack case MIMEYAML, MIMEYAML2: return YAML case MIMETOML: return TOML case MIMEMultipartPOSTForm: return FormMultipart default: // case MIMEPOSTForm: return Form } } func validate(obj any) error { if Validator == nil { return nil } return Validator.ValidateStruct(obj) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/binding/msgpack.go
vendor/github.com/gin-gonic/gin/binding/msgpack.go
// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !nomsgpack package binding import ( "bytes" "io" "net/http" "github.com/ugorji/go/codec" ) type msgpackBinding struct{} func (msgpackBinding) Name() string { return "msgpack" } func (msgpackBinding) Bind(req *http.Request, obj any) error { return decodeMsgPack(req.Body, obj) } func (msgpackBinding) BindBody(body []byte, obj any) error { return decodeMsgPack(bytes.NewReader(body), obj) } func decodeMsgPack(r io.Reader, obj any) error { cdc := new(codec.MsgpackHandle) if err := codec.NewDecoder(r, cdc).Decode(&obj); err != nil { return err } return validate(obj) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/binding/yaml.go
vendor/github.com/gin-gonic/gin/binding/yaml.go
// Copyright 2018 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "bytes" "io" "net/http" "gopkg.in/yaml.v3" ) type yamlBinding struct{} func (yamlBinding) Name() string { return "yaml" } func (yamlBinding) Bind(req *http.Request, obj any) error { return decodeYAML(req.Body, obj) } func (yamlBinding) BindBody(body []byte, obj any) error { return decodeYAML(bytes.NewReader(body), obj) } func decodeYAML(r io.Reader, obj any) error { decoder := yaml.NewDecoder(r) if err := decoder.Decode(obj); err != nil { return err } return validate(obj) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/binding/default_validator.go
vendor/github.com/gin-gonic/gin/binding/default_validator.go
// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "fmt" "reflect" "strings" "sync" "github.com/go-playground/validator/v10" ) type defaultValidator struct { once sync.Once validate *validator.Validate } type SliceValidationError []error // Error concatenates all error elements in SliceValidationError into a single string separated by \n. func (err SliceValidationError) Error() string { n := len(err) switch n { case 0: return "" default: var b strings.Builder if err[0] != nil { fmt.Fprintf(&b, "[%d]: %s", 0, err[0].Error()) } if n > 1 { for i := 1; i < n; i++ { if err[i] != nil { b.WriteString("\n") fmt.Fprintf(&b, "[%d]: %s", i, err[i].Error()) } } } return b.String() } } var _ StructValidator = (*defaultValidator)(nil) // ValidateStruct receives any kind of type, but only performed struct or pointer to struct type. func (v *defaultValidator) ValidateStruct(obj any) error { if obj == nil { return nil } value := reflect.ValueOf(obj) switch value.Kind() { case reflect.Ptr: if value.Elem().Kind() != reflect.Struct { return v.ValidateStruct(value.Elem().Interface()) } return v.validateStruct(obj) case reflect.Struct: return v.validateStruct(obj) case reflect.Slice, reflect.Array: count := value.Len() validateRet := make(SliceValidationError, 0) for i := 0; i < count; i++ { if err := v.ValidateStruct(value.Index(i).Interface()); err != nil { validateRet = append(validateRet, err) } } if len(validateRet) == 0 { return nil } return validateRet default: return nil } } // validateStruct receives struct type func (v *defaultValidator) validateStruct(obj any) error { v.lazyinit() return v.validate.Struct(obj) } // Engine returns the underlying validator engine which powers the default // Validator instance. This is useful if you want to register custom validations // or struct level validations. See validator GoDoc for more info - // https://pkg.go.dev/github.com/go-playground/validator/v10 func (v *defaultValidator) Engine() any { v.lazyinit() return v.validate } func (v *defaultValidator) lazyinit() { v.once.Do(func() { v.validate = validator.New() v.validate.SetTagName("binding") }) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/binding/protobuf.go
vendor/github.com/gin-gonic/gin/binding/protobuf.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "errors" "io" "net/http" "google.golang.org/protobuf/proto" ) type protobufBinding struct{} func (protobufBinding) Name() string { return "protobuf" } func (b protobufBinding) Bind(req *http.Request, obj any) error { buf, err := io.ReadAll(req.Body) if err != nil { return err } return b.BindBody(buf, obj) } func (protobufBinding) BindBody(body []byte, obj any) error { msg, ok := obj.(proto.Message) if !ok { return errors.New("obj is not ProtoMessage") } if err := proto.Unmarshal(body, msg); err != nil { return err } // Here it's same to return validate(obj), but util now we can't add // `binding:""` to the struct which automatically generate by gen-proto return nil // return validate(obj) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/binding/header.go
vendor/github.com/gin-gonic/gin/binding/header.go
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "net/http" "net/textproto" "reflect" ) type headerBinding struct{} func (headerBinding) Name() string { return "header" } func (headerBinding) Bind(req *http.Request, obj any) error { if err := mapHeader(obj, req.Header); err != nil { return err } return validate(obj) } func mapHeader(ptr any, h map[string][]string) error { return mappingByPtr(ptr, headerSource(h), "header") } type headerSource map[string][]string var _ setter = headerSource(nil) func (hs headerSource) TrySet(value reflect.Value, field reflect.StructField, tagValue string, opt setOptions) (bool, error) { return setByForm(value, field, hs, textproto.CanonicalMIMEHeaderKey(tagValue), opt) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/binding/binding_nomsgpack.go
vendor/github.com/gin-gonic/gin/binding/binding_nomsgpack.go
// Copyright 2020 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build nomsgpack package binding import "net/http" // Content-Type MIME of the most common data formats. const ( MIMEJSON = "application/json" MIMEHTML = "text/html" MIMEXML = "application/xml" MIMEXML2 = "text/xml" MIMEPlain = "text/plain" MIMEPOSTForm = "application/x-www-form-urlencoded" MIMEMultipartPOSTForm = "multipart/form-data" MIMEPROTOBUF = "application/x-protobuf" MIMEYAML = "application/x-yaml" MIMEYAML2 = "application/yaml" MIMETOML = "application/toml" ) // Binding describes the interface which needs to be implemented for binding the // data present in the request such as JSON request body, query parameters or // the form POST. type Binding interface { Name() string Bind(*http.Request, any) error } // BindingBody adds BindBody method to Binding. BindBody is similar with Bind, // but it reads the body from supplied bytes instead of req.Body. type BindingBody interface { Binding BindBody([]byte, any) error } // BindingUri adds BindUri method to Binding. BindUri is similar with Bind, // but it reads the Params. type BindingUri interface { Name() string BindUri(map[string][]string, any) error } // StructValidator is the minimal interface which needs to be implemented in // order for it to be used as the validator engine for ensuring the correctness // of the request. Gin provides a default implementation for this using // https://github.com/go-playground/validator/tree/v10.6.1. type StructValidator interface { // ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right. // If the received type is not a struct, any validation should be skipped and nil must be returned. // If the received type is a struct or pointer to a struct, the validation should be performed. // If the struct is not valid or the validation itself fails, a descriptive error should be returned. // Otherwise nil must be returned. ValidateStruct(any) error // Engine returns the underlying validator engine which powers the // StructValidator implementation. Engine() any } // Validator is the default validator which implements the StructValidator // interface. It uses https://github.com/go-playground/validator/tree/v10.6.1 // under the hood. var Validator StructValidator = &defaultValidator{} // These implement the Binding interface and can be used to bind the data // present in the request to struct instances. var ( JSON = jsonBinding{} XML = xmlBinding{} Form = formBinding{} Query = queryBinding{} FormPost = formPostBinding{} FormMultipart = formMultipartBinding{} ProtoBuf = protobufBinding{} YAML = yamlBinding{} Uri = uriBinding{} Header = headerBinding{} TOML = tomlBinding{} ) // Default returns the appropriate Binding instance based on the HTTP method // and the content type. func Default(method, contentType string) Binding { if method == "GET" { return Form } switch contentType { case MIMEJSON: return JSON case MIMEXML, MIMEXML2: return XML case MIMEPROTOBUF: return ProtoBuf case MIMEYAML, MIMEYAML2: return YAML case MIMEMultipartPOSTForm: return FormMultipart case MIMETOML: return TOML default: // case MIMEPOSTForm: return Form } } func validate(obj any) error { if Validator == nil { return nil } return Validator.ValidateStruct(obj) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/binding/multipart_form_mapping.go
vendor/github.com/gin-gonic/gin/binding/multipart_form_mapping.go
// Copyright 2019 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "errors" "mime/multipart" "net/http" "reflect" ) type multipartRequest http.Request var _ setter = (*multipartRequest)(nil) var ( // ErrMultiFileHeader multipart.FileHeader invalid ErrMultiFileHeader = errors.New("unsupported field type for multipart.FileHeader") // ErrMultiFileHeaderLenInvalid array for []*multipart.FileHeader len invalid ErrMultiFileHeaderLenInvalid = errors.New("unsupported len of array for []*multipart.FileHeader") ) // TrySet tries to set a value by the multipart request with the binding a form file func (r *multipartRequest) TrySet(value reflect.Value, field reflect.StructField, key string, opt setOptions) (bool, error) { if files := r.MultipartForm.File[key]; len(files) != 0 { return setByMultipartFormFile(value, field, files) } return setByForm(value, field, r.MultipartForm.Value, key, opt) } func setByMultipartFormFile(value reflect.Value, field reflect.StructField, files []*multipart.FileHeader) (isSet bool, err error) { switch value.Kind() { case reflect.Ptr: switch value.Interface().(type) { case *multipart.FileHeader: value.Set(reflect.ValueOf(files[0])) return true, nil } case reflect.Struct: switch value.Interface().(type) { case multipart.FileHeader: value.Set(reflect.ValueOf(*files[0])) return true, nil } case reflect.Slice: slice := reflect.MakeSlice(value.Type(), len(files), len(files)) isSet, err = setArrayOfMultipartFormFiles(slice, field, files) if err != nil || !isSet { return isSet, err } value.Set(slice) return true, nil case reflect.Array: return setArrayOfMultipartFormFiles(value, field, files) } return false, ErrMultiFileHeader } func setArrayOfMultipartFormFiles(value reflect.Value, field reflect.StructField, files []*multipart.FileHeader) (isSet bool, err error) { if value.Len() != len(files) { return false, ErrMultiFileHeaderLenInvalid } for i := range files { set, err := setByMultipartFormFile(value.Index(i), field, files[i:i+1]) if err != nil || !set { return set, err } } return true, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/binding/query.go
vendor/github.com/gin-gonic/gin/binding/query.go
// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import "net/http" type queryBinding struct{} func (queryBinding) Name() string { return "query" } func (queryBinding) Bind(req *http.Request, obj any) error { values := req.URL.Query() if err := mapForm(obj, values); err != nil { return err } return validate(obj) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/binding/toml.go
vendor/github.com/gin-gonic/gin/binding/toml.go
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "bytes" "io" "net/http" "github.com/pelletier/go-toml/v2" ) type tomlBinding struct{} func (tomlBinding) Name() string { return "toml" } func (tomlBinding) Bind(req *http.Request, obj any) error { return decodeToml(req.Body, obj) } func (tomlBinding) BindBody(body []byte, obj any) error { return decodeToml(bytes.NewReader(body), obj) } func decodeToml(r io.Reader, obj any) error { decoder := toml.NewDecoder(r) if err := decoder.Decode(obj); err != nil { return err } return decoder.Decode(obj) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-gonic/gin/binding/form_mapping.go
vendor/github.com/gin-gonic/gin/binding/form_mapping.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "errors" "fmt" "mime/multipart" "reflect" "strconv" "strings" "time" "github.com/gin-gonic/gin/internal/bytesconv" "github.com/gin-gonic/gin/internal/json" ) var ( errUnknownType = errors.New("unknown type") // ErrConvertMapStringSlice can not convert to map[string][]string ErrConvertMapStringSlice = errors.New("can not convert to map slices of strings") // ErrConvertToMapString can not convert to map[string]string ErrConvertToMapString = errors.New("can not convert to map of strings") ) func mapURI(ptr any, m map[string][]string) error { return mapFormByTag(ptr, m, "uri") } func mapForm(ptr any, form map[string][]string) error { return mapFormByTag(ptr, form, "form") } func MapFormWithTag(ptr any, form map[string][]string, tag string) error { return mapFormByTag(ptr, form, tag) } var emptyField = reflect.StructField{} func mapFormByTag(ptr any, form map[string][]string, tag string) error { // Check if ptr is a map ptrVal := reflect.ValueOf(ptr) var pointed any if ptrVal.Kind() == reflect.Ptr { ptrVal = ptrVal.Elem() pointed = ptrVal.Interface() } if ptrVal.Kind() == reflect.Map && ptrVal.Type().Key().Kind() == reflect.String { if pointed != nil { ptr = pointed } return setFormMap(ptr, form) } return mappingByPtr(ptr, formSource(form), tag) } // setter tries to set value on a walking by fields of a struct type setter interface { TrySet(value reflect.Value, field reflect.StructField, key string, opt setOptions) (isSet bool, err error) } type formSource map[string][]string var _ setter = formSource(nil) // TrySet tries to set a value by request's form source (like map[string][]string) func (form formSource) TrySet(value reflect.Value, field reflect.StructField, tagValue string, opt setOptions) (isSet bool, err error) { return setByForm(value, field, form, tagValue, opt) } func mappingByPtr(ptr any, setter setter, tag string) error { _, err := mapping(reflect.ValueOf(ptr), emptyField, setter, tag) return err } func mapping(value reflect.Value, field reflect.StructField, setter setter, tag string) (bool, error) { if field.Tag.Get(tag) == "-" { // just ignoring this field return false, nil } vKind := value.Kind() if vKind == reflect.Ptr { var isNew bool vPtr := value if value.IsNil() { isNew = true vPtr = reflect.New(value.Type().Elem()) } isSet, err := mapping(vPtr.Elem(), field, setter, tag) if err != nil { return false, err } if isNew && isSet { value.Set(vPtr) } return isSet, nil } if vKind != reflect.Struct || !field.Anonymous { ok, err := tryToSetValue(value, field, setter, tag) if err != nil { return false, err } if ok { return true, nil } } if vKind == reflect.Struct { tValue := value.Type() var isSet bool for i := 0; i < value.NumField(); i++ { sf := tValue.Field(i) if sf.PkgPath != "" && !sf.Anonymous { // unexported continue } ok, err := mapping(value.Field(i), sf, setter, tag) if err != nil { return false, err } isSet = isSet || ok } return isSet, nil } return false, nil } type setOptions struct { isDefaultExists bool defaultValue string } func tryToSetValue(value reflect.Value, field reflect.StructField, setter setter, tag string) (bool, error) { var tagValue string var setOpt setOptions tagValue = field.Tag.Get(tag) tagValue, opts := head(tagValue, ",") if tagValue == "" { // default value is FieldName tagValue = field.Name } if tagValue == "" { // when field is "emptyField" variable return false, nil } var opt string for len(opts) > 0 { opt, opts = head(opts, ",") if k, v := head(opt, "="); k == "default" { setOpt.isDefaultExists = true setOpt.defaultValue = v } } return setter.TrySet(value, field, tagValue, setOpt) } // BindUnmarshaler is the interface used to wrap the UnmarshalParam method. type BindUnmarshaler interface { // UnmarshalParam decodes and assigns a value from an form or query param. UnmarshalParam(param string) error } // trySetCustom tries to set a custom type value // If the value implements the BindUnmarshaler interface, it will be used to set the value, we will return `true` // to skip the default value setting. func trySetCustom(val string, value reflect.Value) (isSet bool, err error) { switch v := value.Addr().Interface().(type) { case BindUnmarshaler: return true, v.UnmarshalParam(val) } return false, nil } func setByForm(value reflect.Value, field reflect.StructField, form map[string][]string, tagValue string, opt setOptions) (isSet bool, err error) { vs, ok := form[tagValue] if !ok && !opt.isDefaultExists { return false, nil } switch value.Kind() { case reflect.Slice: if !ok { vs = []string{opt.defaultValue} } return true, setSlice(vs, value, field) case reflect.Array: if !ok { vs = []string{opt.defaultValue} } if len(vs) != value.Len() { return false, fmt.Errorf("%q is not valid value for %s", vs, value.Type().String()) } return true, setArray(vs, value, field) default: var val string if !ok { val = opt.defaultValue } if len(vs) > 0 { val = vs[0] } if ok, err := trySetCustom(val, value); ok { return ok, err } return true, setWithProperType(val, value, field) } } func setWithProperType(val string, value reflect.Value, field reflect.StructField) error { switch value.Kind() { case reflect.Int: return setIntField(val, 0, value) case reflect.Int8: return setIntField(val, 8, value) case reflect.Int16: return setIntField(val, 16, value) case reflect.Int32: return setIntField(val, 32, value) case reflect.Int64: switch value.Interface().(type) { case time.Duration: return setTimeDuration(val, value) } return setIntField(val, 64, value) case reflect.Uint: return setUintField(val, 0, value) case reflect.Uint8: return setUintField(val, 8, value) case reflect.Uint16: return setUintField(val, 16, value) case reflect.Uint32: return setUintField(val, 32, value) case reflect.Uint64: return setUintField(val, 64, value) case reflect.Bool: return setBoolField(val, value) case reflect.Float32: return setFloatField(val, 32, value) case reflect.Float64: return setFloatField(val, 64, value) case reflect.String: value.SetString(val) case reflect.Struct: switch value.Interface().(type) { case time.Time: return setTimeField(val, field, value) case multipart.FileHeader: return nil } return json.Unmarshal(bytesconv.StringToBytes(val), value.Addr().Interface()) case reflect.Map: return json.Unmarshal(bytesconv.StringToBytes(val), value.Addr().Interface()) case reflect.Ptr: if !value.Elem().IsValid() { value.Set(reflect.New(value.Type().Elem())) } return setWithProperType(val, value.Elem(), field) default: return errUnknownType } return nil } func setIntField(val string, bitSize int, field reflect.Value) error { if val == "" { val = "0" } intVal, err := strconv.ParseInt(val, 10, bitSize) if err == nil { field.SetInt(intVal) } return err } func setUintField(val string, bitSize int, field reflect.Value) error { if val == "" { val = "0" } uintVal, err := strconv.ParseUint(val, 10, bitSize) if err == nil { field.SetUint(uintVal) } return err } func setBoolField(val string, field reflect.Value) error { if val == "" { val = "false" } boolVal, err := strconv.ParseBool(val) if err == nil { field.SetBool(boolVal) } return err } func setFloatField(val string, bitSize int, field reflect.Value) error { if val == "" { val = "0.0" } floatVal, err := strconv.ParseFloat(val, bitSize) if err == nil { field.SetFloat(floatVal) } return err } func setTimeField(val string, structField reflect.StructField, value reflect.Value) error { timeFormat := structField.Tag.Get("time_format") if timeFormat == "" { timeFormat = time.RFC3339 } switch tf := strings.ToLower(timeFormat); tf { case "unix", "unixnano": tv, err := strconv.ParseInt(val, 10, 64) if err != nil { return err } d := time.Duration(1) if tf == "unixnano" { d = time.Second } t := time.Unix(tv/int64(d), tv%int64(d)) value.Set(reflect.ValueOf(t)) return nil } if val == "" { value.Set(reflect.ValueOf(time.Time{})) return nil } l := time.Local if isUTC, _ := strconv.ParseBool(structField.Tag.Get("time_utc")); isUTC { l = time.UTC } if locTag := structField.Tag.Get("time_location"); locTag != "" { loc, err := time.LoadLocation(locTag) if err != nil { return err } l = loc } t, err := time.ParseInLocation(timeFormat, val, l) if err != nil { return err } value.Set(reflect.ValueOf(t)) return nil } func setArray(vals []string, value reflect.Value, field reflect.StructField) error { for i, s := range vals { err := setWithProperType(s, value.Index(i), field) if err != nil { return err } } return nil } func setSlice(vals []string, value reflect.Value, field reflect.StructField) error { slice := reflect.MakeSlice(value.Type(), len(vals), len(vals)) err := setArray(vals, slice, field) if err != nil { return err } value.Set(slice) return nil } func setTimeDuration(val string, value reflect.Value) error { d, err := time.ParseDuration(val) if err != nil { return err } value.Set(reflect.ValueOf(d)) return nil } func head(str, sep string) (head string, tail string) { idx := strings.Index(str, sep) if idx < 0 { return str, "" } return str[:idx], str[idx+len(sep):] } func setFormMap(ptr any, form map[string][]string) error { el := reflect.TypeOf(ptr).Elem() if el.Kind() == reflect.Slice { ptrMap, ok := ptr.(map[string][]string) if !ok { return ErrConvertMapStringSlice } for k, v := range form { ptrMap[k] = v } return nil } ptrMap, ok := ptr.(map[string]string) if !ok { return ErrConvertToMapString } for k, v := range form { ptrMap[k] = v[len(v)-1] // pick last } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/huandu/xstrings/manipulate.go
vendor/github.com/huandu/xstrings/manipulate.go
// Copyright 2015 Huan Du. All rights reserved. // Licensed under the MIT license that can be found in the LICENSE file. package xstrings import ( "strings" "unicode/utf8" ) // Reverse a utf8 encoded string. func Reverse(str string) string { var size int tail := len(str) buf := make([]byte, tail) s := buf for len(str) > 0 { _, size = utf8.DecodeRuneInString(str) tail -= size s = append(s[:tail], []byte(str[:size])...) str = str[size:] } return string(buf) } // Slice a string by rune. // // Start must satisfy 0 <= start <= rune length. // // End can be positive, zero or negative. // If end >= 0, start and end must satisfy start <= end <= rune length. // If end < 0, it means slice to the end of string. // // Otherwise, Slice will panic as out of range. func Slice(str string, start, end int) string { var size, startPos, endPos int origin := str if start < 0 || end > len(str) || (end >= 0 && start > end) { panic("out of range") } if end >= 0 { end -= start } for start > 0 && len(str) > 0 { _, size = utf8.DecodeRuneInString(str) start-- startPos += size str = str[size:] } if end < 0 { return origin[startPos:] } endPos = startPos for end > 0 && len(str) > 0 { _, size = utf8.DecodeRuneInString(str) end-- endPos += size str = str[size:] } if len(str) == 0 && (start > 0 || end > 0) { panic("out of range") } return origin[startPos:endPos] } // Partition splits a string by sep into three parts. // The return value is a slice of strings with head, match and tail. // // If str contains sep, for example "hello" and "l", Partition returns // // "he", "l", "lo" // // If str doesn't contain sep, for example "hello" and "x", Partition returns // // "hello", "", "" func Partition(str, sep string) (head, match, tail string) { index := strings.Index(str, sep) if index == -1 { head = str return } head = str[:index] match = str[index : index+len(sep)] tail = str[index+len(sep):] return } // LastPartition splits a string by last instance of sep into three parts. // The return value is a slice of strings with head, match and tail. // // If str contains sep, for example "hello" and "l", LastPartition returns // // "hel", "l", "o" // // If str doesn't contain sep, for example "hello" and "x", LastPartition returns // // "", "", "hello" func LastPartition(str, sep string) (head, match, tail string) { index := strings.LastIndex(str, sep) if index == -1 { tail = str return } head = str[:index] match = str[index : index+len(sep)] tail = str[index+len(sep):] return } // Insert src into dst at given rune index. // Index is counted by runes instead of bytes. // // If index is out of range of dst, panic with out of range. func Insert(dst, src string, index int) string { return Slice(dst, 0, index) + src + Slice(dst, index, -1) } // Scrub scrubs invalid utf8 bytes with repl string. // Adjacent invalid bytes are replaced only once. func Scrub(str, repl string) string { var buf *stringBuilder var r rune var size, pos int var hasError bool origin := str for len(str) > 0 { r, size = utf8.DecodeRuneInString(str) if r == utf8.RuneError { if !hasError { if buf == nil { buf = &stringBuilder{} } buf.WriteString(origin[:pos]) hasError = true } } else if hasError { hasError = false buf.WriteString(repl) origin = origin[pos:] pos = 0 } pos += size str = str[size:] } if buf != nil { buf.WriteString(origin) return buf.String() } // No invalid byte. return origin } // WordSplit splits a string into words. Returns a slice of words. // If there is no word in a string, return nil. // // Word is defined as a locale dependent string containing alphabetic characters, // which may also contain but not start with `'` and `-` characters. func WordSplit(str string) []string { var word string var words []string var r rune var size, pos int inWord := false for len(str) > 0 { r, size = utf8.DecodeRuneInString(str) switch { case isAlphabet(r): if !inWord { inWord = true word = str pos = 0 } case inWord && (r == '\'' || r == '-'): // Still in word. default: if inWord { inWord = false words = append(words, word[:pos]) } } pos += size str = str[size:] } if inWord { words = append(words, word[:pos]) } return words }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/huandu/xstrings/convert.go
vendor/github.com/huandu/xstrings/convert.go
// Copyright 2015 Huan Du. All rights reserved. // Licensed under the MIT license that can be found in the LICENSE file. package xstrings import ( "math/rand" "unicode" "unicode/utf8" ) // ToCamelCase is to convert words separated by space, underscore and hyphen to camel case. // // Some samples. // // "some_words" => "someWords" // "http_server" => "httpServer" // "no_https" => "noHttps" // "_complex__case_" => "_complex_Case_" // "some words" => "someWords" // "GOLANG_IS_GREAT" => "golangIsGreat" func ToCamelCase(str string) string { return toCamelCase(str, false) } // ToPascalCase is to convert words separated by space, underscore and hyphen to pascal case. // // Some samples. // // "some_words" => "SomeWords" // "http_server" => "HttpServer" // "no_https" => "NoHttps" // "_complex__case_" => "_Complex_Case_" // "some words" => "SomeWords" // "GOLANG_IS_GREAT" => "GolangIsGreat" func ToPascalCase(str string) string { return toCamelCase(str, true) } func toCamelCase(str string, isBig bool) string { if len(str) == 0 { return "" } buf := &stringBuilder{} var isFirstRuneUpper bool var r0, r1 rune var size int // leading connector will appear in output. for len(str) > 0 { r0, size = utf8.DecodeRuneInString(str) str = str[size:] if !isConnector(r0) { isFirstRuneUpper = unicode.IsUpper(r0) if isBig { r0 = unicode.ToUpper(r0) } else { r0 = unicode.ToLower(r0) } break } buf.WriteRune(r0) } if len(str) == 0 { // A special case for a string contains only 1 rune. if size != 0 { buf.WriteRune(r0) } return buf.String() } for len(str) > 0 { r1 = r0 r0, size = utf8.DecodeRuneInString(str) str = str[size:] if isConnector(r0) && isConnector(r1) { buf.WriteRune(r1) continue } if isConnector(r1) { isFirstRuneUpper = unicode.IsUpper(r0) r0 = unicode.ToUpper(r0) } else { if isFirstRuneUpper { if unicode.IsUpper(r0) { r0 = unicode.ToLower(r0) } else { isFirstRuneUpper = false } } buf.WriteRune(r1) } } if isFirstRuneUpper && !isBig { r0 = unicode.ToLower(r0) } buf.WriteRune(r0) return buf.String() } // ToSnakeCase can convert all upper case characters in a string to // snake case format. // // Some samples. // // "FirstName" => "first_name" // "HTTPServer" => "http_server" // "NoHTTPS" => "no_https" // "GO_PATH" => "go_path" // "GO PATH" => "go_path" // space is converted to underscore. // "GO-PATH" => "go_path" // hyphen is converted to underscore. // "http2xx" => "http_2xx" // insert an underscore before a number and after an alphabet. // "HTTP20xOK" => "http_20x_ok" // "Duration2m3s" => "duration_2m3s" // "Bld4Floor3rd" => "bld4_floor_3rd" func ToSnakeCase(str string) string { return camelCaseToLowerCase(str, '_') } // ToKebabCase can convert all upper case characters in a string to // kebab case format. // // Some samples. // // "FirstName" => "first-name" // "HTTPServer" => "http-server" // "NoHTTPS" => "no-https" // "GO_PATH" => "go-path" // "GO PATH" => "go-path" // space is converted to '-'. // "GO-PATH" => "go-path" // hyphen is converted to '-'. // "http2xx" => "http-2xx" // insert an underscore before a number and after an alphabet. // "HTTP20xOK" => "http-20x-ok" // "Duration2m3s" => "duration-2m3s" // "Bld4Floor3rd" => "bld4-floor-3rd" func ToKebabCase(str string) string { return camelCaseToLowerCase(str, '-') } func camelCaseToLowerCase(str string, connector rune) string { if len(str) == 0 { return "" } buf := &stringBuilder{} wt, word, remaining := nextWord(str) for len(remaining) > 0 { if wt != connectorWord { toLower(buf, wt, word, connector) } prev := wt last := word wt, word, remaining = nextWord(remaining) switch prev { case numberWord: for wt == alphabetWord || wt == numberWord { toLower(buf, wt, word, connector) wt, word, remaining = nextWord(remaining) } if wt != invalidWord && wt != punctWord && wt != connectorWord { buf.WriteRune(connector) } case connectorWord: toLower(buf, prev, last, connector) case punctWord: // nothing. default: if wt != numberWord { if wt != connectorWord && wt != punctWord { buf.WriteRune(connector) } break } if len(remaining) == 0 { break } last := word wt, word, remaining = nextWord(remaining) // consider number as a part of previous word. // e.g. "Bld4Floor" => "bld4_floor" if wt != alphabetWord { toLower(buf, numberWord, last, connector) if wt != connectorWord && wt != punctWord { buf.WriteRune(connector) } break } // if there are some lower case letters following a number, // add connector before the number. // e.g. "HTTP2xx" => "http_2xx" buf.WriteRune(connector) toLower(buf, numberWord, last, connector) for wt == alphabetWord || wt == numberWord { toLower(buf, wt, word, connector) wt, word, remaining = nextWord(remaining) } if wt != invalidWord && wt != connectorWord && wt != punctWord { buf.WriteRune(connector) } } } toLower(buf, wt, word, connector) return buf.String() } func isConnector(r rune) bool { return r == '-' || r == '_' || unicode.IsSpace(r) } type wordType int const ( invalidWord wordType = iota numberWord upperCaseWord alphabetWord connectorWord punctWord otherWord ) func nextWord(str string) (wt wordType, word, remaining string) { if len(str) == 0 { return } var offset int remaining = str r, size := nextValidRune(remaining, utf8.RuneError) offset += size if r == utf8.RuneError { wt = invalidWord word = str[:offset] remaining = str[offset:] return } switch { case isConnector(r): wt = connectorWord remaining = remaining[size:] for len(remaining) > 0 { r, size = nextValidRune(remaining, r) if !isConnector(r) { break } offset += size remaining = remaining[size:] } case unicode.IsPunct(r): wt = punctWord remaining = remaining[size:] for len(remaining) > 0 { r, size = nextValidRune(remaining, r) if !unicode.IsPunct(r) { break } offset += size remaining = remaining[size:] } case unicode.IsUpper(r): wt = upperCaseWord remaining = remaining[size:] if len(remaining) == 0 { break } r, size = nextValidRune(remaining, r) switch { case unicode.IsUpper(r): prevSize := size offset += size remaining = remaining[size:] for len(remaining) > 0 { r, size = nextValidRune(remaining, r) if !unicode.IsUpper(r) { break } prevSize = size offset += size remaining = remaining[size:] } // it's a bit complex when dealing with a case like "HTTPStatus". // it's expected to be splitted into "HTTP" and "Status". // Therefore "S" should be in remaining instead of word. if len(remaining) > 0 && isAlphabet(r) { offset -= prevSize remaining = str[offset:] } case isAlphabet(r): offset += size remaining = remaining[size:] for len(remaining) > 0 { r, size = nextValidRune(remaining, r) if !isAlphabet(r) || unicode.IsUpper(r) { break } offset += size remaining = remaining[size:] } } case isAlphabet(r): wt = alphabetWord remaining = remaining[size:] for len(remaining) > 0 { r, size = nextValidRune(remaining, r) if !isAlphabet(r) || unicode.IsUpper(r) { break } offset += size remaining = remaining[size:] } case unicode.IsNumber(r): wt = numberWord remaining = remaining[size:] for len(remaining) > 0 { r, size = nextValidRune(remaining, r) if !unicode.IsNumber(r) { break } offset += size remaining = remaining[size:] } default: wt = otherWord remaining = remaining[size:] for len(remaining) > 0 { r, size = nextValidRune(remaining, r) if size == 0 || isConnector(r) || isAlphabet(r) || unicode.IsNumber(r) || unicode.IsPunct(r) { break } offset += size remaining = remaining[size:] } } word = str[:offset] return } func nextValidRune(str string, prev rune) (r rune, size int) { var sz int for len(str) > 0 { r, sz = utf8.DecodeRuneInString(str) size += sz if r != utf8.RuneError { return } str = str[sz:] } r = prev return } func toLower(buf *stringBuilder, wt wordType, str string, connector rune) { buf.Grow(buf.Len() + len(str)) if wt != upperCaseWord && wt != connectorWord { buf.WriteString(str) return } for len(str) > 0 { r, size := utf8.DecodeRuneInString(str) str = str[size:] if isConnector(r) { buf.WriteRune(connector) } else if unicode.IsUpper(r) { buf.WriteRune(unicode.ToLower(r)) } else { buf.WriteRune(r) } } } // SwapCase will swap characters case from upper to lower or lower to upper. func SwapCase(str string) string { var r rune var size int buf := &stringBuilder{} for len(str) > 0 { r, size = utf8.DecodeRuneInString(str) switch { case unicode.IsUpper(r): buf.WriteRune(unicode.ToLower(r)) case unicode.IsLower(r): buf.WriteRune(unicode.ToUpper(r)) default: buf.WriteRune(r) } str = str[size:] } return buf.String() } // FirstRuneToUpper converts first rune to upper case if necessary. func FirstRuneToUpper(str string) string { if str == "" { return str } r, size := utf8.DecodeRuneInString(str) if !unicode.IsLower(r) { return str } buf := &stringBuilder{} buf.WriteRune(unicode.ToUpper(r)) buf.WriteString(str[size:]) return buf.String() } // FirstRuneToLower converts first rune to lower case if necessary. func FirstRuneToLower(str string) string { if str == "" { return str } r, size := utf8.DecodeRuneInString(str) if !unicode.IsUpper(r) { return str } buf := &stringBuilder{} buf.WriteRune(unicode.ToLower(r)) buf.WriteString(str[size:]) return buf.String() } // Shuffle randomizes runes in a string and returns the result. // It uses default random source in `math/rand`. func Shuffle(str string) string { if str == "" { return str } runes := []rune(str) index := 0 for i := len(runes) - 1; i > 0; i-- { index = rand.Intn(i + 1) if i != index { runes[i], runes[index] = runes[index], runes[i] } } return string(runes) } // ShuffleSource randomizes runes in a string with given random source. func ShuffleSource(str string, src rand.Source) string { if str == "" { return str } runes := []rune(str) index := 0 r := rand.New(src) for i := len(runes) - 1; i > 0; i-- { index = r.Intn(i + 1) if i != index { runes[i], runes[index] = runes[index], runes[i] } } return string(runes) } // Successor returns the successor to string. // // If there is one alphanumeric rune is found in string, increase the rune by 1. // If increment generates a "carry", the rune to the left of it is incremented. // This process repeats until there is no carry, adding an additional rune if necessary. // // If there is no alphanumeric rune, the rightmost rune will be increased by 1 // regardless whether the result is a valid rune or not. // // Only following characters are alphanumeric. // - a - z // - A - Z // - 0 - 9 // // Samples (borrowed from ruby's String#succ document): // // "abcd" => "abce" // "THX1138" => "THX1139" // "<<koala>>" => "<<koalb>>" // "1999zzz" => "2000aaa" // "ZZZ9999" => "AAAA0000" // "***" => "**+" func Successor(str string) string { if str == "" { return str } var r rune var i int carry := ' ' runes := []rune(str) l := len(runes) lastAlphanumeric := l for i = l - 1; i >= 0; i-- { r = runes[i] if ('a' <= r && r <= 'y') || ('A' <= r && r <= 'Y') || ('0' <= r && r <= '8') { runes[i]++ carry = ' ' lastAlphanumeric = i break } switch r { case 'z': runes[i] = 'a' carry = 'a' lastAlphanumeric = i case 'Z': runes[i] = 'A' carry = 'A' lastAlphanumeric = i case '9': runes[i] = '0' carry = '0' lastAlphanumeric = i } } // Needs to add one character for carry. if i < 0 && carry != ' ' { buf := &stringBuilder{} buf.Grow(l + 4) // Reserve enough space for write. if lastAlphanumeric != 0 { buf.WriteString(str[:lastAlphanumeric]) } buf.WriteRune(carry) for _, r = range runes[lastAlphanumeric:] { buf.WriteRune(r) } return buf.String() } // No alphanumeric character. Simply increase last rune's value. if lastAlphanumeric == l { runes[l-1]++ } return string(runes) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/huandu/xstrings/format.go
vendor/github.com/huandu/xstrings/format.go
// Copyright 2015 Huan Du. All rights reserved. // Licensed under the MIT license that can be found in the LICENSE file. package xstrings import ( "unicode/utf8" ) // ExpandTabs can expand tabs ('\t') rune in str to one or more spaces dpending on // current column and tabSize. // The column number is reset to zero after each newline ('\n') occurring in the str. // // ExpandTabs uses RuneWidth to decide rune's width. // For example, CJK characters will be treated as two characters. // // If tabSize <= 0, ExpandTabs panics with error. // // Samples: // // ExpandTabs("a\tbc\tdef\tghij\tk", 4) => "a bc def ghij k" // ExpandTabs("abcdefg\thij\nk\tl", 4) => "abcdefg hij\nk l" // ExpandTabs("z中\t文\tw", 4) => "z中 文 w" func ExpandTabs(str string, tabSize int) string { if tabSize <= 0 { panic("tab size must be positive") } var r rune var i, size, column, expand int var output *stringBuilder orig := str for len(str) > 0 { r, size = utf8.DecodeRuneInString(str) if r == '\t' { expand = tabSize - column%tabSize if output == nil { output = allocBuffer(orig, str) } for i = 0; i < expand; i++ { output.WriteRune(' ') } column += expand } else { if r == '\n' { column = 0 } else { column += RuneWidth(r) } if output != nil { output.WriteRune(r) } } str = str[size:] } if output == nil { return orig } return output.String() } // LeftJustify returns a string with pad string at right side if str's rune length is smaller than length. // If str's rune length is larger than length, str itself will be returned. // // If pad is an empty string, str will be returned. // // Samples: // // LeftJustify("hello", 4, " ") => "hello" // LeftJustify("hello", 10, " ") => "hello " // LeftJustify("hello", 10, "123") => "hello12312" func LeftJustify(str string, length int, pad string) string { l := Len(str) if l >= length || pad == "" { return str } remains := length - l padLen := Len(pad) output := &stringBuilder{} output.Grow(len(str) + (remains/padLen+1)*len(pad)) output.WriteString(str) writePadString(output, pad, padLen, remains) return output.String() } // RightJustify returns a string with pad string at left side if str's rune length is smaller than length. // If str's rune length is larger than length, str itself will be returned. // // If pad is an empty string, str will be returned. // // Samples: // // RightJustify("hello", 4, " ") => "hello" // RightJustify("hello", 10, " ") => " hello" // RightJustify("hello", 10, "123") => "12312hello" func RightJustify(str string, length int, pad string) string { l := Len(str) if l >= length || pad == "" { return str } remains := length - l padLen := Len(pad) output := &stringBuilder{} output.Grow(len(str) + (remains/padLen+1)*len(pad)) writePadString(output, pad, padLen, remains) output.WriteString(str) return output.String() } // Center returns a string with pad string at both side if str's rune length is smaller than length. // If str's rune length is larger than length, str itself will be returned. // // If pad is an empty string, str will be returned. // // Samples: // // Center("hello", 4, " ") => "hello" // Center("hello", 10, " ") => " hello " // Center("hello", 10, "123") => "12hello123" func Center(str string, length int, pad string) string { l := Len(str) if l >= length || pad == "" { return str } remains := length - l padLen := Len(pad) output := &stringBuilder{} output.Grow(len(str) + (remains/padLen+1)*len(pad)) writePadString(output, pad, padLen, remains/2) output.WriteString(str) writePadString(output, pad, padLen, (remains+1)/2) return output.String() } func writePadString(output *stringBuilder, pad string, padLen, remains int) { var r rune var size int repeats := remains / padLen for i := 0; i < repeats; i++ { output.WriteString(pad) } remains = remains % padLen if remains != 0 { for i := 0; i < remains; i++ { r, size = utf8.DecodeRuneInString(pad) output.WriteRune(r) pad = pad[size:] } } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/huandu/xstrings/translate.go
vendor/github.com/huandu/xstrings/translate.go
// Copyright 2015 Huan Du. All rights reserved. // Licensed under the MIT license that can be found in the LICENSE file. package xstrings import ( "unicode" "unicode/utf8" ) type runeRangeMap struct { FromLo rune // Lower bound of range map. FromHi rune // An inclusive higher bound of range map. ToLo rune ToHi rune } type runeDict struct { Dict [unicode.MaxASCII + 1]rune } type runeMap map[rune]rune // Translator can translate string with pre-compiled from and to patterns. // If a from/to pattern pair needs to be used more than once, it's recommended // to create a Translator and reuse it. type Translator struct { quickDict *runeDict // A quick dictionary to look up rune by index. Only available for latin runes. runeMap runeMap // Rune map for translation. ranges []*runeRangeMap // Ranges of runes. mappedRune rune // If mappedRune >= 0, all matched runes are translated to the mappedRune. reverted bool // If to pattern is empty, all matched characters will be deleted. hasPattern bool } // NewTranslator creates new Translator through a from/to pattern pair. func NewTranslator(from, to string) *Translator { tr := &Translator{} if from == "" { return tr } reverted := from[0] == '^' deletion := len(to) == 0 if reverted { from = from[1:] } var fromStart, fromEnd, fromRangeStep rune var toStart, toEnd, toRangeStep rune var fromRangeSize, toRangeSize rune var singleRunes []rune // Update the to rune range. updateRange := func() { // No more rune to read in the to rune pattern. if toEnd == utf8.RuneError { return } if toRangeStep == 0 { to, toStart, toEnd, toRangeStep = nextRuneRange(to, toEnd) return } // Current range is not empty. Consume 1 rune from start. if toStart != toEnd { toStart += toRangeStep return } // No more rune. Repeat the last rune. if to == "" { toEnd = utf8.RuneError return } // Both start and end are used. Read two more runes from the to pattern. to, toStart, toEnd, toRangeStep = nextRuneRange(to, utf8.RuneError) } if deletion { toStart = utf8.RuneError toEnd = utf8.RuneError } else { // If from pattern is reverted, only the last rune in the to pattern will be used. if reverted { var size int for len(to) > 0 { toStart, size = utf8.DecodeRuneInString(to) to = to[size:] } toEnd = utf8.RuneError } else { to, toStart, toEnd, toRangeStep = nextRuneRange(to, utf8.RuneError) } } fromEnd = utf8.RuneError for len(from) > 0 { from, fromStart, fromEnd, fromRangeStep = nextRuneRange(from, fromEnd) // fromStart is a single character. Just map it with a rune in the to pattern. if fromRangeStep == 0 { singleRunes = tr.addRune(fromStart, toStart, singleRunes) updateRange() continue } for toEnd != utf8.RuneError && fromStart != fromEnd { // If mapped rune is a single character instead of a range, simply shift first // rune in the range. if toRangeStep == 0 { singleRunes = tr.addRune(fromStart, toStart, singleRunes) updateRange() fromStart += fromRangeStep continue } fromRangeSize = (fromEnd - fromStart) * fromRangeStep toRangeSize = (toEnd - toStart) * toRangeStep // Not enough runes in the to pattern. Need to read more. if fromRangeSize > toRangeSize { fromStart, toStart = tr.addRuneRange(fromStart, fromStart+toRangeSize*fromRangeStep, toStart, toEnd, singleRunes) fromStart += fromRangeStep updateRange() // Edge case: If fromRangeSize == toRangeSize + 1, the last fromStart value needs be considered // as a single rune. if fromStart == fromEnd { singleRunes = tr.addRune(fromStart, toStart, singleRunes) updateRange() } continue } fromStart, toStart = tr.addRuneRange(fromStart, fromEnd, toStart, toStart+fromRangeSize*toRangeStep, singleRunes) updateRange() break } if fromStart == fromEnd { fromEnd = utf8.RuneError continue } _, toStart = tr.addRuneRange(fromStart, fromEnd, toStart, toStart, singleRunes) fromEnd = utf8.RuneError } if fromEnd != utf8.RuneError { tr.addRune(fromEnd, toStart, singleRunes) } tr.reverted = reverted tr.mappedRune = -1 tr.hasPattern = true // Translate RuneError only if in deletion or reverted mode. if deletion || reverted { tr.mappedRune = toStart } return tr } func (tr *Translator) addRune(from, to rune, singleRunes []rune) []rune { if from <= unicode.MaxASCII { if tr.quickDict == nil { tr.quickDict = &runeDict{} } tr.quickDict.Dict[from] = to } else { if tr.runeMap == nil { tr.runeMap = make(runeMap) } tr.runeMap[from] = to } singleRunes = append(singleRunes, from) return singleRunes } func (tr *Translator) addRuneRange(fromLo, fromHi, toLo, toHi rune, singleRunes []rune) (rune, rune) { var r rune var rrm *runeRangeMap if fromLo < fromHi { rrm = &runeRangeMap{ FromLo: fromLo, FromHi: fromHi, ToLo: toLo, ToHi: toHi, } } else { rrm = &runeRangeMap{ FromLo: fromHi, FromHi: fromLo, ToLo: toHi, ToHi: toLo, } } // If there is any single rune conflicts with this rune range, clear single rune record. for _, r = range singleRunes { if rrm.FromLo <= r && r <= rrm.FromHi { if r <= unicode.MaxASCII { tr.quickDict.Dict[r] = 0 } else { delete(tr.runeMap, r) } } } tr.ranges = append(tr.ranges, rrm) return fromHi, toHi } func nextRuneRange(str string, last rune) (remaining string, start, end rune, rangeStep rune) { var r rune var size int remaining = str escaping := false isRange := false for len(remaining) > 0 { r, size = utf8.DecodeRuneInString(remaining) remaining = remaining[size:] // Parse special characters. if !escaping { if r == '\\' { escaping = true continue } if r == '-' { // Ignore slash at beginning of string. if last == utf8.RuneError { continue } start = last isRange = true continue } } escaping = false if last != utf8.RuneError { // This is a range which start and end are the same. // Considier it as a normal character. if isRange && last == r { isRange = false continue } start = last end = r if isRange { if start < end { rangeStep = 1 } else { rangeStep = -1 } } return } last = r } start = last end = utf8.RuneError return } // Translate str with a from/to pattern pair. // // See comment in Translate function for usage and samples. func (tr *Translator) Translate(str string) string { if !tr.hasPattern || str == "" { return str } var r rune var size int var needTr bool orig := str var output *stringBuilder for len(str) > 0 { r, size = utf8.DecodeRuneInString(str) r, needTr = tr.TranslateRune(r) if needTr && output == nil { output = allocBuffer(orig, str) } if r != utf8.RuneError && output != nil { output.WriteRune(r) } str = str[size:] } // No character is translated. if output == nil { return orig } return output.String() } // TranslateRune return translated rune and true if r matches the from pattern. // If r doesn't match the pattern, original r is returned and translated is false. func (tr *Translator) TranslateRune(r rune) (result rune, translated bool) { switch { case tr.quickDict != nil: if r <= unicode.MaxASCII { result = tr.quickDict.Dict[r] if result != 0 { translated = true if tr.mappedRune >= 0 { result = tr.mappedRune } break } } fallthrough case tr.runeMap != nil: var ok bool if result, ok = tr.runeMap[r]; ok { translated = true if tr.mappedRune >= 0 { result = tr.mappedRune } break } fallthrough default: var rrm *runeRangeMap ranges := tr.ranges for i := len(ranges) - 1; i >= 0; i-- { rrm = ranges[i] if rrm.FromLo <= r && r <= rrm.FromHi { translated = true if tr.mappedRune >= 0 { result = tr.mappedRune break } if rrm.ToLo < rrm.ToHi { result = rrm.ToLo + r - rrm.FromLo } else if rrm.ToLo > rrm.ToHi { // ToHi can be smaller than ToLo if range is from higher to lower. result = rrm.ToLo - r + rrm.FromLo } else { result = rrm.ToLo } break } } } if tr.reverted { if !translated { result = tr.mappedRune } translated = !translated } if !translated { result = r } return } // HasPattern returns true if Translator has one pattern at least. func (tr *Translator) HasPattern() bool { return tr.hasPattern } // Translate str with the characters defined in from replaced by characters defined in to. // // From and to are patterns representing a set of characters. Pattern is defined as following. // // Special characters: // // 1. '-' means a range of runes, e.g. // "a-z" means all characters from 'a' to 'z' inclusive; // "z-a" means all characters from 'z' to 'a' inclusive. // 2. '^' as first character means a set of all runes excepted listed, e.g. // "^a-z" means all characters except 'a' to 'z' inclusive. // 3. '\' escapes special characters. // // Normal character represents itself, e.g. "abc" is a set including 'a', 'b' and 'c'. // // Translate will try to find a 1:1 mapping from from to to. // If to is smaller than from, last rune in to will be used to map "out of range" characters in from. // // Note that '^' only works in the from pattern. It will be considered as a normal character in the to pattern. // // If the to pattern is an empty string, Translate works exactly the same as Delete. // // Samples: // // Translate("hello", "aeiou", "12345") => "h2ll4" // Translate("hello", "a-z", "A-Z") => "HELLO" // Translate("hello", "z-a", "a-z") => "svool" // Translate("hello", "aeiou", "*") => "h*ll*" // Translate("hello", "^l", "*") => "**ll*" // Translate("hello ^ world", `\^lo`, "*") => "he*** * w*r*d" func Translate(str, from, to string) string { tr := NewTranslator(from, to) return tr.Translate(str) } // Delete runes in str matching the pattern. // Pattern is defined in Translate function. // // Samples: // // Delete("hello", "aeiou") => "hll" // Delete("hello", "a-k") => "llo" // Delete("hello", "^a-k") => "he" func Delete(str, pattern string) string { tr := NewTranslator(pattern, "") return tr.Translate(str) } // Count how many runes in str match the pattern. // Pattern is defined in Translate function. // // Samples: // // Count("hello", "aeiou") => 3 // Count("hello", "a-k") => 3 // Count("hello", "^a-k") => 2 func Count(str, pattern string) int { if pattern == "" || str == "" { return 0 } var r rune var size int var matched bool tr := NewTranslator(pattern, "") cnt := 0 for len(str) > 0 { r, size = utf8.DecodeRuneInString(str) str = str[size:] if _, matched = tr.TranslateRune(r); matched { cnt++ } } return cnt } // Squeeze deletes adjacent repeated runes in str. // If pattern is not empty, only runes matching the pattern will be squeezed. // // Samples: // // Squeeze("hello", "") => "helo" // Squeeze("hello", "m-z") => "hello" // Squeeze("hello world", " ") => "hello world" func Squeeze(str, pattern string) string { var last, r rune var size int var skipSqueeze, matched bool var tr *Translator var output *stringBuilder orig := str last = -1 if len(pattern) > 0 { tr = NewTranslator(pattern, "") } for len(str) > 0 { r, size = utf8.DecodeRuneInString(str) // Need to squeeze the str. if last == r && !skipSqueeze { if tr != nil { if _, matched = tr.TranslateRune(r); !matched { skipSqueeze = true } } if output == nil { output = allocBuffer(orig, str) } if skipSqueeze { output.WriteRune(r) } } else { if output != nil { output.WriteRune(r) } last = r skipSqueeze = false } str = str[size:] } if output == nil { return orig } return output.String() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/huandu/xstrings/stringbuilder_go110.go
vendor/github.com/huandu/xstrings/stringbuilder_go110.go
//go:build !go1.10 // +build !go1.10 package xstrings import "bytes" type stringBuilder struct { bytes.Buffer }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/huandu/xstrings/stringbuilder.go
vendor/github.com/huandu/xstrings/stringbuilder.go
//go:build go1.10 // +build go1.10 package xstrings import "strings" type stringBuilder = strings.Builder
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/huandu/xstrings/doc.go
vendor/github.com/huandu/xstrings/doc.go
// Copyright 2015 Huan Du. All rights reserved. // Licensed under the MIT license that can be found in the LICENSE file. // Package xstrings is to provide string algorithms which are useful but not included in `strings` package. // See project home page for details. https://github.com/huandu/xstrings // // Package xstrings assumes all strings are encoded in utf8. package xstrings
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/huandu/xstrings/count.go
vendor/github.com/huandu/xstrings/count.go
// Copyright 2015 Huan Du. All rights reserved. // Licensed under the MIT license that can be found in the LICENSE file. package xstrings import ( "unicode" "unicode/utf8" ) // Len returns str's utf8 rune length. func Len(str string) int { return utf8.RuneCountInString(str) } // WordCount returns number of words in a string. // // Word is defined as a locale dependent string containing alphabetic characters, // which may also contain but not start with `'` and `-` characters. func WordCount(str string) int { var r rune var size, n int inWord := false for len(str) > 0 { r, size = utf8.DecodeRuneInString(str) switch { case isAlphabet(r): if !inWord { inWord = true n++ } case inWord && (r == '\'' || r == '-'): // Still in word. default: inWord = false } str = str[size:] } return n } const minCJKCharacter = '\u3400' // Checks r is a letter but not CJK character. func isAlphabet(r rune) bool { if !unicode.IsLetter(r) { return false } switch { // Quick check for non-CJK character. case r < minCJKCharacter: return true // Common CJK characters. case r >= '\u4E00' && r <= '\u9FCC': return false // Rare CJK characters. case r >= '\u3400' && r <= '\u4D85': return false // Rare and historic CJK characters. case r >= '\U00020000' && r <= '\U0002B81D': return false } return true } // Width returns string width in monotype font. // Multi-byte characters are usually twice the width of single byte characters. // // Algorithm comes from `mb_strwidth` in PHP. // http://php.net/manual/en/function.mb-strwidth.php func Width(str string) int { var r rune var size, n int for len(str) > 0 { r, size = utf8.DecodeRuneInString(str) n += RuneWidth(r) str = str[size:] } return n } // RuneWidth returns character width in monotype font. // Multi-byte characters are usually twice the width of single byte characters. // // Algorithm comes from `mb_strwidth` in PHP. // http://php.net/manual/en/function.mb-strwidth.php func RuneWidth(r rune) int { switch { case r == utf8.RuneError || r < '\x20': return 0 case '\x20' <= r && r < '\u2000': return 1 case '\u2000' <= r && r < '\uFF61': return 2 case '\uFF61' <= r && r < '\uFFA0': return 1 case '\uFFA0' <= r: return 2 } return 0 }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/huandu/xstrings/common.go
vendor/github.com/huandu/xstrings/common.go
// Copyright 2015 Huan Du. All rights reserved. // Licensed under the MIT license that can be found in the LICENSE file. package xstrings const bufferMaxInitGrowSize = 2048 // Lazy initialize a buffer. func allocBuffer(orig, cur string) *stringBuilder { output := &stringBuilder{} maxSize := len(orig) * 4 // Avoid to reserve too much memory at once. if maxSize > bufferMaxInitGrowSize { maxSize = bufferMaxInitGrowSize } output.Grow(maxSize) output.WriteString(orig[:len(orig)-len(cur)]) return output }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/x448/float16/float16.go
vendor/github.com/x448/float16/float16.go
// Copyright 2019 Montgomery Edwards⁴⁴⁸ and Faye Amacker // // Special thanks to Kathryn Long for her Rust implementation // of float16 at github.com/starkat99/half-rs (MIT license) package float16 import ( "math" "strconv" ) // Float16 represents IEEE 754 half-precision floating-point numbers (binary16). type Float16 uint16 // Precision indicates whether the conversion to Float16 is // exact, subnormal without dropped bits, inexact, underflow, or overflow. type Precision int const ( // PrecisionExact is for non-subnormals that don't drop bits during conversion. // All of these can round-trip. Should always convert to float16. PrecisionExact Precision = iota // PrecisionUnknown is for subnormals that don't drop bits during conversion but // not all of these can round-trip so precision is unknown without more effort. // Only 2046 of these can round-trip and the rest cannot round-trip. PrecisionUnknown // PrecisionInexact is for dropped significand bits and cannot round-trip. // Some of these are subnormals. Cannot round-trip float32->float16->float32. PrecisionInexact // PrecisionUnderflow is for Underflows. Cannot round-trip float32->float16->float32. PrecisionUnderflow // PrecisionOverflow is for Overflows. Cannot round-trip float32->float16->float32. PrecisionOverflow ) // PrecisionFromfloat32 returns Precision without performing // the conversion. Conversions from both Infinity and NaN // values will always report PrecisionExact even if NaN payload // or NaN-Quiet-Bit is lost. This function is kept simple to // allow inlining and run < 0.5 ns/op, to serve as a fast filter. func PrecisionFromfloat32(f32 float32) Precision { u32 := math.Float32bits(f32) if u32 == 0 || u32 == 0x80000000 { // +- zero will always be exact conversion return PrecisionExact } const COEFMASK uint32 = 0x7fffff // 23 least significant bits const EXPSHIFT uint32 = 23 const EXPBIAS uint32 = 127 const EXPMASK uint32 = uint32(0xff) << EXPSHIFT const DROPMASK uint32 = COEFMASK >> 10 exp := int32(((u32 & EXPMASK) >> EXPSHIFT) - EXPBIAS) coef := u32 & COEFMASK if exp == 128 { // +- infinity or NaN // apps may want to do extra checks for NaN separately return PrecisionExact } // https://en.wikipedia.org/wiki/Half-precision_floating-point_format says, // "Decimals between 2^−24 (minimum positive subnormal) and 2^−14 (maximum subnormal): fixed interval 2^−24" if exp < -24 { return PrecisionUnderflow } if exp > 15 { return PrecisionOverflow } if (coef & DROPMASK) != uint32(0) { // these include subnormals and non-subnormals that dropped bits return PrecisionInexact } if exp < -14 { // Subnormals. Caller may want to test these further. // There are 2046 subnormals that can successfully round-trip f32->f16->f32 // and 20 of those 2046 have 32-bit input coef == 0. // RFC 7049 and 7049bis Draft 12 don't precisely define "preserves value" // so some protocols and libraries will choose to handle subnormals differently // when deciding to encode them to CBOR float32 vs float16. return PrecisionUnknown } return PrecisionExact } // Frombits returns the float16 number corresponding to the IEEE 754 binary16 // representation u16, with the sign bit of u16 and the result in the same bit // position. Frombits(Bits(x)) == x. func Frombits(u16 uint16) Float16 { return Float16(u16) } // Fromfloat32 returns a Float16 value converted from f32. Conversion uses // IEEE default rounding (nearest int, with ties to even). func Fromfloat32(f32 float32) Float16 { return Float16(f32bitsToF16bits(math.Float32bits(f32))) } // ErrInvalidNaNValue indicates a NaN was not received. const ErrInvalidNaNValue = float16Error("float16: invalid NaN value, expected IEEE 754 NaN") type float16Error string func (e float16Error) Error() string { return string(e) } // FromNaN32ps converts nan to IEEE binary16 NaN while preserving both // signaling and payload. Unlike Fromfloat32(), which can only return // qNaN because it sets quiet bit = 1, this can return both sNaN and qNaN. // If the result is infinity (sNaN with empty payload), then the // lowest bit of payload is set to make the result a NaN. // Returns ErrInvalidNaNValue and 0x7c01 (sNaN) if nan isn't IEEE 754 NaN. // This function was kept simple to be able to inline. func FromNaN32ps(nan float32) (Float16, error) { const SNAN = Float16(uint16(0x7c01)) // signalling NaN u32 := math.Float32bits(nan) sign := u32 & 0x80000000 exp := u32 & 0x7f800000 coef := u32 & 0x007fffff if (exp != 0x7f800000) || (coef == 0) { return SNAN, ErrInvalidNaNValue } u16 := uint16((sign >> 16) | uint32(0x7c00) | (coef >> 13)) if (u16 & 0x03ff) == 0 { // result became infinity, make it NaN by setting lowest bit in payload u16 = u16 | 0x0001 } return Float16(u16), nil } // NaN returns a Float16 of IEEE 754 binary16 not-a-number (NaN). // Returned NaN value 0x7e01 has all exponent bits = 1 with the // first and last bits = 1 in the significand. This is consistent // with Go's 64-bit math.NaN(). Canonical CBOR in RFC 7049 uses 0x7e00. func NaN() Float16 { return Float16(0x7e01) } // Inf returns a Float16 with an infinity value with the specified sign. // A sign >= returns positive infinity. // A sign < 0 returns negative infinity. func Inf(sign int) Float16 { if sign >= 0 { return Float16(0x7c00) } return Float16(0x8000 | 0x7c00) } // Float32 returns a float32 converted from f (Float16). // This is a lossless conversion. func (f Float16) Float32() float32 { u32 := f16bitsToF32bits(uint16(f)) return math.Float32frombits(u32) } // Bits returns the IEEE 754 binary16 representation of f, with the sign bit // of f and the result in the same bit position. Bits(Frombits(x)) == x. func (f Float16) Bits() uint16 { return uint16(f) } // IsNaN reports whether f is an IEEE 754 binary16 “not-a-number” value. func (f Float16) IsNaN() bool { return (f&0x7c00 == 0x7c00) && (f&0x03ff != 0) } // IsQuietNaN reports whether f is a quiet (non-signaling) IEEE 754 binary16 // “not-a-number” value. func (f Float16) IsQuietNaN() bool { return (f&0x7c00 == 0x7c00) && (f&0x03ff != 0) && (f&0x0200 != 0) } // IsInf reports whether f is an infinity (inf). // A sign > 0 reports whether f is positive inf. // A sign < 0 reports whether f is negative inf. // A sign == 0 reports whether f is either inf. func (f Float16) IsInf(sign int) bool { return ((f == 0x7c00) && sign >= 0) || (f == 0xfc00 && sign <= 0) } // IsFinite returns true if f is neither infinite nor NaN. func (f Float16) IsFinite() bool { return (uint16(f) & uint16(0x7c00)) != uint16(0x7c00) } // IsNormal returns true if f is neither zero, infinite, subnormal, or NaN. func (f Float16) IsNormal() bool { exp := uint16(f) & uint16(0x7c00) return (exp != uint16(0x7c00)) && (exp != 0) } // Signbit reports whether f is negative or negative zero. func (f Float16) Signbit() bool { return (uint16(f) & uint16(0x8000)) != 0 } // String satisfies the fmt.Stringer interface. func (f Float16) String() string { return strconv.FormatFloat(float64(f.Float32()), 'f', -1, 32) } // f16bitsToF32bits returns uint32 (float32 bits) converted from specified uint16. func f16bitsToF32bits(in uint16) uint32 { // All 65536 conversions with this were confirmed to be correct // by Montgomery Edwards⁴⁴⁸ (github.com/x448). sign := uint32(in&0x8000) << 16 // sign for 32-bit exp := uint32(in&0x7c00) >> 10 // exponenent for 16-bit coef := uint32(in&0x03ff) << 13 // significand for 32-bit if exp == 0x1f { if coef == 0 { // infinity return sign | 0x7f800000 | coef } // NaN return sign | 0x7fc00000 | coef } if exp == 0 { if coef == 0 { // zero return sign } // normalize subnormal numbers exp++ for coef&0x7f800000 == 0 { coef <<= 1 exp-- } coef &= 0x007fffff } return sign | ((exp + (0x7f - 0xf)) << 23) | coef } // f32bitsToF16bits returns uint16 (Float16 bits) converted from the specified float32. // Conversion rounds to nearest integer with ties to even. func f32bitsToF16bits(u32 uint32) uint16 { // Translated from Rust to Go by Montgomery Edwards⁴⁴⁸ (github.com/x448). // All 4294967296 conversions with this were confirmed to be correct by x448. // Original Rust implementation is by Kathryn Long (github.com/starkat99) with MIT license. sign := u32 & 0x80000000 exp := u32 & 0x7f800000 coef := u32 & 0x007fffff if exp == 0x7f800000 { // NaN or Infinity nanBit := uint32(0) if coef != 0 { nanBit = uint32(0x0200) } return uint16((sign >> 16) | uint32(0x7c00) | nanBit | (coef >> 13)) } halfSign := sign >> 16 unbiasedExp := int32(exp>>23) - 127 halfExp := unbiasedExp + 15 if halfExp >= 0x1f { return uint16(halfSign | uint32(0x7c00)) } if halfExp <= 0 { if 14-halfExp > 24 { return uint16(halfSign) } coef := coef | uint32(0x00800000) halfCoef := coef >> uint32(14-halfExp) roundBit := uint32(1) << uint32(13-halfExp) if (coef&roundBit) != 0 && (coef&(3*roundBit-1)) != 0 { halfCoef++ } return uint16(halfSign | halfCoef) } uHalfExp := uint32(halfExp) << 10 halfCoef := coef >> 13 roundBit := uint32(0x00001000) if (coef&roundBit) != 0 && (coef&(3*roundBit-1)) != 0 { return uint16((halfSign | uHalfExp | halfCoef) + 1) } return uint16(halfSign | uHalfExp | halfCoef) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/shopspring/decimal/decimal.go
vendor/github.com/shopspring/decimal/decimal.go
// Package decimal implements an arbitrary precision fixed-point decimal. // // The zero-value of a Decimal is 0, as you would expect. // // The best way to create a new Decimal is to use decimal.NewFromString, ex: // // n, err := decimal.NewFromString("-123.4567") // n.String() // output: "-123.4567" // // To use Decimal as part of a struct: // // type StructName struct { // Number Decimal // } // // Note: This can "only" represent numbers with a maximum of 2^31 digits after the decimal point. package decimal import ( "database/sql/driver" "encoding/binary" "fmt" "math" "math/big" "regexp" "strconv" "strings" ) // DivisionPrecision is the number of decimal places in the result when it // doesn't divide exactly. // // Example: // // d1 := decimal.NewFromFloat(2).Div(decimal.NewFromFloat(3)) // d1.String() // output: "0.6666666666666667" // d2 := decimal.NewFromFloat(2).Div(decimal.NewFromFloat(30000)) // d2.String() // output: "0.0000666666666667" // d3 := decimal.NewFromFloat(20000).Div(decimal.NewFromFloat(3)) // d3.String() // output: "6666.6666666666666667" // decimal.DivisionPrecision = 3 // d4 := decimal.NewFromFloat(2).Div(decimal.NewFromFloat(3)) // d4.String() // output: "0.667" var DivisionPrecision = 16 // PowPrecisionNegativeExponent specifies the maximum precision of the result (digits after decimal point) // when calculating decimal power. Only used for cases where the exponent is a negative number. // This constant applies to Pow, PowInt32 and PowBigInt methods, PowWithPrecision method is not constrained by it. // // Example: // // d1, err := decimal.NewFromFloat(15.2).PowInt32(-2) // d1.String() // output: "0.0043282548476454" // // decimal.PowPrecisionNegativeExponent = 24 // d2, err := decimal.NewFromFloat(15.2).PowInt32(-2) // d2.String() // output: "0.004328254847645429362881" var PowPrecisionNegativeExponent = 16 // MarshalJSONWithoutQuotes should be set to true if you want the decimal to // be JSON marshaled as a number, instead of as a string. // WARNING: this is dangerous for decimals with many digits, since many JSON // unmarshallers (ex: Javascript's) will unmarshal JSON numbers to IEEE 754 // double-precision floating point numbers, which means you can potentially // silently lose precision. var MarshalJSONWithoutQuotes = false // ExpMaxIterations specifies the maximum number of iterations needed to calculate // precise natural exponent value using ExpHullAbrham method. var ExpMaxIterations = 1000 // Zero constant, to make computations faster. // Zero should never be compared with == or != directly, please use decimal.Equal or decimal.Cmp instead. var Zero = New(0, 1) var zeroInt = big.NewInt(0) var oneInt = big.NewInt(1) var twoInt = big.NewInt(2) var fourInt = big.NewInt(4) var fiveInt = big.NewInt(5) var tenInt = big.NewInt(10) var twentyInt = big.NewInt(20) var factorials = []Decimal{New(1, 0)} // Decimal represents a fixed-point decimal. It is immutable. // number = value * 10 ^ exp type Decimal struct { value *big.Int // NOTE(vadim): this must be an int32, because we cast it to float64 during // calculations. If exp is 64 bit, we might lose precision. // If we cared about being able to represent every possible decimal, we // could make exp a *big.Int but it would hurt performance and numbers // like that are unrealistic. exp int32 } // New returns a new fixed-point decimal, value * 10 ^ exp. func New(value int64, exp int32) Decimal { return Decimal{ value: big.NewInt(value), exp: exp, } } // NewFromInt converts an int64 to Decimal. // // Example: // // NewFromInt(123).String() // output: "123" // NewFromInt(-10).String() // output: "-10" func NewFromInt(value int64) Decimal { return Decimal{ value: big.NewInt(value), exp: 0, } } // NewFromInt32 converts an int32 to Decimal. // // Example: // // NewFromInt(123).String() // output: "123" // NewFromInt(-10).String() // output: "-10" func NewFromInt32(value int32) Decimal { return Decimal{ value: big.NewInt(int64(value)), exp: 0, } } // NewFromUint64 converts an uint64 to Decimal. // // Example: // // NewFromUint64(123).String() // output: "123" func NewFromUint64(value uint64) Decimal { return Decimal{ value: new(big.Int).SetUint64(value), exp: 0, } } // NewFromBigInt returns a new Decimal from a big.Int, value * 10 ^ exp func NewFromBigInt(value *big.Int, exp int32) Decimal { return Decimal{ value: new(big.Int).Set(value), exp: exp, } } // NewFromBigRat returns a new Decimal from a big.Rat. The numerator and // denominator are divided and rounded to the given precision. // // Example: // // d1 := NewFromBigRat(big.NewRat(0, 1), 0) // output: "0" // d2 := NewFromBigRat(big.NewRat(4, 5), 1) // output: "0.8" // d3 := NewFromBigRat(big.NewRat(1000, 3), 3) // output: "333.333" // d4 := NewFromBigRat(big.NewRat(2, 7), 4) // output: "0.2857" func NewFromBigRat(value *big.Rat, precision int32) Decimal { return Decimal{ value: new(big.Int).Set(value.Num()), exp: 0, }.DivRound(Decimal{ value: new(big.Int).Set(value.Denom()), exp: 0, }, precision) } // NewFromString returns a new Decimal from a string representation. // Trailing zeroes are not trimmed. // // Example: // // d, err := NewFromString("-123.45") // d2, err := NewFromString(".0001") // d3, err := NewFromString("1.47000") func NewFromString(value string) (Decimal, error) { originalInput := value var intString string var exp int64 // Check if number is using scientific notation eIndex := strings.IndexAny(value, "Ee") if eIndex != -1 { expInt, err := strconv.ParseInt(value[eIndex+1:], 10, 32) if err != nil { if e, ok := err.(*strconv.NumError); ok && e.Err == strconv.ErrRange { return Decimal{}, fmt.Errorf("can't convert %s to decimal: fractional part too long", value) } return Decimal{}, fmt.Errorf("can't convert %s to decimal: exponent is not numeric", value) } value = value[:eIndex] exp = expInt } pIndex := -1 vLen := len(value) for i := 0; i < vLen; i++ { if value[i] == '.' { if pIndex > -1 { return Decimal{}, fmt.Errorf("can't convert %s to decimal: too many .s", value) } pIndex = i } } if pIndex == -1 { // There is no decimal point, we can just parse the original string as // an int intString = value } else { if pIndex+1 < vLen { intString = value[:pIndex] + value[pIndex+1:] } else { intString = value[:pIndex] } expInt := -len(value[pIndex+1:]) exp += int64(expInt) } var dValue *big.Int // strconv.ParseInt is faster than new(big.Int).SetString so this is just a shortcut for strings we know won't overflow if len(intString) <= 18 { parsed64, err := strconv.ParseInt(intString, 10, 64) if err != nil { return Decimal{}, fmt.Errorf("can't convert %s to decimal", value) } dValue = big.NewInt(parsed64) } else { dValue = new(big.Int) _, ok := dValue.SetString(intString, 10) if !ok { return Decimal{}, fmt.Errorf("can't convert %s to decimal", value) } } if exp < math.MinInt32 || exp > math.MaxInt32 { // NOTE(vadim): I doubt a string could realistically be this long return Decimal{}, fmt.Errorf("can't convert %s to decimal: fractional part too long", originalInput) } return Decimal{ value: dValue, exp: int32(exp), }, nil } // NewFromFormattedString returns a new Decimal from a formatted string representation. // The second argument - replRegexp, is a regular expression that is used to find characters that should be // removed from given decimal string representation. All matched characters will be replaced with an empty string. // // Example: // // r := regexp.MustCompile("[$,]") // d1, err := NewFromFormattedString("$5,125.99", r) // // r2 := regexp.MustCompile("[_]") // d2, err := NewFromFormattedString("1_000_000", r2) // // r3 := regexp.MustCompile("[USD\\s]") // d3, err := NewFromFormattedString("5000 USD", r3) func NewFromFormattedString(value string, replRegexp *regexp.Regexp) (Decimal, error) { parsedValue := replRegexp.ReplaceAllString(value, "") d, err := NewFromString(parsedValue) if err != nil { return Decimal{}, err } return d, nil } // RequireFromString returns a new Decimal from a string representation // or panics if NewFromString had returned an error. // // Example: // // d := RequireFromString("-123.45") // d2 := RequireFromString(".0001") func RequireFromString(value string) Decimal { dec, err := NewFromString(value) if err != nil { panic(err) } return dec } // NewFromFloat converts a float64 to Decimal. // // The converted number will contain the number of significant digits that can be // represented in a float with reliable roundtrip. // This is typically 15 digits, but may be more in some cases. // See https://www.exploringbinary.com/decimal-precision-of-binary-floating-point-numbers/ for more information. // // For slightly faster conversion, use NewFromFloatWithExponent where you can specify the precision in absolute terms. // // NOTE: this will panic on NaN, +/-inf func NewFromFloat(value float64) Decimal { if value == 0 { return New(0, 0) } return newFromFloat(value, math.Float64bits(value), &float64info) } // NewFromFloat32 converts a float32 to Decimal. // // The converted number will contain the number of significant digits that can be // represented in a float with reliable roundtrip. // This is typically 6-8 digits depending on the input. // See https://www.exploringbinary.com/decimal-precision-of-binary-floating-point-numbers/ for more information. // // For slightly faster conversion, use NewFromFloatWithExponent where you can specify the precision in absolute terms. // // NOTE: this will panic on NaN, +/-inf func NewFromFloat32(value float32) Decimal { if value == 0 { return New(0, 0) } // XOR is workaround for https://github.com/golang/go/issues/26285 a := math.Float32bits(value) ^ 0x80808080 return newFromFloat(float64(value), uint64(a)^0x80808080, &float32info) } func newFromFloat(val float64, bits uint64, flt *floatInfo) Decimal { if math.IsNaN(val) || math.IsInf(val, 0) { panic(fmt.Sprintf("Cannot create a Decimal from %v", val)) } exp := int(bits>>flt.mantbits) & (1<<flt.expbits - 1) mant := bits & (uint64(1)<<flt.mantbits - 1) switch exp { case 0: // denormalized exp++ default: // add implicit top bit mant |= uint64(1) << flt.mantbits } exp += flt.bias var d decimal d.Assign(mant) d.Shift(exp - int(flt.mantbits)) d.neg = bits>>(flt.expbits+flt.mantbits) != 0 roundShortest(&d, mant, exp, flt) // If less than 19 digits, we can do calculation in an int64. if d.nd < 19 { tmp := int64(0) m := int64(1) for i := d.nd - 1; i >= 0; i-- { tmp += m * int64(d.d[i]-'0') m *= 10 } if d.neg { tmp *= -1 } return Decimal{value: big.NewInt(tmp), exp: int32(d.dp) - int32(d.nd)} } dValue := new(big.Int) dValue, ok := dValue.SetString(string(d.d[:d.nd]), 10) if ok { return Decimal{value: dValue, exp: int32(d.dp) - int32(d.nd)} } return NewFromFloatWithExponent(val, int32(d.dp)-int32(d.nd)) } // NewFromFloatWithExponent converts a float64 to Decimal, with an arbitrary // number of fractional digits. // // Example: // // NewFromFloatWithExponent(123.456, -2).String() // output: "123.46" func NewFromFloatWithExponent(value float64, exp int32) Decimal { if math.IsNaN(value) || math.IsInf(value, 0) { panic(fmt.Sprintf("Cannot create a Decimal from %v", value)) } bits := math.Float64bits(value) mant := bits & (1<<52 - 1) exp2 := int32((bits >> 52) & (1<<11 - 1)) sign := bits >> 63 if exp2 == 0 { // specials if mant == 0 { return Decimal{} } // subnormal exp2++ } else { // normal mant |= 1 << 52 } exp2 -= 1023 + 52 // normalizing base-2 values for mant&1 == 0 { mant = mant >> 1 exp2++ } // maximum number of fractional base-10 digits to represent 2^N exactly cannot be more than -N if N<0 if exp < 0 && exp < exp2 { if exp2 < 0 { exp = exp2 } else { exp = 0 } } // representing 10^M * 2^N as 5^M * 2^(M+N) exp2 -= exp temp := big.NewInt(1) dMant := big.NewInt(int64(mant)) // applying 5^M if exp > 0 { temp = temp.SetInt64(int64(exp)) temp = temp.Exp(fiveInt, temp, nil) } else if exp < 0 { temp = temp.SetInt64(-int64(exp)) temp = temp.Exp(fiveInt, temp, nil) dMant = dMant.Mul(dMant, temp) temp = temp.SetUint64(1) } // applying 2^(M+N) if exp2 > 0 { dMant = dMant.Lsh(dMant, uint(exp2)) } else if exp2 < 0 { temp = temp.Lsh(temp, uint(-exp2)) } // rounding and downscaling if exp > 0 || exp2 < 0 { halfDown := new(big.Int).Rsh(temp, 1) dMant = dMant.Add(dMant, halfDown) dMant = dMant.Quo(dMant, temp) } if sign == 1 { dMant = dMant.Neg(dMant) } return Decimal{ value: dMant, exp: exp, } } // Copy returns a copy of decimal with the same value and exponent, but a different pointer to value. func (d Decimal) Copy() Decimal { d.ensureInitialized() return Decimal{ value: new(big.Int).Set(d.value), exp: d.exp, } } // rescale returns a rescaled version of the decimal. Returned // decimal may be less precise if the given exponent is bigger // than the initial exponent of the Decimal. // NOTE: this will truncate, NOT round // // Example: // // d := New(12345, -4) // d2 := d.rescale(-1) // d3 := d2.rescale(-4) // println(d1) // println(d2) // println(d3) // // Output: // // 1.2345 // 1.2 // 1.2000 func (d Decimal) rescale(exp int32) Decimal { d.ensureInitialized() if d.exp == exp { return Decimal{ new(big.Int).Set(d.value), d.exp, } } // NOTE(vadim): must convert exps to float64 before - to prevent overflow diff := math.Abs(float64(exp) - float64(d.exp)) value := new(big.Int).Set(d.value) expScale := new(big.Int).Exp(tenInt, big.NewInt(int64(diff)), nil) if exp > d.exp { value = value.Quo(value, expScale) } else if exp < d.exp { value = value.Mul(value, expScale) } return Decimal{ value: value, exp: exp, } } // Abs returns the absolute value of the decimal. func (d Decimal) Abs() Decimal { if !d.IsNegative() { return d } d.ensureInitialized() d2Value := new(big.Int).Abs(d.value) return Decimal{ value: d2Value, exp: d.exp, } } // Add returns d + d2. func (d Decimal) Add(d2 Decimal) Decimal { rd, rd2 := RescalePair(d, d2) d3Value := new(big.Int).Add(rd.value, rd2.value) return Decimal{ value: d3Value, exp: rd.exp, } } // Sub returns d - d2. func (d Decimal) Sub(d2 Decimal) Decimal { rd, rd2 := RescalePair(d, d2) d3Value := new(big.Int).Sub(rd.value, rd2.value) return Decimal{ value: d3Value, exp: rd.exp, } } // Neg returns -d. func (d Decimal) Neg() Decimal { d.ensureInitialized() val := new(big.Int).Neg(d.value) return Decimal{ value: val, exp: d.exp, } } // Mul returns d * d2. func (d Decimal) Mul(d2 Decimal) Decimal { d.ensureInitialized() d2.ensureInitialized() expInt64 := int64(d.exp) + int64(d2.exp) if expInt64 > math.MaxInt32 || expInt64 < math.MinInt32 { // NOTE(vadim): better to panic than give incorrect results, as // Decimals are usually used for money panic(fmt.Sprintf("exponent %v overflows an int32!", expInt64)) } d3Value := new(big.Int).Mul(d.value, d2.value) return Decimal{ value: d3Value, exp: int32(expInt64), } } // Shift shifts the decimal in base 10. // It shifts left when shift is positive and right if shift is negative. // In simpler terms, the given value for shift is added to the exponent // of the decimal. func (d Decimal) Shift(shift int32) Decimal { d.ensureInitialized() return Decimal{ value: new(big.Int).Set(d.value), exp: d.exp + shift, } } // Div returns d / d2. If it doesn't divide exactly, the result will have // DivisionPrecision digits after the decimal point. func (d Decimal) Div(d2 Decimal) Decimal { return d.DivRound(d2, int32(DivisionPrecision)) } // QuoRem does division with remainder // d.QuoRem(d2,precision) returns quotient q and remainder r such that // // d = d2 * q + r, q an integer multiple of 10^(-precision) // 0 <= r < abs(d2) * 10 ^(-precision) if d>=0 // 0 >= r > -abs(d2) * 10 ^(-precision) if d<0 // // Note that precision<0 is allowed as input. func (d Decimal) QuoRem(d2 Decimal, precision int32) (Decimal, Decimal) { d.ensureInitialized() d2.ensureInitialized() if d2.value.Sign() == 0 { panic("decimal division by 0") } scale := -precision e := int64(d.exp) - int64(d2.exp) - int64(scale) if e > math.MaxInt32 || e < math.MinInt32 { panic("overflow in decimal QuoRem") } var aa, bb, expo big.Int var scalerest int32 // d = a 10^ea // d2 = b 10^eb if e < 0 { aa = *d.value expo.SetInt64(-e) bb.Exp(tenInt, &expo, nil) bb.Mul(d2.value, &bb) scalerest = d.exp // now aa = a // bb = b 10^(scale + eb - ea) } else { expo.SetInt64(e) aa.Exp(tenInt, &expo, nil) aa.Mul(d.value, &aa) bb = *d2.value scalerest = scale + d2.exp // now aa = a ^ (ea - eb - scale) // bb = b } var q, r big.Int q.QuoRem(&aa, &bb, &r) dq := Decimal{value: &q, exp: scale} dr := Decimal{value: &r, exp: scalerest} return dq, dr } // DivRound divides and rounds to a given precision // i.e. to an integer multiple of 10^(-precision) // // for a positive quotient digit 5 is rounded up, away from 0 // if the quotient is negative then digit 5 is rounded down, away from 0 // // Note that precision<0 is allowed as input. func (d Decimal) DivRound(d2 Decimal, precision int32) Decimal { // QuoRem already checks initialization q, r := d.QuoRem(d2, precision) // the actual rounding decision is based on comparing r*10^precision and d2/2 // instead compare 2 r 10 ^precision and d2 var rv2 big.Int rv2.Abs(r.value) rv2.Lsh(&rv2, 1) // now rv2 = abs(r.value) * 2 r2 := Decimal{value: &rv2, exp: r.exp + precision} // r2 is now 2 * r * 10 ^ precision var c = r2.Cmp(d2.Abs()) if c < 0 { return q } if d.value.Sign()*d2.value.Sign() < 0 { return q.Sub(New(1, -precision)) } return q.Add(New(1, -precision)) } // Mod returns d % d2. func (d Decimal) Mod(d2 Decimal) Decimal { _, r := d.QuoRem(d2, 0) return r } // Pow returns d to the power of d2. // When exponent is negative the returned decimal will have maximum precision of PowPrecisionNegativeExponent places after decimal point. // // Pow returns 0 (zero-value of Decimal) instead of error for power operation edge cases, to handle those edge cases use PowWithPrecision // Edge cases not handled by Pow: // - 0 ** 0 => undefined value // - 0 ** y, where y < 0 => infinity // - x ** y, where x < 0 and y is non-integer decimal => imaginary value // // Example: // // d1 := decimal.NewFromFloat(4.0) // d2 := decimal.NewFromFloat(4.0) // res1 := d1.Pow(d2) // res1.String() // output: "256" // // d3 := decimal.NewFromFloat(5.0) // d4 := decimal.NewFromFloat(5.73) // res2 := d3.Pow(d4) // res2.String() // output: "10118.08037125" func (d Decimal) Pow(d2 Decimal) Decimal { baseSign := d.Sign() expSign := d2.Sign() if baseSign == 0 { if expSign == 0 { return Decimal{} } if expSign == 1 { return Decimal{zeroInt, 0} } if expSign == -1 { return Decimal{} } } if expSign == 0 { return Decimal{oneInt, 0} } // TODO: optimize extraction of fractional part one := Decimal{oneInt, 0} expIntPart, expFracPart := d2.QuoRem(one, 0) if baseSign == -1 && !expFracPart.IsZero() { return Decimal{} } intPartPow, _ := d.PowBigInt(expIntPart.value) // if exponent is an integer we don't need to calculate d1**frac(d2) if expFracPart.value.Sign() == 0 { return intPartPow } // TODO: optimize NumDigits for more performant precision adjustment digitsBase := d.NumDigits() digitsExponent := d2.NumDigits() precision := digitsBase if digitsExponent > precision { precision += digitsExponent } precision += 6 // Calculate x ** frac(y), where // x ** frac(y) = exp(ln(x ** frac(y)) = exp(ln(x) * frac(y)) fracPartPow, err := d.Abs().Ln(-d.exp + int32(precision)) if err != nil { return Decimal{} } fracPartPow = fracPartPow.Mul(expFracPart) fracPartPow, err = fracPartPow.ExpTaylor(-d.exp + int32(precision)) if err != nil { return Decimal{} } // Join integer and fractional part, // base ** (expBase + expFrac) = base ** expBase * base ** expFrac res := intPartPow.Mul(fracPartPow) return res } // PowWithPrecision returns d to the power of d2. // Precision parameter specifies minimum precision of the result (digits after decimal point). // Returned decimal is not rounded to 'precision' places after decimal point. // // PowWithPrecision returns error when: // - 0 ** 0 => undefined value // - 0 ** y, where y < 0 => infinity // - x ** y, where x < 0 and y is non-integer decimal => imaginary value // // Example: // // d1 := decimal.NewFromFloat(4.0) // d2 := decimal.NewFromFloat(4.0) // res1, err := d1.PowWithPrecision(d2, 2) // res1.String() // output: "256" // // d3 := decimal.NewFromFloat(5.0) // d4 := decimal.NewFromFloat(5.73) // res2, err := d3.PowWithPrecision(d4, 5) // res2.String() // output: "10118.080371595015625" // // d5 := decimal.NewFromFloat(-3.0) // d6 := decimal.NewFromFloat(-6.0) // res3, err := d5.PowWithPrecision(d6, 10) // res3.String() // output: "0.0013717421" func (d Decimal) PowWithPrecision(d2 Decimal, precision int32) (Decimal, error) { baseSign := d.Sign() expSign := d2.Sign() if baseSign == 0 { if expSign == 0 { return Decimal{}, fmt.Errorf("cannot represent undefined value of 0**0") } if expSign == 1 { return Decimal{zeroInt, 0}, nil } if expSign == -1 { return Decimal{}, fmt.Errorf("cannot represent infinity value of 0 ** y, where y < 0") } } if expSign == 0 { return Decimal{oneInt, 0}, nil } // TODO: optimize extraction of fractional part one := Decimal{oneInt, 0} expIntPart, expFracPart := d2.QuoRem(one, 0) if baseSign == -1 && !expFracPart.IsZero() { return Decimal{}, fmt.Errorf("cannot represent imaginary value of x ** y, where x < 0 and y is non-integer decimal") } intPartPow, _ := d.powBigIntWithPrecision(expIntPart.value, precision) // if exponent is an integer we don't need to calculate d1**frac(d2) if expFracPart.value.Sign() == 0 { return intPartPow, nil } // TODO: optimize NumDigits for more performant precision adjustment digitsBase := d.NumDigits() digitsExponent := d2.NumDigits() if int32(digitsBase) > precision { precision = int32(digitsBase) } if int32(digitsExponent) > precision { precision += int32(digitsExponent) } // increase precision by 10 to compensate for errors in further calculations precision += 10 // Calculate x ** frac(y), where // x ** frac(y) = exp(ln(x ** frac(y)) = exp(ln(x) * frac(y)) fracPartPow, err := d.Abs().Ln(precision) if err != nil { return Decimal{}, err } fracPartPow = fracPartPow.Mul(expFracPart) fracPartPow, err = fracPartPow.ExpTaylor(precision) if err != nil { return Decimal{}, err } // Join integer and fractional part, // base ** (expBase + expFrac) = base ** expBase * base ** expFrac res := intPartPow.Mul(fracPartPow) return res, nil } // PowInt32 returns d to the power of exp, where exp is int32. // Only returns error when d and exp is 0, thus result is undefined. // // When exponent is negative the returned decimal will have maximum precision of PowPrecisionNegativeExponent places after decimal point. // // Example: // // d1, err := decimal.NewFromFloat(4.0).PowInt32(4) // d1.String() // output: "256" // // d2, err := decimal.NewFromFloat(3.13).PowInt32(5) // d2.String() // output: "300.4150512793" func (d Decimal) PowInt32(exp int32) (Decimal, error) { if d.IsZero() && exp == 0 { return Decimal{}, fmt.Errorf("cannot represent undefined value of 0**0") } isExpNeg := exp < 0 exp = abs(exp) n, result := d, New(1, 0) for exp > 0 { if exp%2 == 1 { result = result.Mul(n) } exp /= 2 if exp > 0 { n = n.Mul(n) } } if isExpNeg { return New(1, 0).DivRound(result, int32(PowPrecisionNegativeExponent)), nil } return result, nil } // PowBigInt returns d to the power of exp, where exp is big.Int. // Only returns error when d and exp is 0, thus result is undefined. // // When exponent is negative the returned decimal will have maximum precision of PowPrecisionNegativeExponent places after decimal point. // // Example: // // d1, err := decimal.NewFromFloat(3.0).PowBigInt(big.NewInt(3)) // d1.String() // output: "27" // // d2, err := decimal.NewFromFloat(629.25).PowBigInt(big.NewInt(5)) // d2.String() // output: "98654323103449.5673828125" func (d Decimal) PowBigInt(exp *big.Int) (Decimal, error) { return d.powBigIntWithPrecision(exp, int32(PowPrecisionNegativeExponent)) } func (d Decimal) powBigIntWithPrecision(exp *big.Int, precision int32) (Decimal, error) { if d.IsZero() && exp.Sign() == 0 { return Decimal{}, fmt.Errorf("cannot represent undefined value of 0**0") } tmpExp := new(big.Int).Set(exp) isExpNeg := exp.Sign() < 0 if isExpNeg { tmpExp.Abs(tmpExp) } n, result := d, New(1, 0) for tmpExp.Sign() > 0 { if tmpExp.Bit(0) == 1 { result = result.Mul(n) } tmpExp.Rsh(tmpExp, 1) if tmpExp.Sign() > 0 { n = n.Mul(n) } } if isExpNeg { return New(1, 0).DivRound(result, precision), nil } return result, nil } // ExpHullAbrham calculates the natural exponent of decimal (e to the power of d) using Hull-Abraham algorithm. // OverallPrecision argument specifies the overall precision of the result (integer part + decimal part). // // ExpHullAbrham is faster than ExpTaylor for small precision values, but it is much slower for large precision values. // // Example: // // NewFromFloat(26.1).ExpHullAbrham(2).String() // output: "220000000000" // NewFromFloat(26.1).ExpHullAbrham(20).String() // output: "216314672147.05767284" func (d Decimal) ExpHullAbrham(overallPrecision uint32) (Decimal, error) { // Algorithm based on Variable precision exponential function. // ACM Transactions on Mathematical Software by T. E. Hull & A. Abrham. if d.IsZero() { return Decimal{oneInt, 0}, nil } currentPrecision := overallPrecision // Algorithm does not work if currentPrecision * 23 < |x|. // Precision is automatically increased in such cases, so the value can be calculated precisely. // If newly calculated precision is higher than ExpMaxIterations the currentPrecision will not be changed. f := d.Abs().InexactFloat64() if ncp := f / 23; ncp > float64(currentPrecision) && ncp < float64(ExpMaxIterations) { currentPrecision = uint32(math.Ceil(ncp)) } // fail if abs(d) beyond an over/underflow threshold overflowThreshold := New(23*int64(currentPrecision), 0) if d.Abs().Cmp(overflowThreshold) > 0 { return Decimal{}, fmt.Errorf("over/underflow threshold, exp(x) cannot be calculated precisely") } // Return 1 if abs(d) small enough; this also avoids later over/underflow overflowThreshold2 := New(9, -int32(currentPrecision)-1) if d.Abs().Cmp(overflowThreshold2) <= 0 { return Decimal{oneInt, d.exp}, nil } // t is the smallest integer >= 0 such that the corresponding abs(d/k) < 1 t := d.exp + int32(d.NumDigits()) // Add d.NumDigits because the paper assumes that d.value [0.1, 1) if t < 0 { t = 0 } k := New(1, t) // reduction factor r := Decimal{new(big.Int).Set(d.value), d.exp - t} // reduced argument p := int32(currentPrecision) + t + 2 // precision for calculating the sum // Determine n, the number of therms for calculating sum // use first Newton step (1.435p - 1.182) / log10(p/abs(r)) // for solving appropriate equation, along with directed // roundings and simple rational bound for log10(p/abs(r)) rf := r.Abs().InexactFloat64() pf := float64(p) nf := math.Ceil((1.453*pf - 1.182) / math.Log10(pf/rf)) if nf > float64(ExpMaxIterations) || math.IsNaN(nf) { return Decimal{}, fmt.Errorf("exact value cannot be calculated in <=ExpMaxIterations iterations") } n := int64(nf) tmp := New(0, 0) sum := New(1, 0) one := New(1, 0) for i := n - 1; i > 0; i-- { tmp.value.SetInt64(i) sum = sum.Mul(r.DivRound(tmp, p)) sum = sum.Add(one) } ki := k.IntPart() res := New(1, 0) for i := ki; i > 0; i-- { res = res.Mul(sum) } resNumDigits := int32(res.NumDigits()) var roundDigits int32 if resNumDigits > abs(res.exp) { roundDigits = int32(currentPrecision) - resNumDigits - res.exp } else { roundDigits = int32(currentPrecision) } res = res.Round(roundDigits) return res, nil } // ExpTaylor calculates the natural exponent of decimal (e to the power of d) using Taylor series expansion. // Precision argument specifies how precise the result must be (number of digits after decimal point). // Negative precision is allowed. // // ExpTaylor is much faster for large precision values than ExpHullAbrham. // // Example: // // d, err := NewFromFloat(26.1).ExpTaylor(2).String() // d.String() // output: "216314672147.06" // // NewFromFloat(26.1).ExpTaylor(20).String() // d.String() // output: "216314672147.05767284062928674083" // // NewFromFloat(26.1).ExpTaylor(-10).String() // d.String() // output: "220000000000" func (d Decimal) ExpTaylor(precision int32) (Decimal, error) { // Note(mwoss): Implementation can be optimized by exclusively using big.Int API only if d.IsZero() { return Decimal{oneInt, 0}.Round(precision), nil } var epsilon Decimal var divPrecision int32 if precision < 0 { epsilon = New(1, -1) divPrecision = 8 } else { epsilon = New(1, -precision-1) divPrecision = precision + 1 } decAbs := d.Abs() pow := d.Abs() factorial := New(1, 0) result := New(1, 0) for i := int64(1); ; { step := pow.DivRound(factorial, divPrecision) result = result.Add(step) // Stop Taylor series when current step is smaller than epsilon if step.Cmp(epsilon) < 0 { break } pow = pow.Mul(decAbs) i++ // Calculate next factorial number or retrieve cached value if len(factorials) >= int(i) && !factorials[i-1].IsZero() { factorial = factorials[i-1] } else { // To avoid any race conditions, firstly the zero value is appended to a slice to create // a spot for newly calculated factorial. After that, the zero value is replaced by calculated // factorial using the index notation. factorial = factorials[i-2].Mul(New(i, 0)) factorials = append(factorials, Zero) factorials[i-1] = factorial } } if d.Sign() < 0 { result = New(1, 0).DivRound(result, precision+1) } result = result.Round(precision) return result, nil } // Ln calculates natural logarithm of d. // Precision argument specifies how precise the result must be (number of digits after decimal point). // Negative precision is allowed. // // Example: // // d1, err := NewFromFloat(13.3).Ln(2) // d1.String() // output: "2.59" // // d2, err := NewFromFloat(579.161).Ln(10) // d2.String() // output: "6.3615805046" func (d Decimal) Ln(precision int32) (Decimal, error) { // Algorithm based on The Use of Iteration Methods for Approximating the Natural Logarithm, // James F. Epperson, The American Mathematical Monthly, Vol. 96, No. 9, November 1989, pp. 831-835. if d.IsNegative() { return Decimal{}, fmt.Errorf("cannot calculate natural logarithm for negative decimals") } if d.IsZero() { return Decimal{}, fmt.Errorf("cannot represent natural logarithm of 0, result: -infinity") } calcPrecision := precision + 2 z := d.Copy() var comp1, comp3, comp2, comp4, reduceAdjust Decimal comp1 = z.Sub(Decimal{oneInt, 0}) comp3 = Decimal{oneInt, -1} // for decimal in range [0.9, 1.1] where ln(d) is close to 0 usePowerSeries := false if comp1.Abs().Cmp(comp3) <= 0 { usePowerSeries = true } else { // reduce input decimal to range [0.1, 1) expDelta := int32(z.NumDigits()) + z.exp z.exp -= expDelta // Input decimal was reduced by factor of 10^expDelta, thus we will need to add // ln(10^expDelta) = expDelta * ln(10) // to the result to compensate that ln10 := ln10.withPrecision(calcPrecision) reduceAdjust = NewFromInt32(expDelta) reduceAdjust = reduceAdjust.Mul(ln10) comp1 = z.Sub(Decimal{oneInt, 0}) if comp1.Abs().Cmp(comp3) <= 0 { usePowerSeries = true } else { // initial estimate using floats zFloat := z.InexactFloat64() comp1 = NewFromFloat(math.Log(zFloat)) } } epsilon := Decimal{oneInt, -calcPrecision} if usePowerSeries { // Power Series - https://en.wikipedia.org/wiki/Logarithm#Power_series // Calculating n-th term of formula: ln(z+1) = 2 sum [ 1 / (2n+1) * (z / (z+2))^(2n+1) ] // until the difference between current and next term is smaller than epsilon. // Coverage quite fast for decimals close to 1.0 // z + 2 comp2 = comp1.Add(Decimal{twoInt, 0}) // z / (z + 2) comp3 = comp1.DivRound(comp2, calcPrecision) // 2 * (z / (z + 2))
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/shopspring/decimal/const.go
vendor/github.com/shopspring/decimal/const.go
package decimal import ( "strings" ) const ( strLn10 = "2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286248633409525465082806756666287369098781689482907208325554680843799894826233198528393505308965377732628846163366222287698219886746543667474404243274365155048934314939391479619404400222105101714174800368808401264708068556774321622835522011480466371565912137345074785694768346361679210180644507064800027750268491674655058685693567342067058113642922455440575892572420824131469568901675894025677631135691929203337658714166023010570308963457207544037084746994016826928280848118428931484852494864487192780967627127577539702766860595249671667418348570442250719796500471495105049221477656763693866297697952211071826454973477266242570942932258279850258550978526538320760672631716430950599508780752371033310119785754733154142180842754386359177811705430982748238504564801909561029929182431823752535770975053956518769751037497088869218020518933950723853920514463419726528728696511086257149219884997874887377134568620916705849807828059751193854445009978131146915934666241071846692310107598438319191292230792503747298650929009880391941702654416816335727555703151596113564846546190897042819763365836983716328982174407366009162177850541779276367731145041782137660111010731042397832521894898817597921798666394319523936855916447118246753245630912528778330963604262982153040874560927760726641354787576616262926568298704957954913954918049209069438580790032763017941503117866862092408537949861264933479354871737451675809537088281067452440105892444976479686075120275724181874989395971643105518848195288330746699317814634930000321200327765654130472621883970596794457943468343218395304414844803701305753674262153675579814770458031413637793236291560128185336498466942261465206459942072917119370602444929358037007718981097362533224548366988505528285966192805098447175198503666680874970496982273220244823343097169111136813588418696549323714996941979687803008850408979618598756579894836445212043698216415292987811742973332588607915912510967187510929248475023930572665446276200923068791518135803477701295593646298412366497023355174586195564772461857717369368404676577047874319780573853271810933883496338813069945569399346101090745616033312247949360455361849123333063704751724871276379140924398331810164737823379692265637682071706935846394531616949411701841938119405416449466111274712819705817783293841742231409930022911502362192186723337268385688273533371925103412930705632544426611429765388301822384091026198582888433587455960453004548370789052578473166283701953392231047527564998119228742789713715713228319641003422124210082180679525276689858180956119208391760721080919923461516952599099473782780648128058792731993893453415320185969711021407542282796298237068941764740642225757212455392526179373652434440560595336591539160312524480149313234572453879524389036839236450507881731359711238145323701508413491122324390927681724749607955799151363982881058285740538000653371655553014196332241918087621018204919492651483892" ) var ( ln10 = newConstApproximation(strLn10) ) type constApproximation struct { exact Decimal approximations []Decimal } func newConstApproximation(value string) constApproximation { parts := strings.Split(value, ".") coeff, fractional := parts[0], parts[1] coeffLen := len(coeff) maxPrecision := len(fractional) var approximations []Decimal for p := 1; p < maxPrecision; p *= 2 { r := RequireFromString(value[:coeffLen+p]) approximations = append(approximations, r) } return constApproximation{ RequireFromString(value), approximations, } } // Returns the smallest approximation available that's at least as precise // as the passed precision (places after decimal point), i.e. Floor[ log2(precision) ] + 1 func (c constApproximation) withPrecision(precision int32) Decimal { i := 0 if precision >= 1 { i++ } for precision >= 16 { precision /= 16 i += 4 } for precision >= 2 { precision /= 2 i++ } if i >= len(c.approximations) { return c.exact } return c.approximations[i] }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/shopspring/decimal/rounding.go
vendor/github.com/shopspring/decimal/rounding.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Multiprecision decimal numbers. // For floating-point formatting only; not general purpose. // Only operations are assign and (binary) left/right shift. // Can do binary floating point in multiprecision decimal precisely // because 2 divides 10; cannot do decimal floating point // in multiprecision binary precisely. package decimal type floatInfo struct { mantbits uint expbits uint bias int } var float32info = floatInfo{23, 8, -127} var float64info = floatInfo{52, 11, -1023} // roundShortest rounds d (= mant * 2^exp) to the shortest number of digits // that will let the original floating point value be precisely reconstructed. func roundShortest(d *decimal, mant uint64, exp int, flt *floatInfo) { // If mantissa is zero, the number is zero; stop now. if mant == 0 { d.nd = 0 return } // Compute upper and lower such that any decimal number // between upper and lower (possibly inclusive) // will round to the original floating point number. // We may see at once that the number is already shortest. // // Suppose d is not denormal, so that 2^exp <= d < 10^dp. // The closest shorter number is at least 10^(dp-nd) away. // The lower/upper bounds computed below are at distance // at most 2^(exp-mantbits). // // So the number is already shortest if 10^(dp-nd) > 2^(exp-mantbits), // or equivalently log2(10)*(dp-nd) > exp-mantbits. // It is true if 332/100*(dp-nd) >= exp-mantbits (log2(10) > 3.32). minexp := flt.bias + 1 // minimum possible exponent if exp > minexp && 332*(d.dp-d.nd) >= 100*(exp-int(flt.mantbits)) { // The number is already shortest. return } // d = mant << (exp - mantbits) // Next highest floating point number is mant+1 << exp-mantbits. // Our upper bound is halfway between, mant*2+1 << exp-mantbits-1. upper := new(decimal) upper.Assign(mant*2 + 1) upper.Shift(exp - int(flt.mantbits) - 1) // d = mant << (exp - mantbits) // Next lowest floating point number is mant-1 << exp-mantbits, // unless mant-1 drops the significant bit and exp is not the minimum exp, // in which case the next lowest is mant*2-1 << exp-mantbits-1. // Either way, call it mantlo << explo-mantbits. // Our lower bound is halfway between, mantlo*2+1 << explo-mantbits-1. var mantlo uint64 var explo int if mant > 1<<flt.mantbits || exp == minexp { mantlo = mant - 1 explo = exp } else { mantlo = mant*2 - 1 explo = exp - 1 } lower := new(decimal) lower.Assign(mantlo*2 + 1) lower.Shift(explo - int(flt.mantbits) - 1) // The upper and lower bounds are possible outputs only if // the original mantissa is even, so that IEEE round-to-even // would round to the original mantissa and not the neighbors. inclusive := mant%2 == 0 // As we walk the digits we want to know whether rounding up would fall // within the upper bound. This is tracked by upperdelta: // // If upperdelta == 0, the digits of d and upper are the same so far. // // If upperdelta == 1, we saw a difference of 1 between d and upper on a // previous digit and subsequently only 9s for d and 0s for upper. // (Thus rounding up may fall outside the bound, if it is exclusive.) // // If upperdelta == 2, then the difference is greater than 1 // and we know that rounding up falls within the bound. var upperdelta uint8 // Now we can figure out the minimum number of digits required. // Walk along until d has distinguished itself from upper and lower. for ui := 0; ; ui++ { // lower, d, and upper may have the decimal points at different // places. In this case upper is the longest, so we iterate from // ui==0 and start li and mi at (possibly) -1. mi := ui - upper.dp + d.dp if mi >= d.nd { break } li := ui - upper.dp + lower.dp l := byte('0') // lower digit if li >= 0 && li < lower.nd { l = lower.d[li] } m := byte('0') // middle digit if mi >= 0 { m = d.d[mi] } u := byte('0') // upper digit if ui < upper.nd { u = upper.d[ui] } // Okay to round down (truncate) if lower has a different digit // or if lower is inclusive and is exactly the result of rounding // down (i.e., and we have reached the final digit of lower). okdown := l != m || inclusive && li+1 == lower.nd switch { case upperdelta == 0 && m+1 < u: // Example: // m = 12345xxx // u = 12347xxx upperdelta = 2 case upperdelta == 0 && m != u: // Example: // m = 12345xxx // u = 12346xxx upperdelta = 1 case upperdelta == 1 && (m != '9' || u != '0'): // Example: // m = 1234598x // u = 1234600x upperdelta = 2 } // Okay to round up if upper has a different digit and either upper // is inclusive or upper is bigger than the result of rounding up. okup := upperdelta > 0 && (inclusive || upperdelta > 1 || ui+1 < upper.nd) // If it's okay to do either, then round to the nearest one. // If it's okay to do only one, do it. switch { case okdown && okup: d.Round(mi + 1) return case okdown: d.RoundDown(mi + 1) return case okup: d.RoundUp(mi + 1) return } } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/shopspring/decimal/decimal-go.go
vendor/github.com/shopspring/decimal/decimal-go.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Multiprecision decimal numbers. // For floating-point formatting only; not general purpose. // Only operations are assign and (binary) left/right shift. // Can do binary floating point in multiprecision decimal precisely // because 2 divides 10; cannot do decimal floating point // in multiprecision binary precisely. package decimal type decimal struct { d [800]byte // digits, big-endian representation nd int // number of digits used dp int // decimal point neg bool // negative flag trunc bool // discarded nonzero digits beyond d[:nd] } func (a *decimal) String() string { n := 10 + a.nd if a.dp > 0 { n += a.dp } if a.dp < 0 { n += -a.dp } buf := make([]byte, n) w := 0 switch { case a.nd == 0: return "0" case a.dp <= 0: // zeros fill space between decimal point and digits buf[w] = '0' w++ buf[w] = '.' w++ w += digitZero(buf[w : w+-a.dp]) w += copy(buf[w:], a.d[0:a.nd]) case a.dp < a.nd: // decimal point in middle of digits w += copy(buf[w:], a.d[0:a.dp]) buf[w] = '.' w++ w += copy(buf[w:], a.d[a.dp:a.nd]) default: // zeros fill space between digits and decimal point w += copy(buf[w:], a.d[0:a.nd]) w += digitZero(buf[w : w+a.dp-a.nd]) } return string(buf[0:w]) } func digitZero(dst []byte) int { for i := range dst { dst[i] = '0' } return len(dst) } // trim trailing zeros from number. // (They are meaningless; the decimal point is tracked // independent of the number of digits.) func trim(a *decimal) { for a.nd > 0 && a.d[a.nd-1] == '0' { a.nd-- } if a.nd == 0 { a.dp = 0 } } // Assign v to a. func (a *decimal) Assign(v uint64) { var buf [24]byte // Write reversed decimal in buf. n := 0 for v > 0 { v1 := v / 10 v -= 10 * v1 buf[n] = byte(v + '0') n++ v = v1 } // Reverse again to produce forward decimal in a.d. a.nd = 0 for n--; n >= 0; n-- { a.d[a.nd] = buf[n] a.nd++ } a.dp = a.nd trim(a) } // Maximum shift that we can do in one pass without overflow. // A uint has 32 or 64 bits, and we have to be able to accommodate 9<<k. const uintSize = 32 << (^uint(0) >> 63) const maxShift = uintSize - 4 // Binary shift right (/ 2) by k bits. k <= maxShift to avoid overflow. func rightShift(a *decimal, k uint) { r := 0 // read pointer w := 0 // write pointer // Pick up enough leading digits to cover first shift. var n uint for ; n>>k == 0; r++ { if r >= a.nd { if n == 0 { // a == 0; shouldn't get here, but handle anyway. a.nd = 0 return } for n>>k == 0 { n = n * 10 r++ } break } c := uint(a.d[r]) n = n*10 + c - '0' } a.dp -= r - 1 var mask uint = (1 << k) - 1 // Pick up a digit, put down a digit. for ; r < a.nd; r++ { c := uint(a.d[r]) dig := n >> k n &= mask a.d[w] = byte(dig + '0') w++ n = n*10 + c - '0' } // Put down extra digits. for n > 0 { dig := n >> k n &= mask if w < len(a.d) { a.d[w] = byte(dig + '0') w++ } else if dig > 0 { a.trunc = true } n = n * 10 } a.nd = w trim(a) } // Cheat sheet for left shift: table indexed by shift count giving // number of new digits that will be introduced by that shift. // // For example, leftcheats[4] = {2, "625"}. That means that // if we are shifting by 4 (multiplying by 16), it will add 2 digits // when the string prefix is "625" through "999", and one fewer digit // if the string prefix is "000" through "624". // // Credit for this trick goes to Ken. type leftCheat struct { delta int // number of new digits cutoff string // minus one digit if original < a. } var leftcheats = []leftCheat{ // Leading digits of 1/2^i = 5^i. // 5^23 is not an exact 64-bit floating point number, // so have to use bc for the math. // Go up to 60 to be large enough for 32bit and 64bit platforms. /* seq 60 | sed 's/^/5^/' | bc | awk 'BEGIN{ print "\t{ 0, \"\" }," } { log2 = log(2)/log(10) printf("\t{ %d, \"%s\" },\t// * %d\n", int(log2*NR+1), $0, 2**NR) }' */ {0, ""}, {1, "5"}, // * 2 {1, "25"}, // * 4 {1, "125"}, // * 8 {2, "625"}, // * 16 {2, "3125"}, // * 32 {2, "15625"}, // * 64 {3, "78125"}, // * 128 {3, "390625"}, // * 256 {3, "1953125"}, // * 512 {4, "9765625"}, // * 1024 {4, "48828125"}, // * 2048 {4, "244140625"}, // * 4096 {4, "1220703125"}, // * 8192 {5, "6103515625"}, // * 16384 {5, "30517578125"}, // * 32768 {5, "152587890625"}, // * 65536 {6, "762939453125"}, // * 131072 {6, "3814697265625"}, // * 262144 {6, "19073486328125"}, // * 524288 {7, "95367431640625"}, // * 1048576 {7, "476837158203125"}, // * 2097152 {7, "2384185791015625"}, // * 4194304 {7, "11920928955078125"}, // * 8388608 {8, "59604644775390625"}, // * 16777216 {8, "298023223876953125"}, // * 33554432 {8, "1490116119384765625"}, // * 67108864 {9, "7450580596923828125"}, // * 134217728 {9, "37252902984619140625"}, // * 268435456 {9, "186264514923095703125"}, // * 536870912 {10, "931322574615478515625"}, // * 1073741824 {10, "4656612873077392578125"}, // * 2147483648 {10, "23283064365386962890625"}, // * 4294967296 {10, "116415321826934814453125"}, // * 8589934592 {11, "582076609134674072265625"}, // * 17179869184 {11, "2910383045673370361328125"}, // * 34359738368 {11, "14551915228366851806640625"}, // * 68719476736 {12, "72759576141834259033203125"}, // * 137438953472 {12, "363797880709171295166015625"}, // * 274877906944 {12, "1818989403545856475830078125"}, // * 549755813888 {13, "9094947017729282379150390625"}, // * 1099511627776 {13, "45474735088646411895751953125"}, // * 2199023255552 {13, "227373675443232059478759765625"}, // * 4398046511104 {13, "1136868377216160297393798828125"}, // * 8796093022208 {14, "5684341886080801486968994140625"}, // * 17592186044416 {14, "28421709430404007434844970703125"}, // * 35184372088832 {14, "142108547152020037174224853515625"}, // * 70368744177664 {15, "710542735760100185871124267578125"}, // * 140737488355328 {15, "3552713678800500929355621337890625"}, // * 281474976710656 {15, "17763568394002504646778106689453125"}, // * 562949953421312 {16, "88817841970012523233890533447265625"}, // * 1125899906842624 {16, "444089209850062616169452667236328125"}, // * 2251799813685248 {16, "2220446049250313080847263336181640625"}, // * 4503599627370496 {16, "11102230246251565404236316680908203125"}, // * 9007199254740992 {17, "55511151231257827021181583404541015625"}, // * 18014398509481984 {17, "277555756156289135105907917022705078125"}, // * 36028797018963968 {17, "1387778780781445675529539585113525390625"}, // * 72057594037927936 {18, "6938893903907228377647697925567626953125"}, // * 144115188075855872 {18, "34694469519536141888238489627838134765625"}, // * 288230376151711744 {18, "173472347597680709441192448139190673828125"}, // * 576460752303423488 {19, "867361737988403547205962240695953369140625"}, // * 1152921504606846976 } // Is the leading prefix of b lexicographically less than s? func prefixIsLessThan(b []byte, s string) bool { for i := 0; i < len(s); i++ { if i >= len(b) { return true } if b[i] != s[i] { return b[i] < s[i] } } return false } // Binary shift left (* 2) by k bits. k <= maxShift to avoid overflow. func leftShift(a *decimal, k uint) { delta := leftcheats[k].delta if prefixIsLessThan(a.d[0:a.nd], leftcheats[k].cutoff) { delta-- } r := a.nd // read index w := a.nd + delta // write index // Pick up a digit, put down a digit. var n uint for r--; r >= 0; r-- { n += (uint(a.d[r]) - '0') << k quo := n / 10 rem := n - 10*quo w-- if w < len(a.d) { a.d[w] = byte(rem + '0') } else if rem != 0 { a.trunc = true } n = quo } // Put down extra digits. for n > 0 { quo := n / 10 rem := n - 10*quo w-- if w < len(a.d) { a.d[w] = byte(rem + '0') } else if rem != 0 { a.trunc = true } n = quo } a.nd += delta if a.nd >= len(a.d) { a.nd = len(a.d) } a.dp += delta trim(a) } // Binary shift left (k > 0) or right (k < 0). func (a *decimal) Shift(k int) { switch { case a.nd == 0: // nothing to do: a == 0 case k > 0: for k > maxShift { leftShift(a, maxShift) k -= maxShift } leftShift(a, uint(k)) case k < 0: for k < -maxShift { rightShift(a, maxShift) k += maxShift } rightShift(a, uint(-k)) } } // If we chop a at nd digits, should we round up? func shouldRoundUp(a *decimal, nd int) bool { if nd < 0 || nd >= a.nd { return false } if a.d[nd] == '5' && nd+1 == a.nd { // exactly halfway - round to even // if we truncated, a little higher than what's recorded - always round up if a.trunc { return true } return nd > 0 && (a.d[nd-1]-'0')%2 != 0 } // not halfway - digit tells all return a.d[nd] >= '5' } // Round a to nd digits (or fewer). // If nd is zero, it means we're rounding // just to the left of the digits, as in // 0.09 -> 0.1. func (a *decimal) Round(nd int) { if nd < 0 || nd >= a.nd { return } if shouldRoundUp(a, nd) { a.RoundUp(nd) } else { a.RoundDown(nd) } } // Round a down to nd digits (or fewer). func (a *decimal) RoundDown(nd int) { if nd < 0 || nd >= a.nd { return } a.nd = nd trim(a) } // Round a up to nd digits (or fewer). func (a *decimal) RoundUp(nd int) { if nd < 0 || nd >= a.nd { return } // round up for i := nd - 1; i >= 0; i-- { c := a.d[i] if c < '9' { // can stop after this digit a.d[i]++ a.nd = i + 1 return } } // Number is all 9s. // Change to single 1 with adjusted decimal point. a.d[0] = '1' a.nd = 1 a.dp++ } // Extract integer part, rounded appropriately. // No guarantees about overflow. func (a *decimal) RoundedInteger() uint64 { if a.dp > 20 { return 0xFFFFFFFFFFFFFFFF } var i int n := uint64(0) for i = 0; i < a.dp && i < a.nd; i++ { n = n*10 + uint64(a.d[i]-'0') } for ; i < a.dp; i++ { n *= 10 } if shouldRoundUp(a, a.dp) { n++ } return n }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/concurrent/go_above_19.go
vendor/github.com/modern-go/concurrent/go_above_19.go
//+build go1.9 package concurrent import "sync" // Map is a wrapper for sync.Map introduced in go1.9 type Map struct { sync.Map } // NewMap creates a thread safe Map func NewMap() *Map { return &Map{} }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/concurrent/go_below_19.go
vendor/github.com/modern-go/concurrent/go_below_19.go
//+build !go1.9 package concurrent import "sync" // Map implements a thread safe map for go version below 1.9 using mutex type Map struct { lock sync.RWMutex data map[interface{}]interface{} } // NewMap creates a thread safe map func NewMap() *Map { return &Map{ data: make(map[interface{}]interface{}, 32), } } // Load is same as sync.Map Load func (m *Map) Load(key interface{}) (elem interface{}, found bool) { m.lock.RLock() elem, found = m.data[key] m.lock.RUnlock() return } // Load is same as sync.Map Store func (m *Map) Store(key interface{}, elem interface{}) { m.lock.Lock() m.data[key] = elem m.lock.Unlock() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/concurrent/log.go
vendor/github.com/modern-go/concurrent/log.go
package concurrent import ( "os" "log" "io/ioutil" ) // ErrorLogger is used to print out error, can be set to writer other than stderr var ErrorLogger = log.New(os.Stderr, "", 0) // InfoLogger is used to print informational message, default to off var InfoLogger = log.New(ioutil.Discard, "", 0)
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/concurrent/unbounded_executor.go
vendor/github.com/modern-go/concurrent/unbounded_executor.go
package concurrent import ( "context" "fmt" "runtime" "runtime/debug" "sync" "time" "reflect" ) // HandlePanic logs goroutine panic by default var HandlePanic = func(recovered interface{}, funcName string) { ErrorLogger.Println(fmt.Sprintf("%s panic: %v", funcName, recovered)) ErrorLogger.Println(string(debug.Stack())) } // UnboundedExecutor is a executor without limits on counts of alive goroutines // it tracks the goroutine started by it, and can cancel them when shutdown type UnboundedExecutor struct { ctx context.Context cancel context.CancelFunc activeGoroutinesMutex *sync.Mutex activeGoroutines map[string]int HandlePanic func(recovered interface{}, funcName string) } // GlobalUnboundedExecutor has the life cycle of the program itself // any goroutine want to be shutdown before main exit can be started from this executor // GlobalUnboundedExecutor expects the main function to call stop // it does not magically knows the main function exits var GlobalUnboundedExecutor = NewUnboundedExecutor() // NewUnboundedExecutor creates a new UnboundedExecutor, // UnboundedExecutor can not be created by &UnboundedExecutor{} // HandlePanic can be set with a callback to override global HandlePanic func NewUnboundedExecutor() *UnboundedExecutor { ctx, cancel := context.WithCancel(context.TODO()) return &UnboundedExecutor{ ctx: ctx, cancel: cancel, activeGoroutinesMutex: &sync.Mutex{}, activeGoroutines: map[string]int{}, } } // Go starts a new goroutine and tracks its lifecycle. // Panic will be recovered and logged automatically, except for StopSignal func (executor *UnboundedExecutor) Go(handler func(ctx context.Context)) { pc := reflect.ValueOf(handler).Pointer() f := runtime.FuncForPC(pc) funcName := f.Name() file, line := f.FileLine(pc) executor.activeGoroutinesMutex.Lock() defer executor.activeGoroutinesMutex.Unlock() startFrom := fmt.Sprintf("%s:%d", file, line) executor.activeGoroutines[startFrom] += 1 go func() { defer func() { recovered := recover() // if you want to quit a goroutine without trigger HandlePanic // use runtime.Goexit() to quit if recovered != nil { if executor.HandlePanic == nil { HandlePanic(recovered, funcName) } else { executor.HandlePanic(recovered, funcName) } } executor.activeGoroutinesMutex.Lock() executor.activeGoroutines[startFrom] -= 1 executor.activeGoroutinesMutex.Unlock() }() handler(executor.ctx) }() } // Stop cancel all goroutines started by this executor without wait func (executor *UnboundedExecutor) Stop() { executor.cancel() } // StopAndWaitForever cancel all goroutines started by this executor and // wait until all goroutines exited func (executor *UnboundedExecutor) StopAndWaitForever() { executor.StopAndWait(context.Background()) } // StopAndWait cancel all goroutines started by this executor and wait. // Wait can be cancelled by the context passed in. func (executor *UnboundedExecutor) StopAndWait(ctx context.Context) { executor.cancel() for { oneHundredMilliseconds := time.NewTimer(time.Millisecond * 100) select { case <-oneHundredMilliseconds.C: if executor.checkNoActiveGoroutines() { return } case <-ctx.Done(): return } } } func (executor *UnboundedExecutor) checkNoActiveGoroutines() bool { executor.activeGoroutinesMutex.Lock() defer executor.activeGoroutinesMutex.Unlock() for startFrom, count := range executor.activeGoroutines { if count > 0 { InfoLogger.Println("UnboundedExecutor is still waiting goroutines to quit", "startFrom", startFrom, "count", count) return false } } return true }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/concurrent/executor.go
vendor/github.com/modern-go/concurrent/executor.go
package concurrent import "context" // Executor replace go keyword to start a new goroutine // the goroutine should cancel itself if the context passed in has been cancelled // the goroutine started by the executor, is owned by the executor // we can cancel all executors owned by the executor just by stop the executor itself // however Executor interface does not Stop method, the one starting and owning executor // should use the concrete type of executor, instead of this interface. type Executor interface { // Go starts a new goroutine controlled by the context Go(handler func(ctx context.Context)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/unsafe_array.go
vendor/github.com/modern-go/reflect2/unsafe_array.go
package reflect2 import ( "reflect" "unsafe" ) type UnsafeArrayType struct { unsafeType elemRType unsafe.Pointer pElemRType unsafe.Pointer elemSize uintptr likePtr bool } func newUnsafeArrayType(cfg *frozenConfig, type1 reflect.Type) *UnsafeArrayType { return &UnsafeArrayType{ unsafeType: *newUnsafeType(cfg, type1), elemRType: unpackEFace(type1.Elem()).data, pElemRType: unpackEFace(reflect.PtrTo(type1.Elem())).data, elemSize: type1.Elem().Size(), likePtr: likePtrType(type1), } } func (type2 *UnsafeArrayType) LikePtr() bool { return type2.likePtr } func (type2 *UnsafeArrayType) Indirect(obj interface{}) interface{} { objEFace := unpackEFace(obj) assertType("Type.Indirect argument 1", type2.ptrRType, objEFace.rtype) return type2.UnsafeIndirect(objEFace.data) } func (type2 *UnsafeArrayType) UnsafeIndirect(ptr unsafe.Pointer) interface{} { if type2.likePtr { return packEFace(type2.rtype, *(*unsafe.Pointer)(ptr)) } return packEFace(type2.rtype, ptr) } func (type2 *UnsafeArrayType) SetIndex(obj interface{}, index int, elem interface{}) { objEFace := unpackEFace(obj) assertType("ArrayType.SetIndex argument 1", type2.ptrRType, objEFace.rtype) elemEFace := unpackEFace(elem) assertType("ArrayType.SetIndex argument 3", type2.pElemRType, elemEFace.rtype) type2.UnsafeSetIndex(objEFace.data, index, elemEFace.data) } func (type2 *UnsafeArrayType) UnsafeSetIndex(obj unsafe.Pointer, index int, elem unsafe.Pointer) { elemPtr := arrayAt(obj, index, type2.elemSize, "i < s.Len") typedmemmove(type2.elemRType, elemPtr, elem) } func (type2 *UnsafeArrayType) GetIndex(obj interface{}, index int) interface{} { objEFace := unpackEFace(obj) assertType("ArrayType.GetIndex argument 1", type2.ptrRType, objEFace.rtype) elemPtr := type2.UnsafeGetIndex(objEFace.data, index) return packEFace(type2.pElemRType, elemPtr) } func (type2 *UnsafeArrayType) UnsafeGetIndex(obj unsafe.Pointer, index int) unsafe.Pointer { return arrayAt(obj, index, type2.elemSize, "i < s.Len") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/safe_field.go
vendor/github.com/modern-go/reflect2/safe_field.go
package reflect2 import ( "reflect" "unsafe" ) type safeField struct { reflect.StructField } func (field *safeField) Offset() uintptr { return field.StructField.Offset } func (field *safeField) Name() string { return field.StructField.Name } func (field *safeField) PkgPath() string { return field.StructField.PkgPath } func (field *safeField) Type() Type { panic("not implemented") } func (field *safeField) Tag() reflect.StructTag { return field.StructField.Tag } func (field *safeField) Index() []int { return field.StructField.Index } func (field *safeField) Anonymous() bool { return field.StructField.Anonymous } func (field *safeField) Set(obj interface{}, value interface{}) { val := reflect.ValueOf(obj).Elem() val.FieldByIndex(field.Index()).Set(reflect.ValueOf(value).Elem()) } func (field *safeField) UnsafeSet(obj unsafe.Pointer, value unsafe.Pointer) { panic("unsafe operation is not supported") } func (field *safeField) Get(obj interface{}) interface{} { val := reflect.ValueOf(obj).Elem().FieldByIndex(field.Index()) ptr := reflect.New(val.Type()) ptr.Elem().Set(val) return ptr.Interface() } func (field *safeField) UnsafeGet(obj unsafe.Pointer) unsafe.Pointer { panic("does not support unsafe operation") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/reflect2.go
vendor/github.com/modern-go/reflect2/reflect2.go
package reflect2 import ( "reflect" "runtime" "sync" "unsafe" ) type Type interface { Kind() reflect.Kind // New return pointer to data of this type New() interface{} // UnsafeNew return the allocated space pointed by unsafe.Pointer UnsafeNew() unsafe.Pointer // PackEFace cast a unsafe pointer to object represented pointer PackEFace(ptr unsafe.Pointer) interface{} // Indirect dereference object represented pointer to this type Indirect(obj interface{}) interface{} // UnsafeIndirect dereference pointer to this type UnsafeIndirect(ptr unsafe.Pointer) interface{} // Type1 returns reflect.Type Type1() reflect.Type Implements(thatType Type) bool String() string RType() uintptr // interface{} of this type has pointer like behavior LikePtr() bool IsNullable() bool IsNil(obj interface{}) bool UnsafeIsNil(ptr unsafe.Pointer) bool Set(obj interface{}, val interface{}) UnsafeSet(ptr unsafe.Pointer, val unsafe.Pointer) AssignableTo(anotherType Type) bool } type ListType interface { Type Elem() Type SetIndex(obj interface{}, index int, elem interface{}) UnsafeSetIndex(obj unsafe.Pointer, index int, elem unsafe.Pointer) GetIndex(obj interface{}, index int) interface{} UnsafeGetIndex(obj unsafe.Pointer, index int) unsafe.Pointer } type ArrayType interface { ListType Len() int } type SliceType interface { ListType MakeSlice(length int, cap int) interface{} UnsafeMakeSlice(length int, cap int) unsafe.Pointer Grow(obj interface{}, newLength int) UnsafeGrow(ptr unsafe.Pointer, newLength int) Append(obj interface{}, elem interface{}) UnsafeAppend(obj unsafe.Pointer, elem unsafe.Pointer) LengthOf(obj interface{}) int UnsafeLengthOf(ptr unsafe.Pointer) int SetNil(obj interface{}) UnsafeSetNil(ptr unsafe.Pointer) Cap(obj interface{}) int UnsafeCap(ptr unsafe.Pointer) int } type StructType interface { Type NumField() int Field(i int) StructField FieldByName(name string) StructField FieldByIndex(index []int) StructField FieldByNameFunc(match func(string) bool) StructField } type StructField interface { Offset() uintptr Name() string PkgPath() string Type() Type Tag() reflect.StructTag Index() []int Anonymous() bool Set(obj interface{}, value interface{}) UnsafeSet(obj unsafe.Pointer, value unsafe.Pointer) Get(obj interface{}) interface{} UnsafeGet(obj unsafe.Pointer) unsafe.Pointer } type MapType interface { Type Key() Type Elem() Type MakeMap(cap int) interface{} UnsafeMakeMap(cap int) unsafe.Pointer SetIndex(obj interface{}, key interface{}, elem interface{}) UnsafeSetIndex(obj unsafe.Pointer, key unsafe.Pointer, elem unsafe.Pointer) TryGetIndex(obj interface{}, key interface{}) (interface{}, bool) GetIndex(obj interface{}, key interface{}) interface{} UnsafeGetIndex(obj unsafe.Pointer, key unsafe.Pointer) unsafe.Pointer Iterate(obj interface{}) MapIterator UnsafeIterate(obj unsafe.Pointer) MapIterator } type MapIterator interface { HasNext() bool Next() (key interface{}, elem interface{}) UnsafeNext() (key unsafe.Pointer, elem unsafe.Pointer) } type PtrType interface { Type Elem() Type } type InterfaceType interface { NumMethod() int } type Config struct { UseSafeImplementation bool } type API interface { TypeOf(obj interface{}) Type Type2(type1 reflect.Type) Type } var ConfigUnsafe = Config{UseSafeImplementation: false}.Froze() var ConfigSafe = Config{UseSafeImplementation: true}.Froze() type frozenConfig struct { useSafeImplementation bool cache *sync.Map } func (cfg Config) Froze() *frozenConfig { return &frozenConfig{ useSafeImplementation: cfg.UseSafeImplementation, cache: new(sync.Map), } } func (cfg *frozenConfig) TypeOf(obj interface{}) Type { cacheKey := uintptr(unpackEFace(obj).rtype) typeObj, found := cfg.cache.Load(cacheKey) if found { return typeObj.(Type) } return cfg.Type2(reflect.TypeOf(obj)) } func (cfg *frozenConfig) Type2(type1 reflect.Type) Type { if type1 == nil { return nil } cacheKey := uintptr(unpackEFace(type1).data) typeObj, found := cfg.cache.Load(cacheKey) if found { return typeObj.(Type) } type2 := cfg.wrapType(type1) cfg.cache.Store(cacheKey, type2) return type2 } func (cfg *frozenConfig) wrapType(type1 reflect.Type) Type { safeType := safeType{Type: type1, cfg: cfg} switch type1.Kind() { case reflect.Struct: if cfg.useSafeImplementation { return &safeStructType{safeType} } return newUnsafeStructType(cfg, type1) case reflect.Array: if cfg.useSafeImplementation { return &safeSliceType{safeType} } return newUnsafeArrayType(cfg, type1) case reflect.Slice: if cfg.useSafeImplementation { return &safeSliceType{safeType} } return newUnsafeSliceType(cfg, type1) case reflect.Map: if cfg.useSafeImplementation { return &safeMapType{safeType} } return newUnsafeMapType(cfg, type1) case reflect.Ptr, reflect.Chan, reflect.Func: if cfg.useSafeImplementation { return &safeMapType{safeType} } return newUnsafePtrType(cfg, type1) case reflect.Interface: if cfg.useSafeImplementation { return &safeMapType{safeType} } if type1.NumMethod() == 0 { return newUnsafeEFaceType(cfg, type1) } return newUnsafeIFaceType(cfg, type1) default: if cfg.useSafeImplementation { return &safeType } return newUnsafeType(cfg, type1) } } func TypeOf(obj interface{}) Type { return ConfigUnsafe.TypeOf(obj) } func TypeOfPtr(obj interface{}) PtrType { return TypeOf(obj).(PtrType) } func Type2(type1 reflect.Type) Type { if type1 == nil { return nil } return ConfigUnsafe.Type2(type1) } func PtrTo(typ Type) Type { return Type2(reflect.PtrTo(typ.Type1())) } func PtrOf(obj interface{}) unsafe.Pointer { return unpackEFace(obj).data } func RTypeOf(obj interface{}) uintptr { return uintptr(unpackEFace(obj).rtype) } func IsNil(obj interface{}) bool { if obj == nil { return true } return unpackEFace(obj).data == nil } func IsNullable(kind reflect.Kind) bool { switch kind { case reflect.Ptr, reflect.Map, reflect.Chan, reflect.Func, reflect.Slice, reflect.Interface: return true } return false } func likePtrKind(kind reflect.Kind) bool { switch kind { case reflect.Ptr, reflect.Map, reflect.Chan, reflect.Func: return true } return false } func likePtrType(typ reflect.Type) bool { if likePtrKind(typ.Kind()) { return true } if typ.Kind() == reflect.Struct { if typ.NumField() != 1 { return false } return likePtrType(typ.Field(0).Type) } if typ.Kind() == reflect.Array { if typ.Len() != 1 { return false } return likePtrType(typ.Elem()) } return false } // NoEscape hides a pointer from escape analysis. noescape is // the identity function but escape analysis doesn't think the // output depends on the input. noescape is inlined and currently // compiles down to zero instructions. // USE CAREFULLY! //go:nosplit func NoEscape(p unsafe.Pointer) unsafe.Pointer { x := uintptr(p) return unsafe.Pointer(x ^ 0) } func UnsafeCastString(str string) []byte { bytes := make([]byte, 0) stringHeader := (*reflect.StringHeader)(unsafe.Pointer(&str)) sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&bytes)) sliceHeader.Data = stringHeader.Data sliceHeader.Cap = stringHeader.Len sliceHeader.Len = stringHeader.Len runtime.KeepAlive(str) return bytes }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/safe_type.go
vendor/github.com/modern-go/reflect2/safe_type.go
package reflect2 import ( "reflect" "unsafe" ) type safeType struct { reflect.Type cfg *frozenConfig } func (type2 *safeType) New() interface{} { return reflect.New(type2.Type).Interface() } func (type2 *safeType) UnsafeNew() unsafe.Pointer { panic("does not support unsafe operation") } func (type2 *safeType) Elem() Type { return type2.cfg.Type2(type2.Type.Elem()) } func (type2 *safeType) Type1() reflect.Type { return type2.Type } func (type2 *safeType) PackEFace(ptr unsafe.Pointer) interface{} { panic("does not support unsafe operation") } func (type2 *safeType) Implements(thatType Type) bool { return type2.Type.Implements(thatType.Type1()) } func (type2 *safeType) RType() uintptr { panic("does not support unsafe operation") } func (type2 *safeType) Indirect(obj interface{}) interface{} { return reflect.Indirect(reflect.ValueOf(obj)).Interface() } func (type2 *safeType) UnsafeIndirect(ptr unsafe.Pointer) interface{} { panic("does not support unsafe operation") } func (type2 *safeType) LikePtr() bool { panic("does not support unsafe operation") } func (type2 *safeType) IsNullable() bool { return IsNullable(type2.Kind()) } func (type2 *safeType) IsNil(obj interface{}) bool { if obj == nil { return true } return reflect.ValueOf(obj).Elem().IsNil() } func (type2 *safeType) UnsafeIsNil(ptr unsafe.Pointer) bool { panic("does not support unsafe operation") } func (type2 *safeType) Set(obj interface{}, val interface{}) { reflect.ValueOf(obj).Elem().Set(reflect.ValueOf(val).Elem()) } func (type2 *safeType) UnsafeSet(ptr unsafe.Pointer, val unsafe.Pointer) { panic("does not support unsafe operation") } func (type2 *safeType) AssignableTo(anotherType Type) bool { return type2.Type1().AssignableTo(anotherType.Type1()) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/unsafe_slice.go
vendor/github.com/modern-go/reflect2/unsafe_slice.go
package reflect2 import ( "reflect" "unsafe" ) // sliceHeader is a safe version of SliceHeader used within this package. type sliceHeader struct { Data unsafe.Pointer Len int Cap int } type UnsafeSliceType struct { unsafeType elemRType unsafe.Pointer pElemRType unsafe.Pointer elemSize uintptr } func newUnsafeSliceType(cfg *frozenConfig, type1 reflect.Type) SliceType { elemType := type1.Elem() return &UnsafeSliceType{ unsafeType: *newUnsafeType(cfg, type1), pElemRType: unpackEFace(reflect.PtrTo(elemType)).data, elemRType: unpackEFace(elemType).data, elemSize: elemType.Size(), } } func (type2 *UnsafeSliceType) Set(obj interface{}, val interface{}) { objEFace := unpackEFace(obj) assertType("Type.Set argument 1", type2.ptrRType, objEFace.rtype) valEFace := unpackEFace(val) assertType("Type.Set argument 2", type2.ptrRType, valEFace.rtype) type2.UnsafeSet(objEFace.data, valEFace.data) } func (type2 *UnsafeSliceType) UnsafeSet(ptr unsafe.Pointer, val unsafe.Pointer) { *(*sliceHeader)(ptr) = *(*sliceHeader)(val) } func (type2 *UnsafeSliceType) IsNil(obj interface{}) bool { if obj == nil { return true } objEFace := unpackEFace(obj) assertType("Type.IsNil argument 1", type2.ptrRType, objEFace.rtype) return type2.UnsafeIsNil(objEFace.data) } func (type2 *UnsafeSliceType) UnsafeIsNil(ptr unsafe.Pointer) bool { if ptr == nil { return true } return (*sliceHeader)(ptr).Data == nil } func (type2 *UnsafeSliceType) SetNil(obj interface{}) { objEFace := unpackEFace(obj) assertType("SliceType.SetNil argument 1", type2.ptrRType, objEFace.rtype) type2.UnsafeSetNil(objEFace.data) } func (type2 *UnsafeSliceType) UnsafeSetNil(ptr unsafe.Pointer) { header := (*sliceHeader)(ptr) header.Len = 0 header.Cap = 0 header.Data = nil } func (type2 *UnsafeSliceType) MakeSlice(length int, cap int) interface{} { return packEFace(type2.ptrRType, type2.UnsafeMakeSlice(length, cap)) } func (type2 *UnsafeSliceType) UnsafeMakeSlice(length int, cap int) unsafe.Pointer { header := &sliceHeader{unsafe_NewArray(type2.elemRType, cap), length, cap} return unsafe.Pointer(header) } func (type2 *UnsafeSliceType) LengthOf(obj interface{}) int { objEFace := unpackEFace(obj) assertType("SliceType.Len argument 1", type2.ptrRType, objEFace.rtype) return type2.UnsafeLengthOf(objEFace.data) } func (type2 *UnsafeSliceType) UnsafeLengthOf(obj unsafe.Pointer) int { header := (*sliceHeader)(obj) return header.Len } func (type2 *UnsafeSliceType) SetIndex(obj interface{}, index int, elem interface{}) { objEFace := unpackEFace(obj) assertType("SliceType.SetIndex argument 1", type2.ptrRType, objEFace.rtype) elemEFace := unpackEFace(elem) assertType("SliceType.SetIndex argument 3", type2.pElemRType, elemEFace.rtype) type2.UnsafeSetIndex(objEFace.data, index, elemEFace.data) } func (type2 *UnsafeSliceType) UnsafeSetIndex(obj unsafe.Pointer, index int, elem unsafe.Pointer) { header := (*sliceHeader)(obj) elemPtr := arrayAt(header.Data, index, type2.elemSize, "i < s.Len") typedmemmove(type2.elemRType, elemPtr, elem) } func (type2 *UnsafeSliceType) GetIndex(obj interface{}, index int) interface{} { objEFace := unpackEFace(obj) assertType("SliceType.GetIndex argument 1", type2.ptrRType, objEFace.rtype) elemPtr := type2.UnsafeGetIndex(objEFace.data, index) return packEFace(type2.pElemRType, elemPtr) } func (type2 *UnsafeSliceType) UnsafeGetIndex(obj unsafe.Pointer, index int) unsafe.Pointer { header := (*sliceHeader)(obj) return arrayAt(header.Data, index, type2.elemSize, "i < s.Len") } func (type2 *UnsafeSliceType) Append(obj interface{}, elem interface{}) { objEFace := unpackEFace(obj) assertType("SliceType.Append argument 1", type2.ptrRType, objEFace.rtype) elemEFace := unpackEFace(elem) assertType("SliceType.Append argument 2", type2.pElemRType, elemEFace.rtype) type2.UnsafeAppend(objEFace.data, elemEFace.data) } func (type2 *UnsafeSliceType) UnsafeAppend(obj unsafe.Pointer, elem unsafe.Pointer) { header := (*sliceHeader)(obj) oldLen := header.Len type2.UnsafeGrow(obj, oldLen+1) type2.UnsafeSetIndex(obj, oldLen, elem) } func (type2 *UnsafeSliceType) Cap(obj interface{}) int { objEFace := unpackEFace(obj) assertType("SliceType.Cap argument 1", type2.ptrRType, objEFace.rtype) return type2.UnsafeCap(objEFace.data) } func (type2 *UnsafeSliceType) UnsafeCap(ptr unsafe.Pointer) int { return (*sliceHeader)(ptr).Cap } func (type2 *UnsafeSliceType) Grow(obj interface{}, newLength int) { objEFace := unpackEFace(obj) assertType("SliceType.Grow argument 1", type2.ptrRType, objEFace.rtype) type2.UnsafeGrow(objEFace.data, newLength) } func (type2 *UnsafeSliceType) UnsafeGrow(obj unsafe.Pointer, newLength int) { header := (*sliceHeader)(obj) if newLength <= header.Cap { header.Len = newLength return } newCap := calcNewCap(header.Cap, newLength) newHeader := (*sliceHeader)(type2.UnsafeMakeSlice(header.Len, newCap)) typedslicecopy(type2.elemRType, *newHeader, *header) header.Data = newHeader.Data header.Cap = newHeader.Cap header.Len = newLength } func calcNewCap(cap int, expectedCap int) int { if cap == 0 { cap = expectedCap } else { for cap < expectedCap { if cap < 1024 { cap += cap } else { cap += cap / 4 } } } return cap }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/unsafe_link.go
vendor/github.com/modern-go/reflect2/unsafe_link.go
package reflect2 import "unsafe" //go:linkname unsafe_New reflect.unsafe_New func unsafe_New(rtype unsafe.Pointer) unsafe.Pointer //go:linkname typedmemmove reflect.typedmemmove func typedmemmove(rtype unsafe.Pointer, dst, src unsafe.Pointer) //go:linkname unsafe_NewArray reflect.unsafe_NewArray func unsafe_NewArray(rtype unsafe.Pointer, length int) unsafe.Pointer // typedslicecopy copies a slice of elemType values from src to dst, // returning the number of elements copied. //go:linkname typedslicecopy reflect.typedslicecopy //go:noescape func typedslicecopy(elemType unsafe.Pointer, dst, src sliceHeader) int //go:linkname mapassign reflect.mapassign //go:noescape func mapassign(rtype unsafe.Pointer, m unsafe.Pointer, key unsafe.Pointer, val unsafe.Pointer) //go:linkname mapaccess reflect.mapaccess //go:noescape func mapaccess(rtype unsafe.Pointer, m unsafe.Pointer, key unsafe.Pointer) (val unsafe.Pointer) //go:noescape //go:linkname mapiternext reflect.mapiternext func mapiternext(it *hiter) //go:linkname ifaceE2I reflect.ifaceE2I func ifaceE2I(rtype unsafe.Pointer, src interface{}, dst unsafe.Pointer) // A hash iteration structure. // If you modify hiter, also change cmd/internal/gc/reflect.go to indicate // the layout of this structure. type hiter struct { key unsafe.Pointer value unsafe.Pointer t unsafe.Pointer h unsafe.Pointer buckets unsafe.Pointer bptr unsafe.Pointer overflow *[]unsafe.Pointer oldoverflow *[]unsafe.Pointer startBucket uintptr offset uint8 wrapped bool B uint8 i uint8 bucket uintptr checkBucket uintptr } // add returns p+x. // // The whySafe string is ignored, so that the function still inlines // as efficiently as p+x, but all call sites should use the string to // record why the addition is safe, which is to say why the addition // does not cause x to advance to the very end of p's allocation // and therefore point incorrectly at the next block in memory. func add(p unsafe.Pointer, x uintptr, whySafe string) unsafe.Pointer { return unsafe.Pointer(uintptr(p) + x) } // arrayAt returns the i-th element of p, // an array whose elements are eltSize bytes wide. // The array pointed at by p must have at least i+1 elements: // it is invalid (but impossible to check here) to pass i >= len, // because then the result will point outside the array. // whySafe must explain why i < len. (Passing "i < len" is fine; // the benefit is to surface this assumption at the call site.) func arrayAt(p unsafe.Pointer, i int, eltSize uintptr, whySafe string) unsafe.Pointer { return add(p, uintptr(i)*eltSize, "i < len") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/go_above_19.go
vendor/github.com/modern-go/reflect2/go_above_19.go
//+build go1.9 package reflect2 import ( "unsafe" ) //go:linkname resolveTypeOff reflect.resolveTypeOff func resolveTypeOff(rtype unsafe.Pointer, off int32) unsafe.Pointer //go:linkname makemap reflect.makemap func makemap(rtype unsafe.Pointer, cap int) (m unsafe.Pointer) func makeMapWithSize(rtype unsafe.Pointer, cap int) unsafe.Pointer { return makemap(rtype, cap) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/unsafe_eface.go
vendor/github.com/modern-go/reflect2/unsafe_eface.go
package reflect2 import ( "reflect" "unsafe" ) type eface struct { rtype unsafe.Pointer data unsafe.Pointer } func unpackEFace(obj interface{}) *eface { return (*eface)(unsafe.Pointer(&obj)) } func packEFace(rtype unsafe.Pointer, data unsafe.Pointer) interface{} { var i interface{} e := (*eface)(unsafe.Pointer(&i)) e.rtype = rtype e.data = data return i } type UnsafeEFaceType struct { unsafeType } func newUnsafeEFaceType(cfg *frozenConfig, type1 reflect.Type) *UnsafeEFaceType { return &UnsafeEFaceType{ unsafeType: *newUnsafeType(cfg, type1), } } func (type2 *UnsafeEFaceType) IsNil(obj interface{}) bool { if obj == nil { return true } objEFace := unpackEFace(obj) assertType("Type.IsNil argument 1", type2.ptrRType, objEFace.rtype) return type2.UnsafeIsNil(objEFace.data) } func (type2 *UnsafeEFaceType) UnsafeIsNil(ptr unsafe.Pointer) bool { if ptr == nil { return true } return unpackEFace(*(*interface{})(ptr)).data == nil } func (type2 *UnsafeEFaceType) Indirect(obj interface{}) interface{} { objEFace := unpackEFace(obj) assertType("Type.Indirect argument 1", type2.ptrRType, objEFace.rtype) return type2.UnsafeIndirect(objEFace.data) } func (type2 *UnsafeEFaceType) UnsafeIndirect(ptr unsafe.Pointer) interface{} { return *(*interface{})(ptr) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/safe_map.go
vendor/github.com/modern-go/reflect2/safe_map.go
package reflect2 import ( "reflect" "unsafe" ) type safeMapType struct { safeType } func (type2 *safeMapType) Key() Type { return type2.safeType.cfg.Type2(type2.Type.Key()) } func (type2 *safeMapType) MakeMap(cap int) interface{} { ptr := reflect.New(type2.Type) ptr.Elem().Set(reflect.MakeMap(type2.Type)) return ptr.Interface() } func (type2 *safeMapType) UnsafeMakeMap(cap int) unsafe.Pointer { panic("does not support unsafe operation") } func (type2 *safeMapType) SetIndex(obj interface{}, key interface{}, elem interface{}) { keyVal := reflect.ValueOf(key) elemVal := reflect.ValueOf(elem) val := reflect.ValueOf(obj) val.Elem().SetMapIndex(keyVal.Elem(), elemVal.Elem()) } func (type2 *safeMapType) UnsafeSetIndex(obj unsafe.Pointer, key unsafe.Pointer, elem unsafe.Pointer) { panic("does not support unsafe operation") } func (type2 *safeMapType) TryGetIndex(obj interface{}, key interface{}) (interface{}, bool) { keyVal := reflect.ValueOf(key) if key == nil { keyVal = reflect.New(type2.Type.Key()).Elem() } val := reflect.ValueOf(obj).MapIndex(keyVal) if !val.IsValid() { return nil, false } return val.Interface(), true } func (type2 *safeMapType) GetIndex(obj interface{}, key interface{}) interface{} { val := reflect.ValueOf(obj).Elem() keyVal := reflect.ValueOf(key).Elem() elemVal := val.MapIndex(keyVal) if !elemVal.IsValid() { ptr := reflect.New(reflect.PtrTo(val.Type().Elem())) return ptr.Elem().Interface() } ptr := reflect.New(elemVal.Type()) ptr.Elem().Set(elemVal) return ptr.Interface() } func (type2 *safeMapType) UnsafeGetIndex(obj unsafe.Pointer, key unsafe.Pointer) unsafe.Pointer { panic("does not support unsafe operation") } func (type2 *safeMapType) Iterate(obj interface{}) MapIterator { m := reflect.ValueOf(obj).Elem() return &safeMapIterator{ m: m, keys: m.MapKeys(), } } func (type2 *safeMapType) UnsafeIterate(obj unsafe.Pointer) MapIterator { panic("does not support unsafe operation") } type safeMapIterator struct { i int m reflect.Value keys []reflect.Value } func (iter *safeMapIterator) HasNext() bool { return iter.i != len(iter.keys) } func (iter *safeMapIterator) Next() (interface{}, interface{}) { key := iter.keys[iter.i] elem := iter.m.MapIndex(key) iter.i += 1 keyPtr := reflect.New(key.Type()) keyPtr.Elem().Set(key) elemPtr := reflect.New(elem.Type()) elemPtr.Elem().Set(elem) return keyPtr.Interface(), elemPtr.Interface() } func (iter *safeMapIterator) UnsafeNext() (unsafe.Pointer, unsafe.Pointer) { panic("does not support unsafe operation") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/reflect2_kind.go
vendor/github.com/modern-go/reflect2/reflect2_kind.go
package reflect2 import ( "reflect" "unsafe" ) // DefaultTypeOfKind return the non aliased default type for the kind func DefaultTypeOfKind(kind reflect.Kind) Type { return kindTypes[kind] } var kindTypes = map[reflect.Kind]Type{ reflect.Bool: TypeOf(true), reflect.Uint8: TypeOf(uint8(0)), reflect.Int8: TypeOf(int8(0)), reflect.Uint16: TypeOf(uint16(0)), reflect.Int16: TypeOf(int16(0)), reflect.Uint32: TypeOf(uint32(0)), reflect.Int32: TypeOf(int32(0)), reflect.Uint64: TypeOf(uint64(0)), reflect.Int64: TypeOf(int64(0)), reflect.Uint: TypeOf(uint(0)), reflect.Int: TypeOf(int(0)), reflect.Float32: TypeOf(float32(0)), reflect.Float64: TypeOf(float64(0)), reflect.Uintptr: TypeOf(uintptr(0)), reflect.String: TypeOf(""), reflect.UnsafePointer: TypeOf(unsafe.Pointer(nil)), }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/safe_slice.go
vendor/github.com/modern-go/reflect2/safe_slice.go
package reflect2 import ( "reflect" "unsafe" ) type safeSliceType struct { safeType } func (type2 *safeSliceType) SetIndex(obj interface{}, index int, value interface{}) { val := reflect.ValueOf(obj).Elem() elem := reflect.ValueOf(value).Elem() val.Index(index).Set(elem) } func (type2 *safeSliceType) UnsafeSetIndex(obj unsafe.Pointer, index int, value unsafe.Pointer) { panic("does not support unsafe operation") } func (type2 *safeSliceType) GetIndex(obj interface{}, index int) interface{} { val := reflect.ValueOf(obj).Elem() elem := val.Index(index) ptr := reflect.New(elem.Type()) ptr.Elem().Set(elem) return ptr.Interface() } func (type2 *safeSliceType) UnsafeGetIndex(obj unsafe.Pointer, index int) unsafe.Pointer { panic("does not support unsafe operation") } func (type2 *safeSliceType) MakeSlice(length int, cap int) interface{} { val := reflect.MakeSlice(type2.Type, length, cap) ptr := reflect.New(val.Type()) ptr.Elem().Set(val) return ptr.Interface() } func (type2 *safeSliceType) UnsafeMakeSlice(length int, cap int) unsafe.Pointer { panic("does not support unsafe operation") } func (type2 *safeSliceType) Grow(obj interface{}, newLength int) { oldCap := type2.Cap(obj) oldSlice := reflect.ValueOf(obj).Elem() delta := newLength - oldCap deltaVals := make([]reflect.Value, delta) newSlice := reflect.Append(oldSlice, deltaVals...) oldSlice.Set(newSlice) } func (type2 *safeSliceType) UnsafeGrow(ptr unsafe.Pointer, newLength int) { panic("does not support unsafe operation") } func (type2 *safeSliceType) Append(obj interface{}, elem interface{}) { val := reflect.ValueOf(obj).Elem() elemVal := reflect.ValueOf(elem).Elem() newVal := reflect.Append(val, elemVal) val.Set(newVal) } func (type2 *safeSliceType) UnsafeAppend(obj unsafe.Pointer, elem unsafe.Pointer) { panic("does not support unsafe operation") } func (type2 *safeSliceType) SetNil(obj interface{}) { val := reflect.ValueOf(obj).Elem() val.Set(reflect.Zero(val.Type())) } func (type2 *safeSliceType) UnsafeSetNil(ptr unsafe.Pointer) { panic("does not support unsafe operation") } func (type2 *safeSliceType) LengthOf(obj interface{}) int { return reflect.ValueOf(obj).Elem().Len() } func (type2 *safeSliceType) UnsafeLengthOf(ptr unsafe.Pointer) int { panic("does not support unsafe operation") } func (type2 *safeSliceType) Cap(obj interface{}) int { return reflect.ValueOf(obj).Elem().Cap() } func (type2 *safeSliceType) UnsafeCap(ptr unsafe.Pointer) int { panic("does not support unsafe operation") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/go_above_118.go
vendor/github.com/modern-go/reflect2/go_above_118.go
//+build go1.18 package reflect2 import ( "unsafe" ) // m escapes into the return value, but the caller of mapiterinit // doesn't let the return value escape. //go:noescape //go:linkname mapiterinit reflect.mapiterinit func mapiterinit(rtype unsafe.Pointer, m unsafe.Pointer, it *hiter) func (type2 *UnsafeMapType) UnsafeIterate(obj unsafe.Pointer) MapIterator { var it hiter mapiterinit(type2.rtype, *(*unsafe.Pointer)(obj), &it) return &UnsafeMapIterator{ hiter: &it, pKeyRType: type2.pKeyRType, pElemRType: type2.pElemRType, } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/unsafe_struct.go
vendor/github.com/modern-go/reflect2/unsafe_struct.go
package reflect2 import ( "reflect" "unsafe" ) type UnsafeStructType struct { unsafeType likePtr bool } func newUnsafeStructType(cfg *frozenConfig, type1 reflect.Type) *UnsafeStructType { return &UnsafeStructType{ unsafeType: *newUnsafeType(cfg, type1), likePtr: likePtrType(type1), } } func (type2 *UnsafeStructType) LikePtr() bool { return type2.likePtr } func (type2 *UnsafeStructType) Indirect(obj interface{}) interface{} { objEFace := unpackEFace(obj) assertType("Type.Indirect argument 1", type2.ptrRType, objEFace.rtype) return type2.UnsafeIndirect(objEFace.data) } func (type2 *UnsafeStructType) UnsafeIndirect(ptr unsafe.Pointer) interface{} { if type2.likePtr { return packEFace(type2.rtype, *(*unsafe.Pointer)(ptr)) } return packEFace(type2.rtype, ptr) } func (type2 *UnsafeStructType) FieldByName(name string) StructField { structField, found := type2.Type.FieldByName(name) if !found { return nil } return newUnsafeStructField(type2, structField) } func (type2 *UnsafeStructType) Field(i int) StructField { return newUnsafeStructField(type2, type2.Type.Field(i)) } func (type2 *UnsafeStructType) FieldByIndex(index []int) StructField { return newUnsafeStructField(type2, type2.Type.FieldByIndex(index)) } func (type2 *UnsafeStructType) FieldByNameFunc(match func(string) bool) StructField { structField, found := type2.Type.FieldByNameFunc(match) if !found { panic("field match condition not found in " + type2.Type.String()) } return newUnsafeStructField(type2, structField) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/unsafe_ptr.go
vendor/github.com/modern-go/reflect2/unsafe_ptr.go
package reflect2 import ( "reflect" "unsafe" ) type UnsafePtrType struct { unsafeType } func newUnsafePtrType(cfg *frozenConfig, type1 reflect.Type) *UnsafePtrType { return &UnsafePtrType{ unsafeType: *newUnsafeType(cfg, type1), } } func (type2 *UnsafePtrType) IsNil(obj interface{}) bool { if obj == nil { return true } objEFace := unpackEFace(obj) assertType("Type.IsNil argument 1", type2.ptrRType, objEFace.rtype) return type2.UnsafeIsNil(objEFace.data) } func (type2 *UnsafePtrType) UnsafeIsNil(ptr unsafe.Pointer) bool { if ptr == nil { return true } return *(*unsafe.Pointer)(ptr) == nil } func (type2 *UnsafePtrType) LikePtr() bool { return true } func (type2 *UnsafePtrType) Indirect(obj interface{}) interface{} { objEFace := unpackEFace(obj) assertType("Type.Indirect argument 1", type2.ptrRType, objEFace.rtype) return type2.UnsafeIndirect(objEFace.data) } func (type2 *UnsafePtrType) UnsafeIndirect(ptr unsafe.Pointer) interface{} { return packEFace(type2.rtype, *(*unsafe.Pointer)(ptr)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/type_map.go
vendor/github.com/modern-go/reflect2/type_map.go
// +build !gccgo package reflect2 import ( "reflect" "sync" "unsafe" ) // typelinks2 for 1.7 ~ //go:linkname typelinks2 reflect.typelinks func typelinks2() (sections []unsafe.Pointer, offset [][]int32) // initOnce guards initialization of types and packages var initOnce sync.Once var types map[string]reflect.Type var packages map[string]map[string]reflect.Type // discoverTypes initializes types and packages func discoverTypes() { types = make(map[string]reflect.Type) packages = make(map[string]map[string]reflect.Type) loadGoTypes() } func loadGoTypes() { var obj interface{} = reflect.TypeOf(0) sections, offset := typelinks2() for i, offs := range offset { rodata := sections[i] for _, off := range offs { (*emptyInterface)(unsafe.Pointer(&obj)).word = resolveTypeOff(unsafe.Pointer(rodata), off) typ := obj.(reflect.Type) if typ.Kind() == reflect.Ptr && typ.Elem().Kind() == reflect.Struct { loadedType := typ.Elem() pkgTypes := packages[loadedType.PkgPath()] if pkgTypes == nil { pkgTypes = map[string]reflect.Type{} packages[loadedType.PkgPath()] = pkgTypes } types[loadedType.String()] = loadedType pkgTypes[loadedType.Name()] = loadedType } } } } type emptyInterface struct { typ unsafe.Pointer word unsafe.Pointer } // TypeByName return the type by its name, just like Class.forName in java func TypeByName(typeName string) Type { initOnce.Do(discoverTypes) return Type2(types[typeName]) } // TypeByPackageName return the type by its package and name func TypeByPackageName(pkgPath string, name string) Type { initOnce.Do(discoverTypes) pkgTypes := packages[pkgPath] if pkgTypes == nil { return nil } return Type2(pkgTypes[name]) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/safe_struct.go
vendor/github.com/modern-go/reflect2/safe_struct.go
package reflect2 type safeStructType struct { safeType } func (type2 *safeStructType) FieldByName(name string) StructField { field, found := type2.Type.FieldByName(name) if !found { panic("field " + name + " not found") } return &safeField{StructField: field} } func (type2 *safeStructType) Field(i int) StructField { return &safeField{StructField: type2.Type.Field(i)} } func (type2 *safeStructType) FieldByIndex(index []int) StructField { return &safeField{StructField: type2.Type.FieldByIndex(index)} } func (type2 *safeStructType) FieldByNameFunc(match func(string) bool) StructField { field, found := type2.Type.FieldByNameFunc(match) if !found { panic("field match condition not found in " + type2.Type.String()) } return &safeField{StructField: field} }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/unsafe_map.go
vendor/github.com/modern-go/reflect2/unsafe_map.go
package reflect2 import ( "reflect" "unsafe" ) type UnsafeMapType struct { unsafeType pKeyRType unsafe.Pointer pElemRType unsafe.Pointer } func newUnsafeMapType(cfg *frozenConfig, type1 reflect.Type) MapType { return &UnsafeMapType{ unsafeType: *newUnsafeType(cfg, type1), pKeyRType: unpackEFace(reflect.PtrTo(type1.Key())).data, pElemRType: unpackEFace(reflect.PtrTo(type1.Elem())).data, } } func (type2 *UnsafeMapType) IsNil(obj interface{}) bool { if obj == nil { return true } objEFace := unpackEFace(obj) assertType("Type.IsNil argument 1", type2.ptrRType, objEFace.rtype) return type2.UnsafeIsNil(objEFace.data) } func (type2 *UnsafeMapType) UnsafeIsNil(ptr unsafe.Pointer) bool { if ptr == nil { return true } return *(*unsafe.Pointer)(ptr) == nil } func (type2 *UnsafeMapType) LikePtr() bool { return true } func (type2 *UnsafeMapType) Indirect(obj interface{}) interface{} { objEFace := unpackEFace(obj) assertType("MapType.Indirect argument 1", type2.ptrRType, objEFace.rtype) return type2.UnsafeIndirect(objEFace.data) } func (type2 *UnsafeMapType) UnsafeIndirect(ptr unsafe.Pointer) interface{} { return packEFace(type2.rtype, *(*unsafe.Pointer)(ptr)) } func (type2 *UnsafeMapType) Key() Type { return type2.cfg.Type2(type2.Type.Key()) } func (type2 *UnsafeMapType) MakeMap(cap int) interface{} { return packEFace(type2.ptrRType, type2.UnsafeMakeMap(cap)) } func (type2 *UnsafeMapType) UnsafeMakeMap(cap int) unsafe.Pointer { m := makeMapWithSize(type2.rtype, cap) return unsafe.Pointer(&m) } func (type2 *UnsafeMapType) SetIndex(obj interface{}, key interface{}, elem interface{}) { objEFace := unpackEFace(obj) assertType("MapType.SetIndex argument 1", type2.ptrRType, objEFace.rtype) keyEFace := unpackEFace(key) assertType("MapType.SetIndex argument 2", type2.pKeyRType, keyEFace.rtype) elemEFace := unpackEFace(elem) assertType("MapType.SetIndex argument 3", type2.pElemRType, elemEFace.rtype) type2.UnsafeSetIndex(objEFace.data, keyEFace.data, elemEFace.data) } func (type2 *UnsafeMapType) UnsafeSetIndex(obj unsafe.Pointer, key unsafe.Pointer, elem unsafe.Pointer) { mapassign(type2.rtype, *(*unsafe.Pointer)(obj), key, elem) } func (type2 *UnsafeMapType) TryGetIndex(obj interface{}, key interface{}) (interface{}, bool) { objEFace := unpackEFace(obj) assertType("MapType.TryGetIndex argument 1", type2.ptrRType, objEFace.rtype) keyEFace := unpackEFace(key) assertType("MapType.TryGetIndex argument 2", type2.pKeyRType, keyEFace.rtype) elemPtr := type2.UnsafeGetIndex(objEFace.data, keyEFace.data) if elemPtr == nil { return nil, false } return packEFace(type2.pElemRType, elemPtr), true } func (type2 *UnsafeMapType) GetIndex(obj interface{}, key interface{}) interface{} { objEFace := unpackEFace(obj) assertType("MapType.GetIndex argument 1", type2.ptrRType, objEFace.rtype) keyEFace := unpackEFace(key) assertType("MapType.GetIndex argument 2", type2.pKeyRType, keyEFace.rtype) elemPtr := type2.UnsafeGetIndex(objEFace.data, keyEFace.data) return packEFace(type2.pElemRType, elemPtr) } func (type2 *UnsafeMapType) UnsafeGetIndex(obj unsafe.Pointer, key unsafe.Pointer) unsafe.Pointer { return mapaccess(type2.rtype, *(*unsafe.Pointer)(obj), key) } func (type2 *UnsafeMapType) Iterate(obj interface{}) MapIterator { objEFace := unpackEFace(obj) assertType("MapType.Iterate argument 1", type2.ptrRType, objEFace.rtype) return type2.UnsafeIterate(objEFace.data) } type UnsafeMapIterator struct { *hiter pKeyRType unsafe.Pointer pElemRType unsafe.Pointer } func (iter *UnsafeMapIterator) HasNext() bool { return iter.key != nil } func (iter *UnsafeMapIterator) Next() (interface{}, interface{}) { key, elem := iter.UnsafeNext() return packEFace(iter.pKeyRType, key), packEFace(iter.pElemRType, elem) } func (iter *UnsafeMapIterator) UnsafeNext() (unsafe.Pointer, unsafe.Pointer) { key := iter.key elem := iter.value mapiternext(iter.hiter) return key, elem }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/unsafe_field.go
vendor/github.com/modern-go/reflect2/unsafe_field.go
package reflect2 import ( "reflect" "unsafe" ) type UnsafeStructField struct { reflect.StructField structType *UnsafeStructType rtype unsafe.Pointer ptrRType unsafe.Pointer } func newUnsafeStructField(structType *UnsafeStructType, structField reflect.StructField) *UnsafeStructField { return &UnsafeStructField{ StructField: structField, rtype: unpackEFace(structField.Type).data, ptrRType: unpackEFace(reflect.PtrTo(structField.Type)).data, structType: structType, } } func (field *UnsafeStructField) Offset() uintptr { return field.StructField.Offset } func (field *UnsafeStructField) Name() string { return field.StructField.Name } func (field *UnsafeStructField) PkgPath() string { return field.StructField.PkgPath } func (field *UnsafeStructField) Type() Type { return field.structType.cfg.Type2(field.StructField.Type) } func (field *UnsafeStructField) Tag() reflect.StructTag { return field.StructField.Tag } func (field *UnsafeStructField) Index() []int { return field.StructField.Index } func (field *UnsafeStructField) Anonymous() bool { return field.StructField.Anonymous } func (field *UnsafeStructField) Set(obj interface{}, value interface{}) { objEFace := unpackEFace(obj) assertType("StructField.SetIndex argument 1", field.structType.ptrRType, objEFace.rtype) valueEFace := unpackEFace(value) assertType("StructField.SetIndex argument 2", field.ptrRType, valueEFace.rtype) field.UnsafeSet(objEFace.data, valueEFace.data) } func (field *UnsafeStructField) UnsafeSet(obj unsafe.Pointer, value unsafe.Pointer) { fieldPtr := add(obj, field.StructField.Offset, "same as non-reflect &v.field") typedmemmove(field.rtype, fieldPtr, value) } func (field *UnsafeStructField) Get(obj interface{}) interface{} { objEFace := unpackEFace(obj) assertType("StructField.GetIndex argument 1", field.structType.ptrRType, objEFace.rtype) value := field.UnsafeGet(objEFace.data) return packEFace(field.ptrRType, value) } func (field *UnsafeStructField) UnsafeGet(obj unsafe.Pointer) unsafe.Pointer { return add(obj, field.StructField.Offset, "same as non-reflect &v.field") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/go_below_118.go
vendor/github.com/modern-go/reflect2/go_below_118.go
//+build !go1.18 package reflect2 import ( "unsafe" ) // m escapes into the return value, but the caller of mapiterinit // doesn't let the return value escape. //go:noescape //go:linkname mapiterinit reflect.mapiterinit func mapiterinit(rtype unsafe.Pointer, m unsafe.Pointer) (val *hiter) func (type2 *UnsafeMapType) UnsafeIterate(obj unsafe.Pointer) MapIterator { return &UnsafeMapIterator{ hiter: mapiterinit(type2.rtype, *(*unsafe.Pointer)(obj)), pKeyRType: type2.pKeyRType, pElemRType: type2.pElemRType, } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/unsafe_type.go
vendor/github.com/modern-go/reflect2/unsafe_type.go
package reflect2 import ( "reflect" "unsafe" ) type unsafeType struct { safeType rtype unsafe.Pointer ptrRType unsafe.Pointer } func newUnsafeType(cfg *frozenConfig, type1 reflect.Type) *unsafeType { return &unsafeType{ safeType: safeType{ Type: type1, cfg: cfg, }, rtype: unpackEFace(type1).data, ptrRType: unpackEFace(reflect.PtrTo(type1)).data, } } func (type2 *unsafeType) Set(obj interface{}, val interface{}) { objEFace := unpackEFace(obj) assertType("Type.Set argument 1", type2.ptrRType, objEFace.rtype) valEFace := unpackEFace(val) assertType("Type.Set argument 2", type2.ptrRType, valEFace.rtype) type2.UnsafeSet(objEFace.data, valEFace.data) } func (type2 *unsafeType) UnsafeSet(ptr unsafe.Pointer, val unsafe.Pointer) { typedmemmove(type2.rtype, ptr, val) } func (type2 *unsafeType) IsNil(obj interface{}) bool { objEFace := unpackEFace(obj) assertType("Type.IsNil argument 1", type2.ptrRType, objEFace.rtype) return type2.UnsafeIsNil(objEFace.data) } func (type2 *unsafeType) UnsafeIsNil(ptr unsafe.Pointer) bool { return ptr == nil } func (type2 *unsafeType) UnsafeNew() unsafe.Pointer { return unsafe_New(type2.rtype) } func (type2 *unsafeType) New() interface{} { return packEFace(type2.ptrRType, type2.UnsafeNew()) } func (type2 *unsafeType) PackEFace(ptr unsafe.Pointer) interface{} { return packEFace(type2.ptrRType, ptr) } func (type2 *unsafeType) RType() uintptr { return uintptr(type2.rtype) } func (type2 *unsafeType) Indirect(obj interface{}) interface{} { objEFace := unpackEFace(obj) assertType("Type.Indirect argument 1", type2.ptrRType, objEFace.rtype) return type2.UnsafeIndirect(objEFace.data) } func (type2 *unsafeType) UnsafeIndirect(obj unsafe.Pointer) interface{} { return packEFace(type2.rtype, obj) } func (type2 *unsafeType) LikePtr() bool { return false } func assertType(where string, expectRType unsafe.Pointer, actualRType unsafe.Pointer) { if expectRType != actualRType { expectType := reflect.TypeOf(0) (*iface)(unsafe.Pointer(&expectType)).data = expectRType actualType := reflect.TypeOf(0) (*iface)(unsafe.Pointer(&actualType)).data = actualRType panic(where + ": expect " + expectType.String() + ", actual " + actualType.String()) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/modern-go/reflect2/unsafe_iface.go
vendor/github.com/modern-go/reflect2/unsafe_iface.go
package reflect2 import ( "reflect" "unsafe" ) type iface struct { itab *itab data unsafe.Pointer } type itab struct { ignore unsafe.Pointer rtype unsafe.Pointer } func IFaceToEFace(ptr unsafe.Pointer) interface{} { iface := (*iface)(ptr) if iface.itab == nil { return nil } return packEFace(iface.itab.rtype, iface.data) } type UnsafeIFaceType struct { unsafeType } func newUnsafeIFaceType(cfg *frozenConfig, type1 reflect.Type) *UnsafeIFaceType { return &UnsafeIFaceType{ unsafeType: *newUnsafeType(cfg, type1), } } func (type2 *UnsafeIFaceType) Indirect(obj interface{}) interface{} { objEFace := unpackEFace(obj) assertType("Type.Indirect argument 1", type2.ptrRType, objEFace.rtype) return type2.UnsafeIndirect(objEFace.data) } func (type2 *UnsafeIFaceType) UnsafeIndirect(ptr unsafe.Pointer) interface{} { return IFaceToEFace(ptr) } func (type2 *UnsafeIFaceType) IsNil(obj interface{}) bool { if obj == nil { return true } objEFace := unpackEFace(obj) assertType("Type.IsNil argument 1", type2.ptrRType, objEFace.rtype) return type2.UnsafeIsNil(objEFace.data) } func (type2 *UnsafeIFaceType) UnsafeIsNil(ptr unsafe.Pointer) bool { if ptr == nil { return true } iface := (*iface)(ptr) if iface.itab == nil { return true } return false }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-contrib/cors/cors.go
vendor/github.com/gin-contrib/cors/cors.go
package cors import ( "errors" "fmt" "regexp" "strings" "time" "github.com/gin-gonic/gin" ) // Config represents all available options for the middleware. type Config struct { AllowAllOrigins bool // AllowOrigins is a list of origins a cross-domain request can be executed from. // If the special "*" value is present in the list, all origins will be allowed. // Default value is [] AllowOrigins []string // AllowOriginFunc is a custom function to validate the origin. It takes the origin // as an argument and returns true if allowed or false otherwise. If this option is // set, the content of AllowOrigins is ignored. AllowOriginFunc func(origin string) bool // Same as AllowOriginFunc except also receives the full request context. // This function should use the context as a read only source and not // have any side effects on the request, such as aborting or injecting // values on the request. AllowOriginWithContextFunc func(c *gin.Context, origin string) bool // AllowMethods is a list of methods the client is allowed to use with // cross-domain requests. Default value is simple methods (GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS) AllowMethods []string // AllowPrivateNetwork indicates whether the response should include allow private network header AllowPrivateNetwork bool // AllowHeaders is list of non simple headers the client is allowed to use with // cross-domain requests. AllowHeaders []string // AllowCredentials indicates whether the request can include user credentials like // cookies, HTTP authentication or client side SSL certificates. AllowCredentials bool // ExposeHeaders indicates which headers are safe to expose to the API of a CORS // API specification ExposeHeaders []string // MaxAge indicates how long (with second-precision) the results of a preflight request // can be cached MaxAge time.Duration // Allows to add origins like http://some-domain/*, https://api.* or http://some.*.subdomain.com AllowWildcard bool // Allows usage of popular browser extensions schemas AllowBrowserExtensions bool // Allows to add custom schema like tauri:// CustomSchemas []string // Allows usage of WebSocket protocol AllowWebSockets bool // Allows usage of file:// schema (dangerous!) use it only when you 100% sure it's needed AllowFiles bool // Allows to pass custom OPTIONS response status code for old browsers / clients OptionsResponseStatusCode int } // AddAllowMethods is allowed to add custom methods func (c *Config) AddAllowMethods(methods ...string) { c.AllowMethods = append(c.AllowMethods, methods...) } // AddAllowHeaders is allowed to add custom headers func (c *Config) AddAllowHeaders(headers ...string) { c.AllowHeaders = append(c.AllowHeaders, headers...) } // AddExposeHeaders is allowed to add custom expose headers func (c *Config) AddExposeHeaders(headers ...string) { c.ExposeHeaders = append(c.ExposeHeaders, headers...) } func (c Config) getAllowedSchemas() []string { allowedSchemas := DefaultSchemas if c.AllowBrowserExtensions { allowedSchemas = append(allowedSchemas, ExtensionSchemas...) } if c.AllowWebSockets { allowedSchemas = append(allowedSchemas, WebSocketSchemas...) } if c.AllowFiles { allowedSchemas = append(allowedSchemas, FileSchemas...) } if c.CustomSchemas != nil { allowedSchemas = append(allowedSchemas, c.CustomSchemas...) } return allowedSchemas } var regexpBasedOrigin = regexp.MustCompile(`^\/(.+)\/[gimuy]?$`) func (c Config) validateAllowedSchemas(origin string) bool { allowedSchemas := c.getAllowedSchemas() if regexpBasedOrigin.MatchString(origin) { // Normalize regexp-based origins origin = regexpBasedOrigin.FindStringSubmatch(origin)[1] origin = strings.Replace(origin, "?", "", 1) } for _, schema := range allowedSchemas { if strings.HasPrefix(origin, schema) { return true } } return false } // Validate is check configuration of user defined. func (c Config) Validate() error { hasOriginFn := c.AllowOriginFunc != nil hasOriginFn = hasOriginFn || c.AllowOriginWithContextFunc != nil if c.AllowAllOrigins && (hasOriginFn || len(c.AllowOrigins) > 0) { originFields := strings.Join([]string{ "AllowOriginFunc", "AllowOriginFuncWithContext", "AllowOrigins", }, " or ") return fmt.Errorf( "conflict settings: all origins enabled. %s is not needed", originFields, ) } if !c.AllowAllOrigins && !hasOriginFn && len(c.AllowOrigins) == 0 { return errors.New("conflict settings: all origins disabled") } for _, origin := range c.AllowOrigins { if !strings.Contains(origin, "*") && !c.validateAllowedSchemas(origin) { return errors.New("bad origin: origins must contain '*' or include " + strings.Join(c.getAllowedSchemas(), ",")) } } return nil } func (c Config) parseWildcardRules() [][]string { var wRules [][]string if !c.AllowWildcard { return wRules } for _, o := range c.AllowOrigins { if !strings.Contains(o, "*") { continue } if c := strings.Count(o, "*"); c > 1 { panic(errors.New("only one * is allowed").Error()) } i := strings.Index(o, "*") if i == 0 { wRules = append(wRules, []string{"*", o[1:]}) continue } if i == (len(o) - 1) { wRules = append(wRules, []string{o[:i], "*"}) continue } wRules = append(wRules, []string{o[:i], o[i+1:]}) } return wRules } // DefaultConfig returns a generic default configuration mapped to localhost. func DefaultConfig() Config { return Config{ AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}, AllowHeaders: []string{"Origin", "Content-Length", "Content-Type"}, AllowCredentials: false, MaxAge: 12 * time.Hour, } } // Default returns the location middleware with default configuration. func Default() gin.HandlerFunc { config := DefaultConfig() config.AllowAllOrigins = true return New(config) } // New returns the location middleware with user-defined custom configuration. func New(config Config) gin.HandlerFunc { cors := newCors(config) return func(c *gin.Context) { cors.applyCors(c) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-contrib/cors/utils.go
vendor/github.com/gin-contrib/cors/utils.go
package cors import ( "net/http" "strconv" "strings" "time" ) type converter func(string) string func generateNormalHeaders(c Config) http.Header { headers := make(http.Header) if c.AllowCredentials { headers.Set("Access-Control-Allow-Credentials", "true") } if len(c.ExposeHeaders) > 0 { exposeHeaders := convert(normalize(c.ExposeHeaders), http.CanonicalHeaderKey) headers.Set("Access-Control-Expose-Headers", strings.Join(exposeHeaders, ",")) } if c.AllowAllOrigins { headers.Set("Access-Control-Allow-Origin", "*") } else { headers.Set("Vary", "Origin") } return headers } func generatePreflightHeaders(c Config) http.Header { headers := make(http.Header) if c.AllowCredentials { headers.Set("Access-Control-Allow-Credentials", "true") } if len(c.AllowMethods) > 0 { allowMethods := convert(normalize(c.AllowMethods), strings.ToUpper) value := strings.Join(allowMethods, ",") headers.Set("Access-Control-Allow-Methods", value) } if len(c.AllowHeaders) > 0 { allowHeaders := convert(normalize(c.AllowHeaders), http.CanonicalHeaderKey) value := strings.Join(allowHeaders, ",") headers.Set("Access-Control-Allow-Headers", value) } if c.MaxAge > time.Duration(0) { value := strconv.FormatInt(int64(c.MaxAge/time.Second), 10) headers.Set("Access-Control-Max-Age", value) } if c.AllowPrivateNetwork { headers.Set("Access-Control-Allow-Private-Network", "true") } if c.AllowAllOrigins { headers.Set("Access-Control-Allow-Origin", "*") } else { // Always set Vary headers // see https://github.com/rs/cors/issues/10, // https://github.com/rs/cors/commit/dbdca4d95feaa7511a46e6f1efb3b3aa505bc43f#commitcomment-12352001 headers.Add("Vary", "Origin") headers.Add("Vary", "Access-Control-Request-Method") headers.Add("Vary", "Access-Control-Request-Headers") } return headers } func normalize(values []string) []string { if values == nil { return nil } distinctMap := make(map[string]bool, len(values)) normalized := make([]string, 0, len(values)) for _, value := range values { value = strings.TrimSpace(value) value = strings.ToLower(value) if _, seen := distinctMap[value]; !seen { normalized = append(normalized, value) distinctMap[value] = true } } return normalized } func convert(s []string, c converter) []string { var out []string for _, i := range s { out = append(out, c(i)) } return out }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-contrib/cors/config.go
vendor/github.com/gin-contrib/cors/config.go
package cors import ( "net/http" "regexp" "strings" "github.com/gin-gonic/gin" ) type cors struct { allowAllOrigins bool allowCredentials bool allowOriginFunc func(string) bool allowOriginWithContextFunc func(*gin.Context, string) bool allowOrigins []string normalHeaders http.Header preflightHeaders http.Header wildcardOrigins [][]string optionsResponseStatusCode int } var ( DefaultSchemas = []string{ "http://", "https://", } ExtensionSchemas = []string{ "chrome-extension://", "safari-extension://", "moz-extension://", "ms-browser-extension://", } FileSchemas = []string{ "file://", } WebSocketSchemas = []string{ "ws://", "wss://", } ) func newCors(config Config) *cors { if err := config.Validate(); err != nil { panic(err.Error()) } for _, origin := range config.AllowOrigins { if origin == "*" { config.AllowAllOrigins = true } } if config.OptionsResponseStatusCode == 0 { config.OptionsResponseStatusCode = http.StatusNoContent } return &cors{ allowOriginFunc: config.AllowOriginFunc, allowOriginWithContextFunc: config.AllowOriginWithContextFunc, allowAllOrigins: config.AllowAllOrigins, allowCredentials: config.AllowCredentials, allowOrigins: normalize(config.AllowOrigins), normalHeaders: generateNormalHeaders(config), preflightHeaders: generatePreflightHeaders(config), wildcardOrigins: config.parseWildcardRules(), optionsResponseStatusCode: config.OptionsResponseStatusCode, } } func (cors *cors) applyCors(c *gin.Context) { origin := c.Request.Header.Get("Origin") if len(origin) == 0 { // request is not a CORS request return } host := c.Request.Host if origin == "http://"+host || origin == "https://"+host { // request is not a CORS request but have origin header. // for example, use fetch api return } if !cors.isOriginValid(c, origin) { c.AbortWithStatus(http.StatusForbidden) return } if c.Request.Method == "OPTIONS" { cors.handlePreflight(c) defer c.AbortWithStatus(cors.optionsResponseStatusCode) } else { cors.handleNormal(c) } if !cors.allowAllOrigins { c.Header("Access-Control-Allow-Origin", origin) } } func (cors *cors) validateWildcardOrigin(origin string) bool { for _, w := range cors.wildcardOrigins { if w[0] == "*" && strings.HasSuffix(origin, w[1]) { return true } if w[1] == "*" && strings.HasPrefix(origin, w[0]) { return true } if strings.HasPrefix(origin, w[0]) && strings.HasSuffix(origin, w[1]) { return true } } return false } func (cors *cors) isOriginValid(c *gin.Context, origin string) bool { valid := cors.validateOrigin(origin) if !valid && cors.allowOriginWithContextFunc != nil { valid = cors.allowOriginWithContextFunc(c, origin) } return valid } var originRegex = regexp.MustCompile(`^/(.+)/[gimuy]?$`) func (cors *cors) validateOrigin(origin string) bool { if cors.allowAllOrigins { return true } for _, value := range cors.allowOrigins { if !originRegex.MatchString(value) && value == origin { return true } if originRegex.MatchString(value) && regexp.MustCompile(originRegex.FindStringSubmatch(value)[1]).MatchString(origin) { return true } } if len(cors.wildcardOrigins) > 0 && cors.validateWildcardOrigin(origin) { return true } if cors.allowOriginFunc != nil { return cors.allowOriginFunc(origin) } return false } func (cors *cors) handlePreflight(c *gin.Context) { header := c.Writer.Header() for key, value := range cors.preflightHeaders { header[key] = value } } func (cors *cors) handleNormal(c *gin.Context) { header := c.Writer.Header() for key, value := range cors.normalHeaders { header[key] = value } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-contrib/sse/sse-encoder.go
vendor/github.com/gin-contrib/sse/sse-encoder.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package sse import ( "encoding/json" "fmt" "io" "net/http" "reflect" "strconv" "strings" ) // Server-Sent Events // W3C Working Draft 29 October 2009 // http://www.w3.org/TR/2009/WD-eventsource-20091029/ const ContentType = "text/event-stream;charset=utf-8" var contentType = []string{ContentType} var noCache = []string{"no-cache"} var fieldReplacer = strings.NewReplacer( "\n", "\\n", "\r", "\\r") var dataReplacer = strings.NewReplacer( "\n", "\ndata:", "\r", "\\r") type Event struct { Event string Id string Retry uint Data interface{} } func Encode(writer io.Writer, event Event) error { w := checkWriter(writer) writeId(w, event.Id) writeEvent(w, event.Event) writeRetry(w, event.Retry) return writeData(w, event.Data) } func writeId(w stringWriter, id string) { if len(id) > 0 { w.WriteString("id:") fieldReplacer.WriteString(w, id) w.WriteString("\n") } } func writeEvent(w stringWriter, event string) { if len(event) > 0 { w.WriteString("event:") fieldReplacer.WriteString(w, event) w.WriteString("\n") } } func writeRetry(w stringWriter, retry uint) { if retry > 0 { w.WriteString("retry:") w.WriteString(strconv.FormatUint(uint64(retry), 10)) w.WriteString("\n") } } func writeData(w stringWriter, data interface{}) error { w.WriteString("data:") bData, ok := data.([]byte) if ok { dataReplacer.WriteString(w, string(bData)) w.WriteString("\n\n") return nil } switch kindOfData(data) { case reflect.Struct, reflect.Slice, reflect.Map: err := json.NewEncoder(w).Encode(data) if err != nil { return err } w.WriteString("\n") default: dataReplacer.WriteString(w, fmt.Sprint(data)) w.WriteString("\n\n") } return nil } func (r Event) Render(w http.ResponseWriter) error { r.WriteContentType(w) return Encode(w, r) } func (r Event) WriteContentType(w http.ResponseWriter) { header := w.Header() header["Content-Type"] = contentType if _, exist := header["Cache-Control"]; !exist { header["Cache-Control"] = noCache } } func kindOfData(data interface{}) reflect.Kind { value := reflect.ValueOf(data) valueType := value.Kind() if valueType == reflect.Ptr { valueType = value.Elem().Kind() } return valueType }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-contrib/sse/writer.go
vendor/github.com/gin-contrib/sse/writer.go
package sse import "io" type stringWriter interface { io.Writer WriteString(string) (int, error) } type stringWrapper struct { io.Writer } func (w stringWrapper) WriteString(str string) (int, error) { return w.Writer.Write([]byte(str)) } func checkWriter(writer io.Writer) stringWriter { if w, ok := writer.(stringWriter); ok { return w } else { return stringWrapper{writer} } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gin-contrib/sse/sse-decoder.go
vendor/github.com/gin-contrib/sse/sse-decoder.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package sse import ( "bytes" "io" "io/ioutil" ) type decoder struct { events []Event } func Decode(r io.Reader) ([]Event, error) { var dec decoder return dec.decode(r) } func (d *decoder) dispatchEvent(event Event, data string) { dataLength := len(data) if dataLength > 0 { //If the data buffer's last character is a U+000A LINE FEED (LF) character, then remove the last character from the data buffer. data = data[:dataLength-1] dataLength-- } if dataLength == 0 && event.Event == "" { return } if event.Event == "" { event.Event = "message" } event.Data = data d.events = append(d.events, event) } func (d *decoder) decode(r io.Reader) ([]Event, error) { buf, err := ioutil.ReadAll(r) if err != nil { return nil, err } var currentEvent Event var dataBuffer *bytes.Buffer = new(bytes.Buffer) // TODO (and unit tests) // Lines must be separated by either a U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair, // a single U+000A LINE FEED (LF) character, // or a single U+000D CARRIAGE RETURN (CR) character. lines := bytes.Split(buf, []byte{'\n'}) for _, line := range lines { if len(line) == 0 { // If the line is empty (a blank line). Dispatch the event. d.dispatchEvent(currentEvent, dataBuffer.String()) // reset current event and data buffer currentEvent = Event{} dataBuffer.Reset() continue } if line[0] == byte(':') { // If the line starts with a U+003A COLON character (:), ignore the line. continue } var field, value []byte colonIndex := bytes.IndexRune(line, ':') if colonIndex != -1 { // If the line contains a U+003A COLON character character (:) // Collect the characters on the line before the first U+003A COLON character (:), // and let field be that string. field = line[:colonIndex] // Collect the characters on the line after the first U+003A COLON character (:), // and let value be that string. value = line[colonIndex+1:] // If value starts with a single U+0020 SPACE character, remove it from value. if len(value) > 0 && value[0] == ' ' { value = value[1:] } } else { // Otherwise, the string is not empty but does not contain a U+003A COLON character character (:) // Use the whole line as the field name, and the empty string as the field value. field = line value = []byte{} } // The steps to process the field given a field name and a field value depend on the field name, // as given in the following list. Field names must be compared literally, // with no case folding performed. switch string(field) { case "event": // Set the event name buffer to field value. currentEvent.Event = string(value) case "id": // Set the event stream's last event ID to the field value. currentEvent.Id = string(value) case "retry": // If the field value consists of only characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), // then interpret the field value as an integer in base ten, and set the event stream's reconnection time to that integer. // Otherwise, ignore the field. currentEvent.Id = string(value) case "data": // Append the field value to the data buffer, dataBuffer.Write(value) // then append a single U+000A LINE FEED (LF) character to the data buffer. dataBuffer.WriteString("\n") default: //Otherwise. The field is ignored. continue } } // Once the end of the file is reached, the user agent must dispatch the event one final time. d.dispatchEvent(currentEvent, dataBuffer.String()) return d.events, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false