// Package byteutil provides some useful functions for byte slice.
package byteutil import ( ) // Md5 Generate a 32-bit md5 bytes func ( any) []byte { := Md5Sum() := make([]byte, hex.EncodedLen(len())) hex.Encode(, ) return } // Md5Sum Generate a md5 bytes func ( any) []byte { := md5.New() switch val := .(type) { case []byte: .Write() case string: .Write([]byte()) default: .Write([]byte(fmt.Sprint())) } return .Sum(nil) // cap(bs) == 16 } // ShortMd5 Generate a 16-bit md5 bytes. remove the first 8 and last 8 bytes from 32-bit md5. func ( any) []byte { return Md5()[8:24] } // Random bytes generate func ( int) ([]byte, error) { := make([]byte, ) // Note that err == nil only if we read len(b) bytes. if , := rand.Read(); != nil { return nil, } return , nil } // FirstLine from command output func ( []byte) []byte { if := bytes.IndexByte(, '\n'); >= 0 { return [0:] } return } // AppendAny append any value to byte slice func ( []byte, any) []byte { if == nil { return append(, "<nil>"...) } switch val := .(type) { case []byte: = append(, ...) case string: = append(, ...) case int: = strconv.AppendInt(, int64(), 10) case int8: = strconv.AppendInt(, int64(), 10) case int16: = strconv.AppendInt(, int64(), 10) case int32: = strconv.AppendInt(, int64(), 10) case int64: = strconv.AppendInt(, , 10) case uint: = strconv.AppendUint(, uint64(), 10) case uint8: = strconv.AppendUint(, uint64(), 10) case uint16: = strconv.AppendUint(, uint64(), 10) case uint32: = strconv.AppendUint(, uint64(), 10) case uint64: = strconv.AppendUint(, , 10) case float32: = strconv.AppendFloat(, float64(), 'f', -1, 32) case float64: = strconv.AppendFloat(, , 'f', -1, 64) case bool: = strconv.AppendBool(, ) case time.Time: = .AppendFormat(, time.RFC3339) case time.Duration: = strconv.AppendInt(, int64(), 10) case error: = append(, .Error()...) case fmt.Stringer: = append(, .String()...) default: = append(, fmt.Sprint()...) } return } // Cut bytes by one byte char. like bytes.Cut(), but sep is byte. func ( []byte, byte) (, []byte, bool) { return bytes.Cut(, []byte{}) } // SafeCut bytes by one byte char. always return before and after func ( []byte, byte) (, []byte) { , , _ = bytes.Cut(, []byte{}) return } // SafeCuts bytes by sub bytes. like the bytes.Cut(), but always return before and after func ( []byte, []byte) (, []byte) { , , _ = bytes.Cut(, ) return }