github.com/pingcap/badger@v1.5.1-0.20230103063557-828f39b09b6d/cache/z/z.go (about)

     1  /*
     2   * Copyright 2019 Dgraph Labs, Inc. and Contributors
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package z
    18  
    19  import (
    20  	"github.com/cespare/xxhash/v2"
    21  )
    22  
    23  // TODO: Figure out a way to re-use memhash for the second uint64 hash, we
    24  //       already know that appending bytes isn't reliable for generating a
    25  //       second hash (see Ristretto PR #88).
    26  //
    27  //       We also know that while the Go runtime has a runtime memhash128
    28  //       function, it's not possible to use it to generate [2]uint64 or
    29  //       anything resembling a 128bit hash, even though that's exactly what
    30  //       we need in this situation.
    31  func KeyToHash(key interface{}) (uint64, uint64) {
    32  	if key == nil {
    33  		return 0, 0
    34  	}
    35  	switch k := key.(type) {
    36  	case uint64:
    37  		return k, 0
    38  	case string:
    39  		raw := []byte(k)
    40  		return MemHash(raw), xxhash.Sum64(raw)
    41  	case []byte:
    42  		return MemHash(k), xxhash.Sum64(k)
    43  	case byte:
    44  		return uint64(k), 0
    45  	case int:
    46  		return uint64(k), 0
    47  	case int32:
    48  		return uint64(k), 0
    49  	case uint32:
    50  		return uint64(k), 0
    51  	case int64:
    52  		return uint64(k), 0
    53  	default:
    54  		panic("Key type not supported")
    55  	}
    56  }