All pastes #1473227 Raw Edit

Untitled

public text v1 · immutable
#1473227 ·published 2009-06-24 21:00 UTC
rendered paste body
package ElasticFormatter;

my $filler = '[...]';

sub new
{
	my $class = shift;
	my ($prefix, $fields, $suffix) = @_;
	my $len = 400; # constant for now
	my @fields;

	$len -= length($prefix . $suffix);

	for my $f (@$fields) {
		my ($fpre, $fsuf) = @$f;
		$len -= length($fpre . $filler . $fsuf);
		push(@fields, ['', $fpre, $fsuf, 0]);
	}

	my $self = {'prefix' => $prefix, 'suffix' => $suffix, 'len' => $len, 'fields' => \@fields};
	return bless($self, $class);
}

sub str {
	my $self = shift;
	my $s = $self->{'prefix'};

	for my $f (@{$self->{'fields'}}) {
		$s .= $f[1] . $f[0] . $f[2];
	}

	$s .= $self->{'suffix'};

	return $s;
};

sub append
{
	my $self = shift;
	my ($n, $s, $whole) = @_;
	my $len = $self->{'len'};
	my $f = $self->{'fields'}->[$n];

	if ($f->[3] == 2) {
		die('Appending to finalised field.');
	}

	if ($len >= length($s)) {
		$f->[0] .= $s;
		$len -= length($s);
	} else {
		if (!$whole) {
			$f->[0] .= substr($s, 0, $len);
			$len = 0;
		}
		$f->[0] .= $filler;
		$f->[3] = 1;
	}

	$self->{'len'} = $len;
}

sub final
{
	my $self = shift;
	my $n = shift;
	my $f = $self->{'fields'}->$f;

	if (!$f->[3]) {
		$self->{'len'} += length($filler);
	}
}

use overload '""' => \&str;