...

Source file src/github.com/chaos-mesh/chaos-mesh/controllers/podnetworkchaos/netutils/len.go

Documentation: github.com/chaos-mesh/chaos-mesh/controllers/podnetworkchaos/netutils

     1  // Copyright 2020 Chaos Mesh Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package netutils
    15  
    16  import (
    17  	"crypto/sha1"
    18  	"fmt"
    19  	"log"
    20  )
    21  
    22  // CompressName compresses name to targetLength with specified postfix
    23  // targetLength < 7 or targetLength-7-len(namePostFix) < 0 are not allowed
    24  func CompressName(originalName string, targetLength int, namePostFix string) (name string) {
    25  	if targetLength < 7 {
    26  		log.Fatal("targetLength shouldn't be less than 7")
    27  	}
    28  	if targetLength-7-len(namePostFix) < 0 {
    29  		log.Fatalf("namePostFix longer than (targetLength-7) = %d: %s", targetLength-7, namePostFix)
    30  	}
    31  
    32  	if len(originalName) < 6 {
    33  		// len(originalName) < 6 && 7 + len(namePostFix) < targetlength
    34  		// => 1 + len(originalName) + len(namePostFix) < targetLength
    35  		name = originalName + "_" + namePostFix
    36  		return
    37  	}
    38  
    39  	namePrefix := originalName[0:5]
    40  	nameRest := originalName[5:]
    41  
    42  	hasher := sha1.New()
    43  	hasher.Write([]byte(nameRest))
    44  	hashValue := fmt.Sprintf("%x", hasher.Sum(nil))
    45  
    46  	// keep the length does not exceed targetLength
    47  	name = namePrefix + "_" + hashValue[0:targetLength-7-len(namePostFix)] + "_" + namePostFix
    48  
    49  	return
    50  }
    51