4fdc87a38c89208a303c6b4d093dfee19e62977e
[gsmperl.git] / GSM / SMS / NBS / Lib.pm
1 package GSM::SMS::NBS::Lib;
2
3 use strict;
4 use warnings;
5
6 require Exporter;
7 our @ISA=qw(Exporter);
8 our @EXPORT=qw(&dcs_to_bits &empty_subload &encode_payload &nail_payload_len &min);
9
10 use Carp;
11
12 use vars qw($VERSION);
13 $VERSION = '0.1';
14
15
16 sub dcs_to_bits {
17         my ($dcs) = @_;
18
19         return ($dcs & 0xF4)==0xF4 ? 8 : 7;
20 }
21
22 sub empty_subload {
23         my ($dcs, $freebytes) = @_;
24
25         return $freebytes if 8==dcs_to_bits($dcs);
26         # assumed 7==dcs_to_bits($dcs)
27         return int($freebytes*8/7);  # floor-rounding is the proper one
28 }
29
30 sub encode_payload {
31         my ($dcs, $payload) = @_;
32
33         return $payload if 8==dcs_to_bits($dcs);
34         # assumed 7==dcs_to_bits($dcs)
35
36         my $bits="";
37         $bits.=unpack("b7",$&) while ($payload=~s/^.//);
38         $bits.="0"x7; # trailing padding
39         my $r="";
40         $r.=pack("b8",$&) while ($bits=~s/^.{8}//);
41
42         return $r;
43 }
44
45 # returns length(encode_payload($dcs, "T"x$payload)) but it is more effective
46 sub nail_payload_len {
47         my ($dcs, $payload_len) = @_;
48
49         return $payload_len if 8==dcs_to_bits($dcs);
50         # assumed 7==dcs_to_bits($dcs)
51         return int(($payload_len*7+7)/8);
52 }
53
54 # Very common function but where is standardized?
55 sub min {
56         my $r = shift;
57
58         for (@_) {
59                 $r = $_ if $_ < $r;
60         }
61         return $r;
62 }
63
64 1;