Skip to content

Commit

Permalink
feat: introduce safe integer conversion with error handling (#812)
Browse files Browse the repository at this point in the history
- 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 <appleboy.tw@gmail.com>
  • Loading branch information
appleboy committed Sep 17, 2024
1 parent 03c922f commit 92164df
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
17 changes: 16 additions & 1 deletion rpc/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package rpc
import (
"context"
"crypto/tls"
"errors"
"fmt"
"math"
"net"
"runtime/debug"
"strings"
Expand Down Expand Up @@ -116,12 +118,25 @@ func (s *Server) Send(ctx context.Context, in *proto.NotificationRequest) (*prot
}
}()

counts, err := safeIntToInt32(len(notification.Tokens))
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}

return &proto.NotificationReply{
Success: true,
Counts: int32(len(notification.Tokens)),
Counts: counts,
}, nil
}

// safeIntToInt32 converts an int to an int32, returning an error if the int is out of range.
func safeIntToInt32(n int) (int32, error) {
if n < math.MinInt32 || n > math.MaxInt32 {
return 0, errors.New("integer overflow: value out of int32 range")
}
return int32(n), nil
}

// RunGRPCServer run gorush grpc server
func RunGRPCServer(ctx context.Context, cfg *config.ConfYaml) error {
if !cfg.GRPC.Enabled {
Expand Down
33 changes: 33 additions & 0 deletions rpc/server_test.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,38 @@
package rpc

import (
"math"
"testing"
)

func TestSafeIntToInt32(t *testing.T) {
tests := []struct {
name string
input int
want int32
wantErr bool
}{
{"Valid int32", 123, 123, false},
{"Max int32", math.MaxInt32, math.MaxInt32, false},
{"Min int32", math.MinInt32, math.MinInt32, false},
{"Overflow int32", math.MaxInt32 + 1, 0, true},
{"Underflow int32", math.MinInt32 - 1, 0, true},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := safeIntToInt32(tt.input)
if (err != nil) != tt.wantErr {
t.Errorf("safeIntToInt32() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("safeIntToInt32() = %v, want %v", got, tt.want)
}
})
}
}

// const gRPCAddr = "localhost:9000"

// func initTest() *config.ConfYaml {
Expand Down

0 comments on commit 92164df

Please sign in to comment.