File: Record.pm

package info (click to toggle)
libffi-platypus-perl 2.10-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,860 kB
  • sloc: perl: 7,388; ansic: 6,862; cpp: 53; sh: 19; makefile: 14
file content (575 lines) | stat: -rw-r--r-- 12,008 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
package FFI::Platypus::Record;

use strict;
use warnings;
use 5.008004;
use Carp qw( croak );
use FFI::Platypus;
use Exporter qw( import );
use constant 1.32 ();

our @EXPORT = qw( record_layout record_layout_1 );

# ABSTRACT: FFI support for structured records data
our $VERSION = '2.10'; # VERSION


sub record_layout_1
{
  if(@_ % 2 == 0)
  {
    my $ffi = FFI::Platypus->new( api => 2);
    unshift @_, $ffi;
    goto &record_layout;
  }
  elsif(defined $_[0] && ref($_[0]) eq 'ARRAY')
  {
    my @args = @{ shift @_ };
    unshift @args, api => 2;
    unshift @_, \@args;
    goto &record_layout;
  }
  elsif(defined $_[0] && eval { $_[0]->isa('FFI::Platypus') })
  {
    goto &record_layout;
  }
  else
  {
    croak "odd number of arguments, but first argument is not either an array reference or Platypus instance";
  }
}


sub record_layout
{
  my $ffi;

  if(defined $_[0])
  {
    if(ref($_[0]) eq 'ARRAY')
    {
      my @args = @{ shift() };
      $ffi = FFI::Platypus->new(@args);
    }
    elsif(eval { $_[0]->isa('FFI::Platypus') })
    {
      $ffi = shift;
    }
  }

  $ffi ||= FFI::Platypus->new;

  my $offset = 0;
  my $record_align = 0;

  croak "uneven number of arguments!" if scalar(@_) % 2;

  my($caller, $filename, $line) = caller;

  if($caller->can("_ffi_record_size")
  || $caller->can("ffi_record_size"))
  {
    croak "record already defined for the class $caller";
  }

  my @destroy;
  my @ffi_types;
  my $has_string;

  while(@_)
  {
    my $spec = shift;
    my $name = shift;
    my $type = $ffi->{tp}->parse( $spec, { member => 1 } );

    croak "illegal name $name"
      unless $name =~ /^[A-Za-z_][A-Za-z_0-9]*$/
      ||     $name eq ':';
    croak "accessor/method $name already exists"
      if $caller->can($name);

    my $size      = $type->sizeof;
    my $align     = $type->alignof;
    $record_align = $align if $align > $record_align;
    my $meta      = $type->meta;

    $offset++ while $offset % $align;

    {
      my $count;
      my $ffi_type;

      if($meta->{type} eq 'record') # this means fixed string atm
      {
        $ffi_type = 'sint8';
        $count = $size;
      }
      else
      {
        $ffi_type = $meta->{ffi_type};
        $count    = $meta->{element_count};
        $count    = 1 unless defined $count;

        $has_string = 1 if $meta->{type} eq 'string';
      }
      push @ffi_types, $ffi_type for 1..$count;
    }

    if($name ne ':')
    {

      if($meta->{type} eq 'string'
      && $meta->{access} eq 'rw')
      {
        push @destroy, eval '# line '. __LINE__ . ' "' . __FILE__ . qq("\n) .qq{
          sub {
            shift->$name(undef);
          };
        };
        die $@ if $@;
      }

      my $full_name = join '::', $caller, $name;
      my $error_str = _accessor
        $full_name,
        "$filename:$line",
        $type,
        $offset;
      croak("$error_str ($spec $name)") if $error_str;
    };

    $offset += $size;
  }

  my $size = $offset;

  no strict 'refs';
  constant->import("${caller}::_ffi_record_size", $size);
  constant->import("${caller}::_ffi_record_align", $record_align);
  *{join '::', $caller, '_ffi_record_ro'} = \&_ffi_record_ro;
  *{join '::', $caller, 'new'} = sub {
    my $class = shift;
    my $args = ref($_[0]) ? [%{$_[0]}] : \@_;
    croak "uneven number of arguments to record constructor"
      if @$args % 2;
    my $record = "\0" x $class->_ffi_record_size;
    my $self = bless \$record, $class;

    while(@$args)
    {
      my $key = shift @$args;
      my $value = shift @$args;
      $self->$key($value);
    }

    $self;
  };

  {
    require FFI::Platypus::Record::Meta;
    my $ffi_meta = FFI::Platypus::Record::Meta->new(
      \@ffi_types,
      !$has_string,
    );
    *{join '::', $caller, '_ffi_meta'} = sub { $ffi_meta };
  }

  my $destroy_sub = sub {};

  if(@destroy)
  {
    $destroy_sub = sub {
      return if _ffi_record_ro($_[0]);
      $_->($_[0]) for @destroy;
    };
  }
  do {
    no strict 'refs';
    *{"${caller}::DESTROY"} = $destroy_sub;
  };
  ();
}

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

FFI::Platypus::Record - FFI support for structured records data

=head1 VERSION

version 2.10

=head1 SYNOPSIS

C:

 struct my_person {
   int         age;
   const char  title[3];
   const char *name
 };
 
 void process_person(struct my_person *person)
 {
   /* ... */
 }

Perl:

 package MyPerson;
 
 use FFI::Platypus::Record;
 
 record_layout_1(
   'int'       => 'age',
   'string(3)' => 'title',
   'string rw' => 'name',
 );
 
 package main;
 
 use FFI::Platypus 2.00;
 
 my $ffi = FFI::Platypus->new( api => 2 );
 $ffi->lib("myperson.so");
 $ffi->type("record(MyPerson)" => 'MyPerson');
 
 my $person = MyPerson->new(
   age   => 40,
   title => "Mr.",
   name  => "John Smith",
 );
 
 $ffi->attach( process_person => [ 'MyPerson*' ] => 'void' );
 
 process_person($person);
 
 $person->age($person->age + 1); # another year older
 
 process_person($person);

=head1 DESCRIPTION

[version 0.21]

This module provides a mechanism for building classes that can be used
to mange structured data records (known as C as "structs" and in some
languages as "records").  A structured record is a series of bytes that
have structure understood by the C or other foreign language library
that you are interfacing with.  It is designed for use with FFI and
L<FFI::Platypus>, though it may have other applications.

Before you get to deep into using this class you should also consider
the L<FFI::C>, which provides some overlapping functionality.  Briefly,
it comes down to this:

(The tl;dr is: use this class when you need to pass by value (since
L<FFI::C> does not support pass by value) and use L<FFI::C> in all
other circumstances).

=over 4

=item L<FFI::Platypus::Record>

Supports:

=over 4

=item C pointers to C<struct> types

=item Passing C C<struct>s by-value.

=back

Does not support:

=over 4

=item C C<union> types.

=item C arrays of C<struct> and C<union> types.

=back

=item L<FFI::C>

Supports:

=over 4

=item C C<struct> andC<union> types

=item C arrays of C<struct> and C<union> types.

=back

Does not support:

=over 4

=item Passing C C<struct>s by-value.

=back

String members are as of this writing a TODO for L<FFI::C>, but
should be coming soon!

=back

=head1 FUNCTIONS

=head2 record_layout_1

 record_layout_1($ffi, $type => $name, ... );
 record_layout_1(\@ffi_args, $type => $name, ... );
 record_layout_1($type => $name, ... );

Define the layout of the record.  You may optionally provide an instance
of L<FFI::Platypus> as the first argument in order to use its type
aliases.  Alternatively you may provide constructor arguments that will
be passed to the internal platypus instance.  Thus this is the same:

 my $ffi = FFI::Platypus->new( lang => 'Rust', api => 2 );
 record_layout_1( $ffi, ... );
 # same as:
 record_layout_1( [ lang => 'Rust' ], ... );

and this is the same:

 my $ffi = FFI::Platypus->new( api => 2 );
 record_layout_1( $ffi, ... );
 # same as:
 record_layout_1( ... );

Then you provide members as type/name pairs.

For each member you declare, C<record_layout_1> will create an accessor
which can be used to read and write its value. For example imagine a
class C<Foo>:

 package Foo;
 
 use FFI::Platypus::Record;
 
 record_layout_1(
   int          => 'bar',  #  int bar;
   'string(10)' => 'baz',  #  char baz[10];
 );

You can get and set its fields with like named C<bar> and C<baz>
accessors:

 my $foo = Foo->new;
 
 $foo->bar(22);
 my $value = $foo->bar;
 
 $foo->baz("grimlock\0\0"); # should be 10 characters long
 my $string_value = $foo->baz; # includes the trailing \0\0

You can also pass initial values in to the constructor, either passing
as a list of key value pairs or by passing a hash reference:

 $foo = Foo->new(
   bar => 22,
   baz => "grimlock\0\0",
 );
 
 # same as:
 
 $foo = Foo->new( {
   bar => 22,
   baz => "grimlock\0\0",
 } );

If there are members of a record that you need to account for in terms
of size and alignment, but do not want to have an accessor for, you can
use C<:> as a place holder for its name:

 record_layout_1(
   'int'        => ':',
   'string(10)' => 'baz',
 );

=head3 strings

So far I've shown fixed length strings.  These are declared with the
word C<string> followed by the length of the string in parentheticals.
Fixed length strings are included inside the record itself and do not
need to be allocated or deallocated separately from the record.
Variable length strings must be allocated on the heap, and thus require
a sense of "ownership", that is whomever allocates variable length
strings should be responsible for also free'ing them.  To handle this,
you can add a C<ro> or C<rw> trait to a string field.  The default is
C<ro>, means that you can get, but not set its value:

 package Foo;
 
 record_layout_1(
   'string ro' => 'bar',  # same type as 'string' and 'string_ro'
 );
 
 package main;
 
 my $foo = Foo->new;
 
 my $string = $foo->bar;  # GOOD
 $foo->bar("starscream"); # BAD

If you specify a field is C<rw>, then you can set its value:

 package Foo;
 
 record_layout_1(
   'string rw' => 'bar',  # same type as 'string_rw'
 );
 
 package main;
 
 my $foo = Foo->new;
 
 my $string = $foo->bar;  # GOOD
 $foo->bar("starscream"); # GOOD

Any string value that is pointed to by the record will be free'd when it
falls out of scope, so you must be very careful that any C<string rw>
fields are not set or modified by C code.  You should also take care not
to copy any record that has a C<rw> string in it because its values will
be free'd twice!

 use Clone qw( clone );
 
 my $foo2 = clone $foo;  # BAD  bar will be free'd twice

=head3 arrays

Arrays of integer, floating points and opaque pointers are supported.

 package Foo;
 
 record_layout_1(
   'int[10]' => 'bar',
 );
 
 my $foo = Foo->new;
 
 $foo->bar([1,2,3,4,5,6,7,8,9,10]); # sets the values for the array
 my $list = $foo->bar;  # returns a list reference
 
 $foo->bar(5, -6); # sets the 5th element in the array to -6
 my $item = $foo->bar(5); gets the 5th element in the array

=head2 record_layout

 record_layout($ffi, $type => $name, ... );
 record_layout(\@ffi_args, $type => $name, ... );
 record_layout($type => $name, ... );

This function works like C<record_layout> except that
C<api =E<gt> 0> is used instead of C<api =E<gt> 1>.
All new code should use C<record_layout_1> instead.

=head1 CAVEATS

These useful features (and probably more) are missing, and unlikely to be added.

=over 4

=item Unions

=item Nested records

=back

If you need these features, consider using L<FFI::C> instead.

=head1 SEE ALSO

=over 4

=item L<FFI::Platypus>

The main platypus documentation.

=item L<FFI::C>

Another interface for constructing structured data.  It includes support for
C<union> and array types (which this module does not), but lacks support for
passing records by-value.

=item L<FFI::Platypus::Record::TieArray>

Tied array interface for record array members.

=item L<Convert::Binary::C>

Another method for constructing and dissecting structured data records.

=item L<pack and unpack|perlpacktut>

Built-in Perl functions for constructing and dissecting structured data
records.

=back

=head1 AUTHOR

Author: Graham Ollis E<lt>plicease@cpan.orgE<gt>

Contributors:

Bakkiaraj Murugesan (bakkiaraj)

Dylan Cali (calid)

pipcet

Zaki Mughal (zmughal)

Fitz Elliott (felliott)

Vickenty Fesunov (vyf)

Gregor Herrmann (gregoa)

Shlomi Fish (shlomif)

Damyan Ivanov

Ilya Pavlov (Ilya33)

Petr Písař (ppisar)

Mohammad S Anwar (MANWAR)

Håkon Hægland (hakonhagland, HAKONH)

Meredith (merrilymeredith, MHOWARD)

Diab Jerius (DJERIUS)

Eric Brine (IKEGAMI)

szTheory

José Joaquín Atria (JJATRIA)

Pete Houston (openstrike, HOUSTON)

Lukas Mai (MAUKE)

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2015-2022 by Graham Ollis.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut