Skip to content

Commit

Permalink
Add extlib::compare_ip() function
Browse files Browse the repository at this point in the history
This function is to be used with the built-in `sort()` function.
  • Loading branch information
jay7x committed Mar 31, 2024
1 parent 4b938f9 commit 839b8d4
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
23 changes: 23 additions & 0 deletions lib/puppet/functions/extlib/compare_ip.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# frozen_string_literal: true

require 'ipaddr'

# A function that compares two IP addresses. To be used with the built-in sort()
# function.
Puppet::Functions.create_function(:'extlib::compare_ip') do
# @param a First value
# @param b Second value
# @return -1, 0 or 1 if first value is lesser, equal or greater than second value
# @example Sorting the array of IP addresses
# $ip_addresses = ['10.1.1.1', '10.10.1.1', '10.2.1.1']
# $ip_addresses.sort |$a, $b| { extlib::compare_ip($a, $b) }
dispatch :compare_ip do
param 'String[1]', :left
param 'String[1]', :right
return_type 'Integer[-1,1]'
end

def compare_ip(left, right)
IPAddr.new(left).to_i <=> IPAddr.new(right).to_i
end
end
21 changes: 21 additions & 0 deletions spec/functions/extlib/compare_ip_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# frozen_string_literal: true

require 'spec_helper'

describe 'extlib::compare_ip' do
it 'exists' do
is_expected.not_to be_nil
end

it { is_expected.to run.with_params('10.1.1.1', '10.2.1.1').and_return(-1) }
it { is_expected.to run.with_params('10.2.1.1', '10.2.1.1').and_return(0) }
it { is_expected.to run.with_params('10.10.1.1', '10.2.1.1').and_return(1) }

it { is_expected.to run.with_params('fe80::1', 'fe80::2').and_return(-1) }
it { is_expected.to run.with_params('fe80::2', 'fe80::2').and_return(0) }
it { is_expected.to run.with_params('fe80::10', 'fe80::2').and_return(1) }

it { is_expected.to run.with_params('0::ffff:fffe', '255.255.255.255').and_return(-1) }
it { is_expected.to run.with_params('0::ffff:ffff', '255.255.255.255').and_return(0) }
it { is_expected.to run.with_params('0::1:0:0', '255.255.255.255').and_return(1) }
end

0 comments on commit 839b8d4

Please sign in to comment.