Aion-Format

 view release on metacpan or  search on metacpan

README.md  view on Meta::CPAN

## KiB ()

The constant is one kibibyte.

```perl
KiB  # -> 2**10
```

## xxL ()

Maximum length in data LongText mysql and mariadb.
L - large.

```perl
xxL  # -> 4*GiB-1
```

## xxM ()

Maximum length in data MediumText mysql and mariadb.
M - medium.

```perl
xxM  # -> 16*MiB-1
```

## xxR ()

Maximum length in data Text mysql and mariadb.
R - regularity.

```perl
xxR  # -> 64*KiB-1
```

## xxS ()

Maximum length in data TinyText mysql and mariadb.
S - small.

```perl
xxS  # -> 255
```

## to_str (;$scalar)

Converts to string perl without interpolation.

lib/Aion/Format.md  view on Meta::CPAN

## KiB ()

The constant is one kibibyte.

```perl
KiB  # -> 2**10
```

## xxL ()

Maximum length in data LongText mysql and mariadb.
L - large.

```perl
xxL  # -> 4*GiB-1
```

## xxM ()

Maximum length in data MediumText mysql and mariadb.
M - medium.

```perl
xxM  # -> 16*MiB-1
```

## xxR ()

Maximum length in data Text mysql and mariadb.
R - regularity.

```perl
xxR  # -> 64*KiB-1
```

## xxS ()

Maximum length in data TinyText mysql and mariadb.
S - small.

```perl
xxS  # -> 255
```

## to_str (;$scalar)

Converts to string perl without interpolation.

lib/Aion/Format.pm  view on Meta::CPAN

	"!\"#\$%&'()*+,./:;<=>?\@[\\]^`{|}~", # символы пунктуации ASCII
	" ", # пробел
	(map chr, 0 .. 0x1F, 0x7F), # управляющие символы ASCII
	# символ 152 (0x98) в cp1251 отсутствует.
;
# Переводит натуральное число в заданную систему счисления
sub to_radix($;$) {
	use bigint;
	my ($n, $radix) = @_;
	$radix //= 64;
	die "to_radix: The number system $radix is too large. Use NS before " . (1 + length $CIF) if $radix > length $CIF;
	$n+=0; $radix+=0;
	my $x = "";
	for(;;) {
		my $cif_idx = $n % $radix;
		my $cif = substr $CIF, $cif_idx, 1;
		$x =~ s/^/$cif/;
		last unless $n = int($n / $radix);
	}
	return $x;
}

# Парсит натуральное число в указанной системе счисления
sub from_radix(@) {
	use bigint;
	my ($s, $radix) = @_;
	$radix //= 64;
	$radix+=0;
	die "from_radix: The number system $radix is too large. Use NS before " . (1 + length $CIF) if $radix > length $CIF;
	my $x = 0;
	for my $ch (split "", $s) {
		$x = $x*$radix + index $CIF, $ch;
	}
	return $x;
}

# Округляет до указанного разряда числа
sub round($;$) {
	my ($x, $dec) = @_;

lib/Aion/Format.pm  view on Meta::CPAN


	return num(round($n)) . "b";
}

# Оставляет $n цифр до и после точки: 10.11 = 10, 0.00012 = 0.00012, 1.2345 = 1.2, если $n = 2
sub sround($;$) {
	my ($number, $digits) = @_;
	$digits //= 2;
	my $num = sprintf("%.100f", $number);
	$num =~ /^-?0?(\d*)\.(0*)[1-9]/;
	return "" . round($num, $digits + length $2) if length($1) == 0;
	my $k = $digits - length $1;
	return "" . round($num, $k < 0? 0: $k);
}

# Кибибайт
sub KiB() { 2**10 }

# Мебибайт
sub MiB() { 2**20 }

# Гибибайт

lib/Aion/Format.pm  view on Meta::CPAN

	MiB  # -> 2**20

=head2 KiB ()

The constant is one kibibyte.

	KiB  # -> 2**10

=head2 xxL ()

Maximum length in data LongText mysql and mariadb.
L - large.

	xxL  # -> 4*GiB-1

=head2 xxM ()

Maximum length in data MediumText mysql and mariadb.
M - medium.

	xxM  # -> 16*MiB-1

=head2 xxR ()

Maximum length in data Text mysql and mariadb.
R - regularity.

	xxR  # -> 64*KiB-1

=head2 xxS ()

Maximum length in data TinyText mysql and mariadb.
S - small.

	xxS  # -> 255

=head2 to_str (;$scalar)

Converts to string perl without interpolation.

	to_str "a'\n" # => 'a\\'\n'
	[map to_str, "a'\n"] # --> ["'a\\'\n'"]

lib/Aion/Format/Html.pm  view on Meta::CPAN

	my $re_proposal = qr/[.?!…]/;
	my @S;			# массив открывающих тегов [tag, '<tag ...>']

	# Функция фиксирует страницу и сбрасывает счётчики
	my $make_page = sub {
		push @pages, join "", @page, map { "</$_->[0]>" } reverse @S;
		$i_page = $c = $is_proposal = 0;
		@page = map $_->[1], @S;
	};
	
	for(grep length, split m{(
		<[a-z] [^<>]* >
		| </ \s* [a-z]\w* \s* >
		| &(?: [a-z]\w* | \# \d+ | \#x[0-9a-f]+ ) ;?
		| \n 		# Абзац
		| $re_proposal+	# Предложение
		| \b		# Слово
	)}xiu, $html) {

		if(/^&/) {$c++} 	# html-символ
		elsif(/^<\/\s*([a-z]\w*)/) { # закрывающий тег
			my $tag = lc $1;
			eval { out_tag @S, $tag };
			next if $@;
			# </p> превращаем в <p></p>
			$_ = "<p></p>" if $tag eq "p";
		}
		elsif(/^<([a-z]\w*)/) { in_tag @S, lc $1, $_ }	# тег
		else {$c += length}	# текст

		push @page, $_; # накапливаем символы в массиве @page

		next if $c < $symbols_on_page;	# страницу не набрали - тогда на next

		$c_page = $c, $i_page = @page if !$i_page;

		# Просматриваем вперёд пока не найдём границу или не достигнем ограничения
		if(/^\n/) { $make_page->() } 	# Абзац
		elsif(!$is_proposal && /^$re_proposal/) { $i_page = @page; $c_page = $c; $is_proposal = 1 }
		elsif($c >= $max) {
			# Если следующий за предложением или словом элемент - пробелы, то добавляем их к странице
			$c_page -= length $page[$i_page++] if $page[$i_page] =~ /^\s/;
			my @x = splice @page, $i_page;
			$make_page->();
			push @page, @x;
			$c -= $c_page;
		}
	}

	$make_page->() if @page;

	# Если размер последней страницы меньше чем 2/3, то добавляем её к предпоследней
	$pages[$#pages - 1] .= pop @pages if @pages > 1 and length($pages[$#pages]) < $symbols_on_page * 2 / 3;

	#my $len = 0; $len += length for @pages;
	#die "Суммарный размер страниц не изменился: " . length($html) . " == $len pages=" . @pages . " ->\n\n$html" if $len == length $html;

	my ($end1) = $html =~ m!([^<>\s]{1,13})\s*(</?\w[^<>]*>\s*)*$!a;
	my ($end2) = $pages[$#pages] =~ m!([^<>\s]{1,13})\s*(</?\w[^<>]*>\s*)*$!a;
	die "Концы текста и последней страницы не сходятся! `$end1` <> `$end2`" if $end1 ne $end2;

	return @pages;
}

our %TAG2SPACE = (
	"br" => "\n",

lib/Aion/Format/Url.pm  view on Meta::CPAN

		$link{path} = "/";
	} else { delete $link{path} }

	$link{orig} = $orig;
	$link{onpage} = $onpage;
	$link{link} = join "", $link{proto}, "://",
		exists $link{user} || exists $link{pass}? ($link{user},
			exists $link{pass}? ":$link{pass}": (), '@'): (),
		$link{dom},
		$link{path},
		length($link{query})? ("?", $link{query}): (),
		length($link{hash})? ("#", $link{hash}): (),
	;

	return \%link;
}

# Нормализует url
sub normalize_url($;$$) {
	parse_url($_[0], $_[1], $_[2])->{link}
}

t/aion/format.t  view on Meta::CPAN

use common::sense; use open qw/:std :utf8/; use Test::More 0.98; sub _mkpath_ { my ($p) = @_; length($`) && !-e $`? mkdir($`, 0755) || die "mkdir $`: $!": () while $p =~ m!/!g; $p } BEGIN { use Scalar::Util qw//; use Carp qw//; $SIG{__DIE__} = sub { ...
# 
# Aion::Format - Perl extension for formatting numbers, colorizing output and so on
# 
# # VERSION
# 
# 0.0.9
# 
# # SYNOPSIS
# 
subtest 'SYNOPSIS' => sub { 

t/aion/format.t  view on Meta::CPAN

# ## KiB ()
# 
# The constant is one kibibyte.
# 
done_testing; }; subtest 'KiB ()' => sub { 
::is scalar do {KiB}, scalar do{2**10}, 'KiB  # -> 2**10';

# 
# ## xxL ()
# 
# Maximum length in data LongText mysql and mariadb.
# L - large.
# 
done_testing; }; subtest 'xxL ()' => sub { 
::is scalar do {xxL}, scalar do{4*GiB-1}, 'xxL  # -> 4*GiB-1';

# 
# ## xxM ()
# 
# Maximum length in data MediumText mysql and mariadb.
# M - medium.
# 
done_testing; }; subtest 'xxM ()' => sub { 
::is scalar do {xxM}, scalar do{16*MiB-1}, 'xxM  # -> 16*MiB-1';

# 
# ## xxR ()
# 
# Maximum length in data Text mysql and mariadb.
# R - regularity.
# 
done_testing; }; subtest 'xxR ()' => sub { 
::is scalar do {xxR}, scalar do{64*KiB-1}, 'xxR  # -> 64*KiB-1';

# 
# ## xxS ()
# 
# Maximum length in data TinyText mysql and mariadb.
# S - small.
# 
done_testing; }; subtest 'xxS ()' => sub { 
::is scalar do {xxS}, scalar do{255}, 'xxS  # -> 255';

# 
# ## to_str (;$scalar)
# 
# Converts to string perl without interpolation.
# 

t/aion/format/html.t  view on Meta::CPAN

use common::sense; use open qw/:std :utf8/; use Test::More 0.98; sub _mkpath_ { my ($p) = @_; length($`) && !-e $`? mkdir($`, 0755) || die "mkdir $`: $!": () while $p =~ m!/!g; $p } BEGIN { use Scalar::Util qw//; use Carp qw//; $SIG{__DIE__} = sub { ...
# 
# Aion::Format::Html - Perl extension for formatting HTML
# 
# # SYNOPSIS
# 
subtest 'SYNOPSIS' => sub { 
use Aion::Format::Html;

::is scalar do {from_html "<b>&excl;</b>"}, "!", 'from_html "<b>&excl;</b>"  # => !';
::is scalar do {to_html "<a>"}, "&lt;a&gt;", 'to_html "<a>"       # => &lt;a&gt;';

t/aion/format/json.t  view on Meta::CPAN

use common::sense; use open qw/:std :utf8/; use Test::More 0.98; sub _mkpath_ { my ($p) = @_; length($`) && !-e $`? mkdir($`, 0755) || die "mkdir $`: $!": () while $p =~ m!/!g; $p } BEGIN { use Scalar::Util qw//; use Carp qw//; $SIG{__DIE__} = sub { ...
# 
# Aion::Format::Json - Perl extension for formatting JSON
# 
# # SYNOPSIS
# 
subtest 'SYNOPSIS' => sub { 
use Aion::Format::Json;

::is scalar do {to_json {a => 10}}, "{\n   \"a\": 10\n}\n", 'to_json {a => 10}    # => {\n   "a": 10\n}\n';
::is_deeply scalar do {from_json '[1, "5"]'}, scalar do {[1, "5"]}, 'from_json \'[1, "5"]\' # --> [1, "5"]';

t/aion/format/url.t  view on Meta::CPAN

use common::sense; use open qw/:std :utf8/; use Test::More 0.98; sub _mkpath_ { my ($p) = @_; length($`) && !-e $`? mkdir($`, 0755) || die "mkdir $`: $!": () while $p =~ m!/!g; $p } BEGIN { use Scalar::Util qw//; use Carp qw//; $SIG{__DIE__} = sub { ...
# 
# Aion::Format::Url - the utitlities for encode and decode the urls
# 
# # SYNOPSIS
# 
subtest 'SYNOPSIS' => sub { 
use Aion::Format::Url;

::is scalar do {to_url_params {a => 1, b => [[1,2],3,{x=>10}]}}, "a&b[][]&b[][]=2&b[]=3&b[][x]=10", 'to_url_params {a => 1, b => [[1,2],3,{x=>10}]} # => a&b[][]&b[][]=2&b[]=3&b[][x]=10';



( run in 0.290 second using v1.01-cache-2.11-cpan-65fba6d93b7 )