Skip to content

Commit

Permalink
#21 fixed
Browse files Browse the repository at this point in the history
  • Loading branch information
yegor256 committed Jul 15, 2024
1 parent b431f7a commit 431ca01
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
11 changes: 8 additions & 3 deletions lib/random-port/pool.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,14 @@ class Timeout < StandardError; end
attr_reader :limit

# Ctor.
# @param [bool] Set it to FALSE if you want this pool to be NOT thread-safe
# @param [int] Set the maximum number of ports in the pool
# @param [Boolean] sync Set it to FALSE if you want this pool to be NOT thread-safe
# @param [Integer] limit Set the maximum number of ports in the pool
def initialize(sync: true, limit: 65_536)
@ports = []
@sync = sync
@monitor = Monitor.new
@limit = limit
@next = 0
end

# Application wide pool of ports
Expand Down Expand Up @@ -96,7 +97,7 @@ def acquire(total = 1, timeout: 4)
opts = Array.new(0, total)
begin
(0..(total - 1)).each do |i|
opts[i] = i.zero? ? take : take(opts[i - 1] + 1)
opts[i] = take(i.zero? ? @next : opts[i - 1] + 1)
end
rescue Errno::EADDRINUSE, SocketError
next
Expand All @@ -108,6 +109,7 @@ def acquire(total = 1, timeout: 4)
opts
end
next if opts.nil?
@next = opts.max + 1
opts = opts[0] if total == 1
return opts unless block_given?
begin
Expand All @@ -131,6 +133,9 @@ def release(port)

private

# Find one possible TCP port.
# @param [Integer] opt Suggested port number
# @return [Integer] Port found
def take(opt = 0)
server = TCPServer.new('127.0.0.1', opt)
p = server.addr[1]
Expand Down
10 changes: 10 additions & 0 deletions test/test_pool.rb
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,16 @@ def test_acquires_unique_numbers
assert_equal(total, numbers.uniq.count)
end

def test_acquires_unique_numbers_in_block
total = 25
numbers = (0..total - 1).map do
RandomPort::Pool::SINGLETON.acquire do |port|
port
end
end
assert_equal(total, numbers.uniq.count)
end

def test_raises_when_too_many
pool = RandomPort::Pool.new(limit: 1)
pool.acquire
Expand Down

0 comments on commit 431ca01

Please sign in to comment.