Skip to content

Commit 92164df

Browse files
authored
feat: introduce safe integer conversion with error handling (#812)
- Add `errors` and `math` packages to imports - Introduce `safeIntToInt32` function to safely convert `int` to `int32` with error handling for out-of-range values - Replace direct `int32` conversion with `safeIntToInt32` in `Send` function - Add unit tests for `safeIntToInt32` function with various test cases including valid, overflow, and underflow scenarios Signed-off-by: appleboy <[email protected]>
1 parent 03c922f commit 92164df

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

rpc/server.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@ package rpc
33
import (
44
"context"
55
"crypto/tls"
6+
"errors"
67
"fmt"
8+
"math"
79
"net"
810
"runtime/debug"
911
"strings"
@@ -116,12 +118,25 @@ func (s *Server) Send(ctx context.Context, in *proto.NotificationRequest) (*prot
116118
}
117119
}()
118120

121+
counts, err := safeIntToInt32(len(notification.Tokens))
122+
if err != nil {
123+
return nil, status.Error(codes.InvalidArgument, err.Error())
124+
}
125+
119126
return &proto.NotificationReply{
120127
Success: true,
121-
Counts: int32(len(notification.Tokens)),
128+
Counts: counts,
122129
}, nil
123130
}
124131

132+
// safeIntToInt32 converts an int to an int32, returning an error if the int is out of range.
133+
func safeIntToInt32(n int) (int32, error) {
134+
if n < math.MinInt32 || n > math.MaxInt32 {
135+
return 0, errors.New("integer overflow: value out of int32 range")
136+
}
137+
return int32(n), nil
138+
}
139+
125140
// RunGRPCServer run gorush grpc server
126141
func RunGRPCServer(ctx context.Context, cfg *config.ConfYaml) error {
127142
if !cfg.GRPC.Enabled {

rpc/server_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,38 @@
11
package rpc
22

3+
import (
4+
"math"
5+
"testing"
6+
)
7+
8+
func TestSafeIntToInt32(t *testing.T) {
9+
tests := []struct {
10+
name string
11+
input int
12+
want int32
13+
wantErr bool
14+
}{
15+
{"Valid int32", 123, 123, false},
16+
{"Max int32", math.MaxInt32, math.MaxInt32, false},
17+
{"Min int32", math.MinInt32, math.MinInt32, false},
18+
{"Overflow int32", math.MaxInt32 + 1, 0, true},
19+
{"Underflow int32", math.MinInt32 - 1, 0, true},
20+
}
21+
22+
for _, tt := range tests {
23+
t.Run(tt.name, func(t *testing.T) {
24+
got, err := safeIntToInt32(tt.input)
25+
if (err != nil) != tt.wantErr {
26+
t.Errorf("safeIntToInt32() error = %v, wantErr %v", err, tt.wantErr)
27+
return
28+
}
29+
if got != tt.want {
30+
t.Errorf("safeIntToInt32() = %v, want %v", got, tt.want)
31+
}
32+
})
33+
}
34+
}
35+
336
// const gRPCAddr = "localhost:9000"
437

538
// func initTest() *config.ConfYaml {

0 commit comments

Comments
 (0)