zhangzengfei
2024-05-28 b5166ec34cea995536384391712373f1d0d69e28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package pkg
 
import (
    "fmt"
    "strconv"
    "strings"
 
    "gat1400Exchange/pkg/snowflake"
)
 
// 生成一个包含楼层的人脸id,解析楼层
// 使用48位源id, 其中前41位是imageid, 不可以修改  +99 + 3位楼层(第一位0表示正,1表示负) + 2位随机数
func GenerateFaceIdContainFloor(srcId, floorStr string) string {
    floorNum, _ := parseFloor(floorStr)
    newId := srcId[0:41] + "99" + floorNum + snowflake.CreateRandomNumber(2)
 
    return newId
}
 
func ParseFloorFromId(srcId string) (string, error) {
    if len(srcId) != 48 {
        return "", fmt.Errorf("invalid id %s", srcId)
    }
 
    if srcId[41:43] != "99" {
        return "", fmt.Errorf("invalid flag %s", srcId[41:43])
    }
 
    return restoreFloor(srcId[43:46])
}
 
// parseFloor parses the floor string and returns a three-character string
func parseFloor(floor string) (string, error) {
    var sign string
    var number string
 
    // Check if the floor is negative
    if strings.HasPrefix(floor, "-") {
        sign = "1"
        number = floor[1 : len(floor)-1]
    } else {
        sign = "0"
        number = floor[:len(floor)-1]
    }
 
    // Convert the number to an integer to validate and ensure it is a valid number
    if _, err := strconv.Atoi(number); err != nil {
        return "", err
    }
 
    // Format the number to be two digits
    formattedNumber := fmt.Sprintf("%02s", number)
 
    return sign + formattedNumber, nil
}
 
// restoreFloor restores the three-character string back to the original floor string
func restoreFloor(encoded string) (string, error) {
    if len(encoded) != 3 {
        return "", fmt.Errorf("encoded string must be 3 characters long")
    }
 
    sign := encoded[0]
    number := encoded[1:]
 
    // Convert the number back to integer to remove any leading zeros
    parsedNumber, err := strconv.Atoi(number)
    if err != nil {
        return "", err
    }
 
    var restoredFloor string
    if sign == '1' {
        restoredFloor = fmt.Sprintf("-%dF", parsedNumber)
    } else if sign == '0' {
        restoredFloor = fmt.Sprintf("%dF", parsedNumber)
    } else {
        return "", fmt.Errorf("invalid sign character in encoded string")
    }
 
    return restoredFloor, nil
}