Commit | Line | Data |
6fe26b29 |
1 | package DBM::Deep::Hash; |
2 | |
3 | use strict; |
4 | |
5 | use base 'DBM::Deep'; |
6 | |
596e9574 |
7 | sub _get_self { |
2ac02042 |
8 | eval { tied( %{$_[0]} ) } || $_[0] |
596e9574 |
9 | } |
10 | |
6fe26b29 |
11 | sub TIEHASH { |
12 | ## |
13 | # Tied hash constructor method, called by Perl's tie() function. |
14 | ## |
15 | my $class = shift; |
16 | my $args; |
217fef02 |
17 | if (scalar(@_) > 1) { |
18 | if ( @_ % 2 ) { |
19 | $class->_throw_error( "Odd number of parameters to TIEHASH" ); |
20 | } |
21 | $args = {@_}; |
22 | } |
e1b265cc |
23 | elsif ( my $type = Scalar::Util::reftype($_[0]) ) { |
24 | if ( $type ne 'HASH' ) { |
25 | $class->_throw_error( "Not a hashref in TIEHASH" ); |
26 | } |
27 | $args = $_[0]; |
28 | } |
6fe26b29 |
29 | else { $args = { file => shift }; } |
30 | |
31 | $args->{type} = $class->TYPE_HASH; |
32 | |
33 | return $class->_init($args); |
34 | } |
35 | |
81d3d316 |
36 | sub STORE { |
37 | my $self = shift->_get_self; |
38 | my $key = ($self->root->{filter_store_key}) |
39 | ? $self->root->{filter_store_key}->($_[0]) |
40 | : $_[0]; |
41 | my $value = $_[1]; |
42 | |
43 | return $self->SUPER::STORE( $key, $value ); |
44 | } |
45 | |
6fe26b29 |
46 | sub FIRSTKEY { |
47 | ## |
48 | # Locate and return first key (in no particular order) |
49 | ## |
2ac02042 |
50 | my $self = $_[0]->_get_self; |
6fe26b29 |
51 | |
52 | ## |
53 | # Make sure file is open |
54 | ## |
55 | if (!defined($self->fh)) { $self->_open(); } |
56 | |
57 | ## |
58 | # Request shared lock for reading |
59 | ## |
60 | $self->lock( $self->LOCK_SH ); |
61 | |
62 | my $result = $self->_get_next_key(); |
63 | |
64 | $self->unlock(); |
65 | |
66 | return ($result && $self->root->{filter_fetch_key}) |
67 | ? $self->root->{filter_fetch_key}->($result) |
68 | : $result; |
69 | } |
70 | |
71 | sub NEXTKEY { |
72 | ## |
73 | # Return next key (in no particular order), given previous one |
74 | ## |
2ac02042 |
75 | my $self = $_[0]->_get_self; |
6fe26b29 |
76 | |
77 | my $prev_key = ($self->root->{filter_store_key}) |
78 | ? $self->root->{filter_store_key}->($_[1]) |
79 | : $_[1]; |
80 | |
81 | my $prev_md5 = $DBM::Deep::DIGEST_FUNC->($prev_key); |
82 | |
83 | ## |
84 | # Make sure file is open |
85 | ## |
86 | if (!defined($self->fh)) { $self->_open(); } |
87 | |
88 | ## |
89 | # Request shared lock for reading |
90 | ## |
91 | $self->lock( $self->LOCK_SH ); |
92 | |
93 | my $result = $self->_get_next_key( $prev_md5 ); |
94 | |
95 | $self->unlock(); |
96 | |
97 | return ($result && $self->root->{filter_fetch_key}) |
98 | ? $self->root->{filter_fetch_key}->($result) |
99 | : $result; |
100 | } |
101 | |
102 | ## |
103 | # Public method aliases |
104 | ## |
105 | *first_key = *FIRSTKEY; |
106 | *next_key = *NEXTKEY; |
107 | |
108 | 1; |
109 | __END__ |