| 1 | package Sidef::Types::Array::Pair; | ||
| 2 | |||
| 3 | use utf8; | ||
| 4 | use 5.016; | ||
| 5 | |||
| 6 | use parent qw( | ||
| 7 | Sidef::Types::Array::Array | ||
| 8 | ); | ||
| 9 | |||
| 10 | use overload q{""} => \&_dump; | ||
| 11 | |||
| 12 | sub new { | ||
| 13 | my (undef, $item1, $item2) = @_; | ||
| 14 | bless [$item1, $item2], __PACKAGE__; | ||
| 15 | } | ||
| 16 | |||
| 17 | *call = \&new; | ||
| 18 | |||
| 19 | sub get_value { | ||
| 20 | my %addr; | ||
| 21 | |||
| 22 | my $sub = sub { | ||
| 23 | my ($obj) = @_; | ||
| 24 | |||
| 25 | my $refaddr = Scalar::Util::refaddr($obj); | ||
| 26 | |||
| 27 | exists($addr{$refaddr}) | ||
| 28 | && return $addr{$refaddr}; | ||
| 29 | |||
| 30 | my @array; | ||
| 31 | $addr{$refaddr} = \@array; | ||
| 32 | |||
| 33 | foreach my $i (0, 1) { | ||
| 34 | my $item = $obj->[$i]; | ||
| 35 | |||
| 36 | if (index(ref($item), 'Sidef::') == 0) { | ||
| 37 | push @array, $item->get_value; | ||
| 38 | } | ||
| 39 | else { | ||
| 40 | push @array, $item; | ||
| 41 | } | ||
| 42 | } | ||
| 43 | |||
| 44 | $addr{$refaddr}; | ||
| 45 | }; | ||
| 46 | |||
| 47 | no warnings 'redefine'; | ||
| 48 | local *Sidef::Types::Array::Pair::get_value = $sub; | ||
| 49 | $sub->($_[0]); | ||
| 50 | } | ||
| 51 | |||
| 52 | sub first : lvalue { | ||
| 53 | $_[0][0]; | ||
| 54 | } | ||
| 55 | |||
| 56 | *key = \&first; | ||
| 57 | |||
| 58 | sub second : lvalue { | ||
| 59 | $_[0][1]; | ||
| 60 | } | ||
| 61 | |||
| 62 | *value = \&second; | ||
| 63 | |||
| 64 | sub swap { | ||
| 65 | my ($self) = @_; | ||
| 66 | ($self->[0], $self->[1]) = ($self->[1], $self->[0]); | ||
| 67 | $self; | ||
| 68 | } | ||
| 69 | |||
| 70 | sub to_hash { | ||
| 71 | my ($self) = @_; | ||
| 72 | Sidef::Types::Hash::Hash->new(@$self); | ||
| 73 | } | ||
| 74 | |||
| 75 | *to_h = \&to_hash; | ||
| 76 | |||
| 77 | sub to_array { | ||
| 78 | my ($self) = @_; | ||
| 79 | Sidef::Types::Array::Array->new(ref($self) ? [@$self] : $self); | ||
| 80 | } | ||
| 81 | |||
| 82 | *to_a = \&to_array; | ||
| 83 | |||
| 84 | sub _dump { | ||
| 85 | |||
| 86 | my %addr; # keeps track of dumped objects | ||
| 87 | |||
| 88 | my $sub = sub { | ||
| 89 | my ($obj) = @_; | ||
| 90 | |||
| 91 | my $refaddr = Scalar::Util::refaddr($obj); | ||
| 92 | |||
| 93 | exists($addr{$refaddr}) | ||
| 94 | and return $addr{$refaddr}; | ||
| 95 | |||
| 96 | $addr{$refaddr} = "Pair(#`($refaddr)...)"; | ||
| 97 | |||
| 98 | my $s; | ||
| 99 | |||
| 100 | 'Pair(' . join(', ', map { (ref($_) && ($s = UNIVERSAL::can($_, 'dump'))) ? $s->($_) : ($_ // 'nil') } @$obj) . ')'; | ||
| 101 | }; | ||
| 102 | |||
| 103 | no warnings 'redefine'; | ||
| 104 | local *Sidef::Types::Array::Pair::dump = $sub; | ||
| 105 | $sub->($_[0]); | ||
| 106 | } | ||
| 107 | |||
| 108 | sub dump { | ||
| 109 | Sidef::Types::String::String->new($_[0]->_dump); | ||
| 110 | } | ||
| 111 | |||
| 112 | *to_s = \&dump; | ||
| 113 | *to_str = \&dump; | ||
| 114 | |||
| 115 | 1 |