From ab7e69e374663e329bdcbf46a36376eb944cbaef Mon Sep 17 00:00:00 2001 From: OHZEKI Naoki <0h23k1.n40k1@gmail.com> Date: Thu, 11 Dec 2025 00:20:14 +0900 Subject: [PATCH] refactor(utils): move util functions to utils.go --- context.go | 8 -------- tree.go | 9 --------- utils.go | 17 +++++++++++++++++ utils_test.go | 11 +++++++++++ 4 files changed, 28 insertions(+), 17 deletions(-) diff --git a/context.go b/context.go index 112f0ee0..e1d9be43 100644 --- a/context.go +++ b/context.go @@ -55,14 +55,6 @@ const ContextRequestKey ContextKeyType = 0 // abortIndex represents a typical value used in abort functions. const abortIndex int8 = math.MaxInt8 >> 1 -// safeInt8 converts int to int8 safely, capping at math.MaxInt8 -func safeInt8(n int) int8 { - if n > math.MaxInt8 { - return math.MaxInt8 - } - return int8(n) -} - // 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 { diff --git a/tree.go b/tree.go index eff07734..88f25fcb 100644 --- a/tree.go +++ b/tree.go @@ -5,7 +5,6 @@ package gin import ( - "math" "net/url" "strings" "unicode" @@ -78,14 +77,6 @@ func (n *node) addChild(child *node) { } } -// safeUint16 converts int to uint16 safely, capping at math.MaxUint16 -func safeUint16(n int) uint16 { - if n > math.MaxUint16 { - return math.MaxUint16 - } - return uint16(n) -} - func countParams(path string) uint16 { colons := strings.Count(path, ":") stars := strings.Count(path, "*") diff --git a/utils.go b/utils.go index 47106a7a..971e9433 100644 --- a/utils.go +++ b/utils.go @@ -6,6 +6,7 @@ package gin import ( "encoding/xml" + "math" "net/http" "os" "path" @@ -162,3 +163,19 @@ func isASCII(s string) bool { } return true } + +// safeInt8 converts int to int8 safely, capping at math.MaxInt8 +func safeInt8(n int) int8 { + if n > math.MaxInt8 { + return math.MaxInt8 + } + return int8(n) +} + +// safeUint16 converts int to uint16 safely, capping at math.MaxUint16 +func safeUint16(n int) uint16 { + if n > math.MaxUint16 { + return math.MaxUint16 + } + return uint16(n) +} diff --git a/utils_test.go b/utils_test.go index 8bcf00e4..893ebc88 100644 --- a/utils_test.go +++ b/utils_test.go @@ -8,6 +8,7 @@ import ( "bytes" "encoding/xml" "fmt" + "math" "net/http" "testing" @@ -148,3 +149,13 @@ func TestIsASCII(t *testing.T) { assert.True(t, isASCII("test")) assert.False(t, isASCII("๐Ÿงก๐Ÿ’›๐Ÿ’š๐Ÿ’™๐Ÿ’œ")) } + +func TestSafeInt8(t *testing.T) { + assert.Equal(t, int8(100), safeInt8(100)) + assert.Equal(t, int8(math.MaxInt8), safeInt8(int(math.MaxInt8)+123)) +} + +func TestSafeUint16(t *testing.T) { + assert.Equal(t, uint16(100), safeUint16(100)) + assert.Equal(t, uint16(math.MaxUint16), safeUint16(int(math.MaxUint16)+123)) +}