# Copyright 1999-2016. Parallels IP Holdings GmbH. All Rights Reserved.
package PerlMD5;

use IPC::Run;
use AgentConfig;

#
# Tiny implementation of Digest::MD5 using external md5sum/md5 utility.
#
# It supports only 'new', 'add', 'hexdigest' methods and does not support
# functional interface.
#

use strict;

sub new {
  my $self = {};
  bless($self, shift);

  my $md5 = AgentConfig::md5Bin();
  return unless $md5;

  my @command = ($md5);

  $self->{input} = "";
  $self->{output} = "";

  $self->{sub} = IPC::Run::start(\@command, \$self->{input}, \$self->{output});

  return $self;
}

sub add {
  my $self = shift;

  $self->{input} = join "", @_;
  $self->{sub}->pump() while length($self->{input});
}

sub hexdigest {
  my ($self) = @_;

  $self->{sub}->finish();
  return (split/\s+/, $self->{output})[0];
}

#
# Test: must output
# 3858f62230ac3c915f300c664312c63f
# 18bfbff466f7fca739efb3ee3fa62cf2
# d41d8cd98f00b204e9800998ecf8427e
#
#
# $a = PerlMD5->new();
# $a->add("foobar");
# print $a->hexdigest() . "\n";
# $a = PerlMD5->new();
# $a->add("foobar", "\n", "bazbaz", "\n");
# print $a->hexdigest() . "\n";
# $a = PerlMD5->new();
# print $a->hexdigest() . "\n";
#

1;
