1 use std
::{convert::TryFrom, str::FromStr}
;
3 use crate::{oid, Kind, ObjectId}
;
5 impl TryFrom
<u8> for Kind
{
8 fn try_from(value
: u8) -> Result
<Self, Self::Error
> {
11 unknown
=> return Err(unknown
),
16 impl FromStr
for Kind
{
19 fn from_str(s
: &str) -> Result
<Self, Self::Err
> {
21 "sha1" | "SHA1" => Kind
::Sha1
,
22 other
=> return Err(other
.into()),
27 impl std
::fmt
::Display
for Kind
{
28 fn fmt(&self, f
: &mut std
::fmt
::Formatter
<'_
>) -> std
::fmt
::Result
{
30 Kind
::Sha1
=> f
.write_str("SHA1"),
36 /// Returns the shortest hash we support.
38 pub const fn shortest() -> Self {
42 /// Returns the longest hash we support.
44 pub const fn longest() -> Self {
48 /// Returns a buffer suitable to hold the longest possible hash in hex.
50 pub const fn hex_buf() -> [u8; Kind
::longest().len_in_hex()] {
51 [0u8; Kind
::longest().len_in_hex()]
54 /// Returns a buffer suitable to hold the longest possible hash as raw bytes.
56 pub const fn buf() -> [u8; Kind
::longest().len_in_bytes()] {
57 [0u8; Kind
::longest().len_in_bytes()]
60 /// Returns the amount of ascii-characters needed to encode this has in hex.
62 pub const fn len_in_hex(&self) -> usize {
67 /// Returns the amount of bytes taken up by the hash of the current kind.
69 pub const fn len_in_bytes(&self) -> usize {
75 /// Returns the kind of hash that would fit the given `hex_len`, or `None` if there is no fitting hash.
76 /// Note that 0 as `hex_len` fits always yields Sha1.
78 pub const fn from_hex_len(hex_len
: usize) -> Option
<Self> {
85 /// Converts a size in bytes as obtained by `Kind::len_in_bytes()` into the corresponding hash kind, if possible.
87 /// **Panics** if the hash length doesn't match a known hash.
89 /// NOTE that this method isn't public as it shouldn't be encouraged to assume all hashes have the same length.
90 /// However, if there should be such a thing, our `oid` implementation will have to become an enum and it's pretty breaking
91 /// to the way it's currently being used as auto-dereffing doesn't work anymore. Let's hope it won't happen.
92 // TODO: make 'const' once Rust 1.57 is more readily available in projects using 'gitoxide'.
94 pub(crate) fn from_len_in_bytes(bytes
: usize) -> Self {
97 _
=> panic
!("BUG: must be called only with valid hash lengths produced by len_in_bytes()"),
101 /// Create a null-id of our hash kind.
103 pub fn null_ref(&self) -> &'
static oid
{
105 Kind
::Sha1
=> oid
::null_sha1(),
109 /// Create a null-id of our hash kind.
111 pub const fn null(&self) -> ObjectId
{
113 Kind
::Sha1
=> ObjectId
::null_sha1(),