package byteutil

import (
	
	
	
	

	
)

// StrOrErr convert to string, return empty string on error.
func ( []byte,  error) (string, error) {
	if  != nil {
		return "", 
	}
	return string(), 
}

// SafeString convert to string, return empty string on error.
func ( []byte,  error) string {
	if  != nil {
		return ""
	}
	return string()
}

// String unsafe convert bytes to string
func ( []byte) string {
	return *(*string)(unsafe.Pointer(&))
}

// ToString convert bytes to string
func ( []byte) string {
	return *(*string)(unsafe.Pointer(&))
}

// ToBytes convert any value to []byte. return error on convert failed.
func ( any) ([]byte, error) {
	return ToBytesWithFunc(, nil)
}

// SafeBytes convert any value to []byte. use fmt.Sprint() on convert failed.
func ( any) []byte {
	,  := ToBytesWithFunc(, func( any) ([]byte, error) {
		return []byte(fmt.Sprint()), nil
	})
	return 
}

// ToBytesFunc convert any value to []byte
type ToBytesFunc = func(v any) ([]byte, error)

// ToBytesWithFunc convert any value to []byte with custom fallback func.
//
// refer the strutil.ToStringWithFunc
//
// On not convert:
//   - If usrFn is nil, will return comdef.ErrConvType.
//   - If usrFn is not nil, will call it to convert.
func ( any,  ToBytesFunc) ([]byte, error) {
	if  == nil {
		return nil, nil
	}

	switch val := .(type) {
	case []byte:
		return , nil
	case string:
		return []byte(), nil
	case int:
		return []byte(strconv.Itoa()), nil
	case int8:
		return []byte(strconv.Itoa(int())), nil
	case int16:
		return []byte(strconv.Itoa(int())), nil
	case int32: // same as `rune`
		return []byte(strconv.Itoa(int())), nil
	case int64:
		return []byte(strconv.FormatInt(, 10)), nil
	case uint:
		return []byte(strconv.FormatUint(uint64(), 10)), nil
	case uint8:
		return []byte(strconv.FormatUint(uint64(), 10)), nil
	case uint16:
		return []byte(strconv.FormatUint(uint64(), 10)), nil
	case uint32:
		return []byte(strconv.FormatUint(uint64(), 10)), nil
	case uint64:
		return []byte(strconv.FormatUint(, 10)), nil
	case float32:
		return []byte(strconv.FormatFloat(float64(), 'f', -1, 32)), nil
	case float64:
		return []byte(strconv.FormatFloat(, 'f', -1, 64)), nil
	case bool:
		return []byte(strconv.FormatBool()), nil
	case time.Duration:
		return []byte(strconv.FormatInt(int64(), 10)), nil
	case fmt.Stringer:
		return []byte(.String()), nil
	case error:
		return []byte(.Error()), nil
	default:
		if  == nil {
			return nil, comdef.ErrConvType
		}
		return ()
	}
}

// Reverse 反转字节数组 eg: ABCD -> DCBA
func ( []byte) {
	for  := 0;  < len()/2; ++ {
		[], [len()-1-] = [len()-1-], []
	}
}