summaryrefslogtreecommitdiff
path: root/lib/Thread/Queue/t/05_extract.t
blob: 8c2fb2f304e68f9abffa6ab91d25187608b71873 (plain)
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
use strict;
use warnings;

BEGIN {
    if ($ENV{'PERL_CORE'}){
        chdir('t');
        unshift(@INC, '../lib');
    }
    use Config;
    if (! $Config{'useithreads'}) {
        print("1..0 # Skip: Perl not compiled with 'useithreads'\n");
        exit(0);
    }
}

use threads;
use Thread::Queue;

if ($] == 5.008) {
    require 't/test.pl';   # Test::More work-alike for Perl 5.8.0
} else {
    require Test::More;
}
Test::More->import();
plan('tests' => 20);

my $q = Thread::Queue->new(1..10);
ok($q, 'New queue');

threads->create(sub {
    # Default count = 1
    is($q->extract(),   1, 'No args');          # 2..10 left
    is($q->extract(0),  2, 'Head');             # 3..10 left
    is($q->extract(5),  8, 'Pos index');        # 3..7,9,10 left
    is($q->extract(-3), 7, 'Neg index');        # 3..6,9,10 left
    my $x = $q->extract(20);                    # unchanged
    ok(! defined($x), 'Big index');
    $x = $q->extract(-20);                      # unchanged
    ok(! defined($x), 'Big neg index');
})->join();

$q = Thread::Queue->new(1..10);
ok($q, 'New queue');

threads->create(sub {
    my @x = $q->extract(0, 2);                  # 3..10 left
    is_deeply(\@x, [1,2], '2 from head');
    @x = $q->extract(6, 2);                     # 3..8 left
    is_deeply(\@x, [9,10], '2 from tail');
    @x = $q->extract(2, 2);                     # 3,4,7,8 left
    is_deeply(\@x, [5,6], '2 from middle');
    @x = $q->extract(2, 4);                     # 3,4 left
    is_deeply(\@x, [7,8], 'Lots from tail');
    @x = $q->extract(3, 4);                     # unchanged
    is_deeply(\@x, [], 'Too far');
})->join();

$q = Thread::Queue->new(1..10);
ok($q, 'New queue');

threads->create(sub {
    my @x = $q->extract(-4, 2);                 # 1..6,9,10 left
    is_deeply(\@x, [7,8], 'Neg index');
    @x = $q->extract(-2, 4);                    # 1..6 left
    is_deeply(\@x, [9,10], 'Lots from tail');
    @x = $q->extract(-6, 2);                    # 3..6 left
    is_deeply(\@x, [1,2], 'Max neg index');
    @x = $q->extract(-10, 3);                   # unchanged
    is_deeply(\@x, [], 'Too far');
    @x = $q->extract(-6, 3);                    # 4..6 left
    is_deeply(\@x, [3], 'Neg overlap');
    @x = $q->extract(-5, 10);                   # empty
    is_deeply(\@x, [4..6], 'Neg big overlap');
})->join();

# EOF