kraken

Форк
0
/
infohash.go 
63 строки · 1.7 Кб
1
// Copyright (c) 2016-2019 Uber Technologies, Inc.
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
package core
15

16
import (
17
	"crypto/sha1"
18
	"encoding/hex"
19
	"fmt"
20
)
21

22
// InfoHash is 20-byte SHA1 hash of the Info struct. It is the authoritative
23
// identifier for a torrent.
24
type InfoHash [20]byte
25

26
// NewInfoHashFromHex converts a hexidemical string into an InfoHash
27
func NewInfoHashFromHex(s string) (InfoHash, error) {
28
	if len(s) != 40 {
29
		return InfoHash{}, fmt.Errorf("invalid hash: expected 40 characters, got %d", len(s))
30
	}
31
	var h InfoHash
32
	n, err := hex.Decode(h[:], []byte(s))
33
	if err != nil {
34
		return InfoHash{}, fmt.Errorf("invalid hex: %s", err)
35
	}
36
	if n != 20 {
37
		return InfoHash{}, fmt.Errorf("invariant violation: expected 20 bytes, got %d", n)
38
	}
39
	return h, nil
40
}
41

42
// NewInfoHashFromBytes converts raw bytes to an InfoHash.
43
func NewInfoHashFromBytes(b []byte) InfoHash {
44
	var h InfoHash
45
	hasher := sha1.New()
46
	hasher.Write(b)
47
	copy(h[:], hasher.Sum(nil))
48
	return h
49
}
50

51
// Bytes converts h to raw bytes.
52
func (h InfoHash) Bytes() []byte {
53
	return h[:]
54
}
55

56
// Hex converts h into a hexidemical string.
57
func (h InfoHash) Hex() string {
58
	return hex.EncodeToString(h[:])
59
}
60

61
func (h InfoHash) String() string {
62
	return h.Hex()
63
}
64

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.