...

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 2021 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  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  //
    15  
    16  package netutils
    17  
    18  import (
    19  	"crypto/sha256"
    20  	"fmt"
    21  	"log"
    22  )
    23  
    24  // CompressName compresses name to targetLength with specified postfix
    25  // targetLength < 7 or targetLength-7-len(namePostFix) < 0 are not allowed
    26  func CompressName(originalName string, targetLength int, namePostFix string) (name string) {
    27  	if targetLength < 7 {
    28  		log.Fatal("targetLength shouldn't be less than 7")
    29  	}
    30  	if targetLength-7-len(namePostFix) < 0 {
    31  		log.Fatalf("namePostFix longer than (targetLength-7) = %d: %s", targetLength-7, namePostFix)
    32  	}
    33  
    34  	if len(originalName) < 6 {
    35  		// len(originalName) < 6 && 7 + len(namePostFix) < targetlength
    36  		// => 1 + len(originalName) + len(namePostFix) < targetLength
    37  		name = originalName + "_" + namePostFix
    38  		return
    39  	}
    40  
    41  	namePrefix := originalName[0:5]
    42  	nameRest := originalName[5:]
    43  
    44  	hasher := sha256.New()
    45  	hasher.Write([]byte(nameRest))
    46  	hashValue := fmt.Sprintf("%x", hasher.Sum(nil))
    47  
    48  	// keep the length does not exceed targetLength
    49  	name = namePrefix + "_" + hashValue[0:targetLength-7-len(namePostFix)] + "_" + namePostFix
    50  
    51  	return
    52  }
    53