move the safe_string_ne and safe_num_ne functions to guesthelpers to remove duplicate code.
add the new safe_boolean_ne and typesafe_ne helper functions also add them in @EXPORT_OK Signed-off-by: Oguz Bektas <o.bek...@proxmox.com> --- v1->v2: * add new helpers to @EXPORT_OK for easy use * add a die to typesafe_ne for safe abort PVE/GuestHelpers.pm | 53 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/PVE/GuestHelpers.pm b/PVE/GuestHelpers.pm index 07a62ce..916f19f 100644 --- a/PVE/GuestHelpers.pm +++ b/PVE/GuestHelpers.pm @@ -9,11 +9,64 @@ use PVE::Storage; use POSIX qw(strftime); use Scalar::Util qw(weaken); +our @EXPORT_OK = qw(safe_string_ne safe_boolean_ne safe_num_ne typesafe_ne); + # We use a separate lock to block migration while a replication job # is running. our $lockdir = '/var/lock/pve-manager'; +# safe variable comparison functions + +sub safe_num_ne { + my ($a, $b) = @_; + + return 0 if !defined($a) && !defined($b); + return 1 if !defined($a); + return 1 if !defined($b); + + return $a != $b; +} + +sub safe_string_ne { + my ($a, $b) = @_; + + return 0 if !defined($a) && !defined($b); + return 1 if !defined($a); + return 1 if !defined($b); + + return $a ne $b; +} + +sub safe_boolean_ne { + my ($a, $b) = @_; + + # we don't check if value is defined, since undefined + # is false (so it's a valid boolean) + + # negate both values to normalize and compare + return !$a != !$b; +} + +sub typesafe_ne { + my ($a, $b, $type) = @_; + + return 0 if !defined($a) && !defined($b); + return 1 if !defined($a); + return 1 if !defined($b); + + if ($type eq 'string') { + return safe_string_ne($a, $b); + } elsif ($type eq 'number' || $type eq 'integer') { + return safe_num_ne($a, $b); + } elsif ($type eq 'boolean') { + return safe_boolean_ne($a, $b); + } + + die "internal error: can't compare $a and $b with type $type"; +} + + sub guest_migration_lock { my ($vmid, $timeout, $func, @param) = @_; -- 2.20.1 _______________________________________________ pve-devel mailing list pve-devel@pve.proxmox.com https://pve.proxmox.com/cgi-bin/mailman/listinfo/pve-devel