File: Hash.pm

package info (click to toggle)
libsub-handlesvia-perl 0.052000-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,740 kB
  • sloc: perl: 9,645; makefile: 2
file content (438 lines) | stat: -rw-r--r-- 13,971 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
use 5.008;
use strict;
use warnings;

package Sub::HandlesVia::HandlerLibrary::Hash;

our $AUTHORITY = 'cpan:TOBYINK';
our $VERSION   = '0.052000';

use Sub::HandlesVia::HandlerLibrary;
our @ISA = 'Sub::HandlesVia::HandlerLibrary';

use Sub::HandlesVia::Handler qw( handler );
use Types::Standard qw( HashRef ArrayRef Optional Str CodeRef Item Any Ref Defined RegexpRef );

our @METHODS = qw( all accessor clear count defined delete elements exists get
	is_empty keys kv set shallow_clone values sorted_keys reset delete_where
	for_each_key for_each_value for_each_pair );

sub _type_inspector {
	my ($me, $type) = @_;
	if ($type == HashRef or $type == Ref or $type == Ref['HASH']) {
		return {
			trust_mutated => 'always',
		};
	}
	if ($type->is_parameterized and $type->parent->name eq 'HashRef' and $type->parent->library eq 'Types::Standard') {
		return {
			trust_mutated => 'maybe',
			value_type    => $type->type_parameter,
			key_type      => Str,
		};
	}
	if ($type->is_parameterized and $type->parent->name eq 'Map' and $type->parent->library eq 'Types::Standard') {
		return {
			trust_mutated => 'maybe',
			value_type    => $type->parameters->[1],
			key_type      => $type->parameters->[0],
		};
	}
	return $me->SUPER::_type_inspector($type);
}

my $additional_validation_for_set_and_insert = sub {
	my $self = CORE::shift;
	my ($sig_was_checked, $gen) = @_;
	my $ti = __PACKAGE__->_type_inspector($gen->isa);
	
	if ($ti and $ti->{trust_mutated} eq 'always') {
		return { code => '1;', env => {} };
	}
	if ($ti and $ti->{trust_mutated} eq 'maybe') {
		my ( $env, $code, $arg );
		$env = {};
		$arg = sub {
			my $gen = shift;
			return '$shv_key'   if $_[0]=='1';
			return '$shv_value' if $_[0]=='2';
			$gen->generate_arg( @_ );
		};
		$code = sprintf(
			'my($shv_key,$shv_value)=%s; if (%s>0) { %s }; if (%s>1) { %s };',
			$gen->generate_args,
			$gen->generate_argc,
			$gen->generate_type_assertion( $env, $ti->{key_type} || Str, '$shv_key' ),
			$gen->generate_argc,
			$gen->generate_type_assertion( $env, $ti->{value_type}, '$shv_value' ),
		);
		return {
			code => $code,
			env => $env,
			arg => $arg,
		};
	}
	return;
};


sub count {
	handler
		name      => 'Hash:count',
		args      => 0,
		template  => 'scalar keys %{$GET}',
		documentation => 'Returns the number of keys in the hash.',
		_examples => sub {
			my ( $class, $attr, $method ) = @_;
			return join "",
				"  my \$object = $class\->new( $attr => { foo => 0, bar => 1 } );\n",
				"  say \$object->$method; ## ==> 2\n",
				"\n";
		},
}

sub is_empty {
	handler
		name      => 'Hash:is_empty',
		args      => 0,
		template  => '!scalar keys %{$GET}',
		documentation => 'Returns true iff there are no keys in the hash.',
		_examples => sub {
			my ( $class, $attr, $method ) = @_;
			return join "",
				"  my \$object = $class\->new( $attr => { foo => 0, bar => 1 } );\n",
				"  say \$object->$method; ## ==> false\n",
				"  \$object->_set_$attr( {} );\n",
				"  say \$object->$method; ## ==> true\n",
				"\n";
		},
}

sub keys {
	handler
		name      => 'Hash:keys',
		args      => 0,
		template  => 'keys %{$GET}',
		documentation => 'Returns the list of keys in the hash.',
		_examples => sub {
			my ( $class, $attr, $method ) = @_;
			return join "",
				"  my \$object = $class\->new( $attr => { foo => 0, bar => 1 } );\n",
				"  # says 'foo' and 'bar' in an unpredictable order\n",
				"  say for \$object->$method;\n",
				"\n";
		},
}

sub sorted_keys {
	handler
		name      => 'Hash:sorted_keys',
		args      => 0,
		template  => 'sort(keys %{$GET})',
		documentation => 'Returns an alphabetically sorted list of keys in the hash.',
		_examples => sub {
			my ( $class, $attr, $method ) = @_;
			return join "",
				"  my \$object = $class\->new( $attr => { foo => 0, bar => 1 } );\n",
				"  # says 'bar' then 'foo'\n",
				"  say for \$object->$method;\n",
				"\n";
		},
}

sub values {
	handler
		name      => 'Hash:values',
		args      => 0,
		template  => 'values %{$GET}',
		documentation => 'Returns the list of values in the hash.',
		_examples => sub {
			my ( $class, $attr, $method ) = @_;
			return join "",
				"  my \$object = $class\->new( $attr => { foo => 0, bar => 1 } );\n",
				"  # says '0' and '1' in an unpredictable order\n",
				"  say for \$object->$method;\n",
				"\n";
		},
}

sub all {
	handler
		name      => 'Hash:all',
		args      => 0,
		template  => '%{$GET}',
		documentation => 'Returns the hash in list context.',
		_examples => sub {
			my ( $class, $attr, $method ) = @_;
			return join "",
				"  my \$object = $class\->new( $attr => { foo => 0, bar => 1 } );\n",
				"  my \%hash = \$object->$method;\n",
				"\n";
		},
}

sub elements {
	handler
		name      => 'Hash:elements',
		args      => 0,
		template  => '%{$GET}',
		documentation => 'Returns the hash in list context.',
		_examples => sub {
			my ( $class, $attr, $method ) = @_;
			return join "",
				"  my \$object = $class\->new( $attr => { foo => 0, bar => 1 } );\n",
				"  my \%hash = \$object->$method;\n",
				"\n";
		},
}

sub kv {
	handler
		name      => 'Hash:kv',
		args      => 0,
		template  => 'map [ $_ => ($GET)->{$_} ], keys %{$GET}',
		documentation => 'Returns a list of arrayrefs, where each arrayref is a key-value pair.',
}

sub get {
	handler
		name      => 'Hash:get',
		min_args  => 1,
		usage     => '$key',
		prefer_shift_self => 1,
		template  => '#ARG>1 ? @{$GET}{@ARG} : ($GET)->{$ARG}',
		documentation => 'Returns a value from the hashref by its key.',
		_examples => sub {
			my ( $class, $attr, $method ) = @_;
			return join "",
				"  my \$object = $class\->new( $attr => { foo => 0, bar => 1 } );\n",
				"  say \$object->$method( 'bar' ); ## ==> 1\n",
				"\n";
		},
}

sub defined {
	handler
		name      => 'Hash:defined',
		args      => 1,
		signature => [Str],
		usage     => '$key',
		template  => 'defined(($GET)->{$ARG})',
		documentation => 'Indicates whether a value exists and is defined in the hashref by its key.',
		_examples => sub {
			my ( $class, $attr, $method ) = @_;
			return join "",
				"  my \$object = $class\->new( $attr => { foo => 0, bar => 1 } );\n",
				"  say \$object->$method( 'foo' ); ## ==> 1\n",
				"\n";
		},
}

sub exists {
	handler
		name      => 'Hash:exists',
		args      => 1,
		signature => [Str],
		usage     => '$key',
		template  => 'exists(($GET)->{$ARG})',
		documentation => 'Indicates whether a value exists in the hashref by its key.',
		_examples => sub {
			my ( $class, $attr, $method ) = @_;
			return join "",
				"  my \$object = $class\->new( $attr => { foo => 0, bar => 1 } );\n",
				"  say \$object->$method( 'foo' ); ## ==> true\n",
				"  say \$object->$method( 'baz' ); ## ==> false\n",
				"\n";
		},
}

sub delete {
	handler
		name      => 'Hash:delete',
		min_args  => 1,
		usage     => '$key',
		template  => 'my %shv_tmp = %{$GET}; my @shv_return = delete @shv_tmp{@ARG}; «\%shv_tmp»; wantarray ? @shv_return : $shv_return[-1]',
		lvalue_template  => 'delete(@{$GET}{@ARG})',
		prefer_shift_self => 1,
		additional_validation => 'no incoming values',
		documentation => 'Removes a value from the hashref by its key.',
		_examples => sub {
			my ( $class, $attr, $method ) = @_;
			return join "",
				"  my \$object = $class\->new( $attr => { foo => 0, bar => 1 } );\n",
				"  \$object->$method( 'foo' );\n",
				"  say exists \$object->$attr\->{foo}; ## ==> false\n",
				"\n";
		},
}

sub delete_where {
	handler
		name      => 'Hash:delete_where',
		min_args  => 1,
		usage     => '$match',
		signature => [ CodeRef | RegexpRef ],
		template  => 'my %shv_tmp = %{$GET}; my $shv_match = $ARG; my @shv_keys = ("CODE" eq ref $shv_match) ? grep($shv_match->($_), keys %shv_tmp) : grep(/$shv_match/, keys %shv_tmp); my @shv_return = delete @shv_tmp{@shv_keys}; «\%shv_tmp»; wantarray ? @shv_return : $shv_return[-1]',
		prefer_shift_self => 1,
		documentation => 'Removes values from the hashref by matching keys against a coderef or regexp.',
		_examples => sub {
			my ( $class, $attr, $method ) = @_;
			return join "",
				"  my \$object = $class\->new( $attr => { foo => 0, bar => 1, baz => 2 } );\n",
				"  \$object->$method( sub { \$_ eq 'foo' or \$_ eq 'bar' } );\n",
				"  say Dumper( \$object->$attr ); ## ==> { baz => 2 }\n",
				"  \n",
				"  my \$object2 = $class\->new( $attr => { foo => 0, bar => 1, baz => 2 } );\n",
				"  \$object2->$method( qr/^b/ );\n",
				"  say Dumper( \$object2->$attr ); ## ==> { foo => 0 }\n",
				"\n";
		},
}

sub clear {
	handler
		name      => 'Hash:clear',
		args      => 0,
		template  => '«{}»',
		lvalue_template => '%{$GET} = ()',
		additional_validation => 'no incoming values',
		documentation => 'Empties the hash.',
		_examples => sub {
			my ( $class, $attr, $method ) = @_;
			return join "",
				"  my \$object = $class\->new( $attr => { foo => 0, bar => 1 } );\n",
				"  \$object->$method;\n",
				"  say exists \$object->$attr\->{foo}; ## ==> false\n",
				"  say exists \$object->$attr\->{bar}; ## ==> false\n",
				"\n";
		},
}

sub shallow_clone {
	handler
		name      => 'Hash:shallow_clone',
		args      => 0,
		template  => '+{%{$GET}}',
		documentation => 'Creates a new hashref with the same keys and values as the original.',
}

sub set {
	my $me = CORE::shift;
	handler
		name      => 'Hash:set',
		min_args  => 2,
		usage     => '$key, $value, ...',
		prefer_shift_self => 1,
		template  => (
			'my (@shv_params) = @ARG; ' .
			'scalar(@shv_params) % 2 and ⸨"Wrong number of parameters; expected even-sized list of keys and values"⸩;' .
			'my (@shv_keys_idx) = grep(!($_ % 2), 0..$#shv_params); ' .
			'my (@shv_values_idx) = grep(($_ % 2), 0..$#shv_params); ' .
			'grep(!defined, @shv_params[@shv_keys_idx]) and ⸨"Undef did not pass type constraint; keys must be defined"⸩;'.
			'"____VALIDATION_HERE____"; '.
			'my %shv_tmp = %{$GET}; @shv_tmp{@shv_params[@shv_keys_idx]} = @shv_params[@shv_values_idx]; «\\%shv_tmp»;' .
			'wantarray ? @shv_tmp{@shv_params[@shv_keys_idx]} : $shv_tmp{$shv_params[$shv_keys_idx[0]]}' ),
		lvalue_template  => (
			'my (@shv_params) = @ARG; ' .
			'scalar(@shv_params) % 2 and ⸨"Wrong number of parameters; expected even-sized list of keys and values"⸩;' .
			'my (@shv_keys_idx) = grep(!($_ % 2), 0..$#shv_params); ' .
			'my (@shv_values_idx) = grep(($_ % 2), 0..$#shv_params); ' .
			'grep(!defined, @shv_params[@shv_keys_idx]) and ⸨"Undef did not pass type constraint; keys must be defined"⸩;'.
			'"____VALIDATION_HERE____"; '.
			'@{$GET}{@shv_params[@shv_keys_idx]} = @shv_params[@shv_values_idx];' .
			'wantarray ? @{$GET}{@shv_params[@shv_keys_idx]} : ($GET)->{$shv_params[$shv_keys_idx[0]]}' ),
		additional_validation => sub {
			my $self = CORE::shift;
			my ($sig_was_checked, $gen) = @_;
			my $ti = __PACKAGE__->_type_inspector($gen->isa);
			my $env = {};
			if ($ti and $ti->{trust_mutated} eq 'always') {
				# still need to check keys are strings
				return {
					code => sprintf(
						'for my $shv_tmp (@shv_keys_idx) { %s };',
						$gen->generate_type_assertion( $env, Str, '$shv_params[$shv_tmp]' ),
					),
					env => $env,
					add_later => 1,
				};
			}
			if ($ti and $ti->{trust_mutated} eq 'maybe') {
				return {
					code => sprintf(
						'for my $shv_tmp (@shv_keys_idx) { %s }; for my $shv_tmp (@shv_values_idx) { %s };',
						$gen->generate_type_assertion( $env, $ti->{key_type}, '$shv_params[$shv_tmp]' ),
						$gen->generate_type_assertion( $env, $ti->{value_type}, '$shv_params[$shv_tmp]' ),
					),
					env => $env,
					add_later => 1,
				};
			}
			return;
		},
		documentation => 'Given a key and value, adds the key to the hashref with the given value.',
		_examples => sub {
			my ( $class, $attr, $method ) = @_;
			return join "",
				"  my \$object = $class\->new( $attr => { foo => 0, bar => 1 } );\n",
				"  \$object->$method( bar => 2, baz => 1 );\n",
				"  say \$object->$attr\->{foo}; ## ==> 0\n",
				"  say \$object->$attr\->{baz}; ## ==> 1\n",
				"  say \$object->$attr\->{bar}; ## ==> 2\n",
				"\n";
		},
}

sub accessor {
	handler
		name      => 'Hash:accessor',
		min_args  => 1,
		max_args  => 2,
		signature => [Str, Optional[Any]],
		usage     => '$key, $value?',
		template  => 'if (#ARG == 1) { ($GET)->{ $ARG[1] } } else { my %shv_tmp = %{$GET}; $shv_tmp{$ARG[1]} = $ARG[2]; «\\%shv_tmp» }',
		lvalue_template => '(#ARG == 1) ? ($GET)->{ $ARG[1] } : (($GET)->{ $ARG[1] } = $ARG[2])',
		additional_validation => $additional_validation_for_set_and_insert,
		documentation => 'Acts like C<get> if given just a key, or C<set> if given a key and a value.',
}

sub for_each_pair {
	handler
		name      => 'Hash:for_each_pair',
		args      => 1,
		signature => [CodeRef],
		usage     => '$coderef',
		template  => 'while (my ($shv_key,$shv_value)=each %{$GET}) { &{$ARG}($shv_key,$shv_value) }; $SELF',
		documentation => 'Chainable method which calls the coderef for each key in the hash, passing the key and value to the coderef.',
}

sub for_each_key {
	handler
		name      => 'Hash:for_each_key',
		args      => 1,
		signature => [CodeRef],
		usage     => '$coderef',
		template  => 'for (keys %{$GET}) { &{$ARG}($_) }; $SELF',
		documentation => 'Chainable method which calls the coderef for each key in the hash, passing just the key to the coderef. The key will also be available as C<< $_ >>.',
}

sub for_each_value {
	handler
		name      => 'Hash:for_each_value',
		args      => 1,
		signature => [CodeRef],
		usage     => '$coderef',
		template  => 'for (values %{$GET}) { &{$ARG}($_) }; $SELF',
		documentation => 'Chainable method which calls the coderef for each value in the hash, passing just the value to the coderef. The value will also be available as C<< $_ >>.',
}

sub reset {
	handler
		name      => 'Hash:reset',
		args      => 0,
		template  => '« $DEFAULT »',
		default_for_reset => sub { '{}' },
		documentation => 'Resets the attribute to its default value, or an empty hashref if it has no default.',
}

1;