From e1d7ce4640c4c897c19398c4c1d7522db35db34d Mon Sep 17 00:00:00 2001 From: Haruue Date: Fri, 5 Apr 2024 10:49:03 +0800 Subject: [PATCH] chore: a better fix for 32-bit unix.Timeval Why there is no decltype() in Golang? At least we got generics now. ref: 9520d840942d3950ed43af281935c262fac35615 --- app/internal/sockopts/sockopts_linux.go | 12 +++++++++++- app/internal/sockopts/timeval_linux_32.go | 15 --------------- app/internal/sockopts/timeval_linux_64.go | 15 --------------- 3 files changed, 11 insertions(+), 31 deletions(-) delete mode 100644 app/internal/sockopts/timeval_linux_32.go delete mode 100644 app/internal/sockopts/timeval_linux_64.go diff --git a/app/internal/sockopts/sockopts_linux.go b/app/internal/sockopts/sockopts_linux.go index e51e75a..ce188d9 100644 --- a/app/internal/sockopts/sockopts_linux.go +++ b/app/internal/sockopts/sockopts_linux.go @@ -7,6 +7,8 @@ import ( "net" "time" + "golang.org/x/exp/constraints" + "golang.org/x/sys/unix" ) @@ -58,7 +60,11 @@ func fdControlUnixSocketImpl(c *net.UDPConn, path string) error { } defer unix.Close(socketFd) - timeout := unixTimeval() + var timeout unix.Timeval + timeUsec := fdControlUnixTimeout.Microseconds() + castAssignInteger(timeUsec/1e6, &timeout.Sec) + // Specifying the type explicitly is not necessary here, but it makes GoLand happy. + castAssignInteger[int64](timeUsec%1e6, &timeout.Usec) _ = unix.SetsockoptTimeval(socketFd, unix.SOL_SOCKET, unix.SO_RCVTIMEO, &timeout) _ = unix.SetsockoptTimeval(socketFd, unix.SOL_SOCKET, unix.SO_SNDTIMEO, &timeout) @@ -85,3 +91,7 @@ func fdControlUnixSocketImpl(c *net.UDPConn, path string) error { return nil }) } + +func castAssignInteger[F, T constraints.Integer](from F, to *T) { + *to = T(from) +} diff --git a/app/internal/sockopts/timeval_linux_32.go b/app/internal/sockopts/timeval_linux_32.go deleted file mode 100644 index af8c262..0000000 --- a/app/internal/sockopts/timeval_linux_32.go +++ /dev/null @@ -1,15 +0,0 @@ -//go:build linux && (386 || arm || mips || mipsle || ppc) - -package sockopts - -import ( - "golang.org/x/sys/unix" -) - -func unixTimeval() unix.Timeval { - timeUsec := fdControlUnixTimeout.Microseconds() - return unix.Timeval{ - Sec: int32(timeUsec / 1e6), - Usec: int32(timeUsec % 1e6), - } -} diff --git a/app/internal/sockopts/timeval_linux_64.go b/app/internal/sockopts/timeval_linux_64.go deleted file mode 100644 index 407438c..0000000 --- a/app/internal/sockopts/timeval_linux_64.go +++ /dev/null @@ -1,15 +0,0 @@ -//go:build linux && (amd64 || arm64 || loong64 || mips64 || mips64le || ppc64 || ppc64le || riscv64 || s390x || sparc64) - -package sockopts - -import ( - "golang.org/x/sys/unix" -) - -func unixTimeval() unix.Timeval { - timeUsec := fdControlUnixTimeout.Microseconds() - return unix.Timeval{ - Sec: timeUsec / 1e6, - Usec: timeUsec % 1e6, - } -}