dae/common/utils.go

81 lines
1.5 KiB
Go
Raw Normal View History

2023-01-23 18:54:21 +07:00
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2022, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package common
import (
"encoding/base64"
"encoding/binary"
"net/url"
"strings"
)
func CloneStrings(slice []string) []string {
c := make([]string, len(slice))
copy(c, slice)
return c
}
func ARangeU32(n uint32) []uint32 {
ret := make([]uint32, n)
for i := uint32(0); i < n; i++ {
ret[i] = i
}
return ret
}
func Ipv6ByteSliceToUint32Array(_ip []byte) (ip [4]uint32) {
for j := 0; j < 16; j += 4 {
ip[j/4] = binary.LittleEndian.Uint32(_ip[j : j+4])
}
return ip
}
func Deduplicate(list []string) []string {
res := make([]string, 0, len(list))
m := make(map[string]struct{})
for _, v := range list {
if _, ok := m[v]; ok {
continue
}
m[v] = struct{}{}
res = append(res, v)
}
return res
}
func Base64UrlDecode(s string) (string, error) {
s = strings.TrimSpace(s)
saver := s
if len(s)%4 > 0 {
s += strings.Repeat("=", 4-len(s)%4)
}
raw, err := base64.URLEncoding.DecodeString(s)
if err != nil {
return saver, err
}
return string(raw), nil
}
func Base64StdDecode(s string) (string, error) {
s = strings.TrimSpace(s)
saver := s
if len(s)%4 > 0 {
s += strings.Repeat("=", 4-len(s)%4)
}
raw, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return saver, err
}
return string(raw), nil
}
func SetValue(values *url.Values, key string, value string) {
if value == "" {
return
}
values.Set(key, value)
}