| 1 | # ABSTRACT: A libgit2 OID (20-byte SHA-1) | ||
| 2 | |||
| 3 | package Git::Native::Oid; | ||
| 4 | use Moo; | ||
| 5 | use Carp (); | ||
| 6 | use Git::Libgit2 qw( oid_from_hex oid_to_hex ); | ||
| 7 | use FFI::Platypus::Buffer qw( scalar_to_buffer ); | ||
| 8 | |||
| 9 | # Holds the raw 20-byte SHA. All other forms (hex, short, pointer) are | ||
| 10 | # derived. The scalar lives as long as the Oid object - that's the | ||
| 11 | # anchor libgit2 dereferences via the pointer we hand it. | ||
| 12 | has raw => ( | ||
| 13 | is => 'ro', | ||
| 14 | required => 1, | ||
| 15 | ); | ||
| 16 | |||
| 17 | sub from_hex { | ||
| 18 | my ( $class, $hex ) = @_; | ||
| 19 | return $class->new( raw => oid_from_hex($hex) ); | ||
| 20 | } | ||
| 21 | |||
| 22 | sub from_raw { | ||
| 23 | my ( $class, $raw ) = @_; | ||
| 24 | Carp::croak "raw OID must be 20 bytes" unless length($raw) == 20; | ||
| 25 | return $class->new( raw => $raw ); | ||
| 26 | } | ||
| 27 | |||
| 28 | # Construct from a pointer libgit2 returned (e.g. git_reference_target). | ||
| 29 | # We copy the 20 bytes out so the resulting Oid owns its memory and | ||
| 30 | # doesn't dangle when the source handle is freed. | ||
| 31 | sub from_ptr { | ||
| 32 | my ( $class, $ptr ) = @_; | ||
| 33 | Carp::croak "from_ptr: null pointer" unless $ptr; | ||
| 34 | require FFI::Platypus; | ||
| 35 | my $ffi = FFI::Platypus->new( api => 2 ); | ||
| 36 | my $copy = $ffi->cast( 'opaque', 'string(20)', $ptr ); | ||
| 37 | return $class->new( raw => $copy ); | ||
| 38 | } | ||
| 39 | |||
| 40 | sub hex { | ||
| 41 | my $self = shift; | ||
| 42 | my ($ptr) = scalar_to_buffer( $self->{raw} ); | ||
| 43 | return oid_to_hex($ptr); | ||
| 44 | } | ||
| 45 | |||
| 46 | sub short { | ||
| 47 | my ( $self, $n ) = @_; | ||
| 48 | $n //= 7; | ||
| 49 | return substr( $self->hex, 0, $n ); | ||
| 50 | } | ||
| 51 | |||
| 52 | sub ptr { | ||
| 53 | my $self = shift; | ||
| 54 | my ($p) = scalar_to_buffer( $self->{raw} ); | ||
| 55 | return $p; | ||
| 56 | } | ||
| 57 | |||
| 58 | use overload | ||
| 59 | '""' => sub { $_[0]->hex }, | ||
| 60 | 'eq' => sub { $_[0]->raw eq (ref $_[1] ? $_[1]->raw : $_[1]) }, | ||
| 61 | fallback => 1; | ||
| 62 | |||
| 63 | 1; | ||
| 64 | |||
| 65 | __END__ |