/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package pegasus

import (
	"encoding/binary"
	"hash/crc64"

	"github.com/apache/incubator-pegasus/go-client/idl/base"
)

func encodeHashKeySortKey(hashKey []byte, sortKey []byte) *base.Blob {
	hashKeyLen := len(hashKey)
	sortKeyLen := len(sortKey)

	blob := &base.Blob{
		Data: make([]byte, 2+hashKeyLen+sortKeyLen),
	}

	binary.BigEndian.PutUint16(blob.Data, uint16(hashKeyLen))

	if hashKeyLen > 0 {
		copy(blob.Data[2:], hashKey)
	}

	if sortKeyLen > 0 {
		copy(blob.Data[2+hashKeyLen:], sortKey)
	}

	return blob
}

func encodeNextBytesByKeys(hashKey []byte, sortKey []byte) *base.Blob {
	key := encodeHashKeySortKey(hashKey, sortKey)
	array := key.Data

	i := len(array) - 1
	for ; i >= 2; i-- {
		if array[i] != 0xFF {
			array[i]++
			break
		}
	}
	return &base.Blob{Data: array[:i+1]}
}

var crc64Table = crc64.MakeTable(0x9a6c9329ac4bc9b5)

func crc64Hash(data []byte) uint64 {
	return crc64.Checksum(data, crc64Table)
}
