Memory layout of a data structure: Difference between revisions

better Pascal example
(Scala solution added)
(better Pascal example)
Line 1:
{{task}}{{omit from|BBC BASIC}}
{{omit from|BBC BASIC}}
It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.
Pin Settings for Plug
Line 313 ⟶ 314:
Print SizeOf(RS232_Pin9) '' 2 bytes
Sleep</lang>
 
=={{transheader|Free Pascal}}==
The FPC (Free Pascal compiler) carefully defines the internal memory structure of data type in its “Programmer’s guide”.
<lang pascal>program memoryLayoutrs232(input, output, stdErr);
type
{$packEnum 2}{$scopedEnums off}
pin = (carrierDetect, receivedData, transmittedData, dataTerminalReady,
signalGround, dataSetReady, requestToSend, clearToSend, ringIndicator);
{$packSet 2}
pins = set of pin;
var
signal: pins;
// for demonstration purposes, in order to reveal the memory layout
signalMemoryStructure: word absolute signal;
{$if sizeOf(signal) <> sizeOf(word)} // just as safe-guard
{$fatal signal size}
{$endIf}
begin
signal := [];
include(signal, signalGround); // equivalent to signal := signal + [signalGround];
// for demonstration purposes: obviously we know this is always `true`
if signalGround in signal then
begin
writeLn(binStr(signalMemoryStructure, bitSizeOf(signal)));
end;
end.</lang>
{{Out}}
<pre>0000000000010000</pre>
 
=={{header|Go}}==
Line 683 ⟶ 712:
 
=={{header|Pascal}}==
Pascal itself does not define, how data types have to be stored in memory.
{{works with|Free_Pascal}}
It is up to the processor (i. e. compiler) to choose appropriate mechanism.
<lang pascal>program memoryLayout;
The [[#Free Pascal|FPC]] (Free Pascal compiler) does predictably define how it stores data.
 
type
T_RS232 = (
carrier_detect,
received_data,
transmitted_data,
data_terminal_ready,
signal_ground,
data_set_ready,
request_to_send,
clear_to_send,
ring_indicator
);
 
var
Signal: bitpacked array[T_RS232] of boolean;
 
begin
Signal[signal_ground] := true;
end.</lang>
 
=={{header|Perl}}==
Line 737 ⟶ 747:
$vec->set($rs232{'RD Received data'}, 1);
$vec->get($rs232{'TC Transmit clock'});</lang>
 
=={{header|Perl 6}}==
{{trans|Pascal}}
The following is specced to work, but implementation of shaped arrays is not quite complete.
<lang perl6>enum T_RS232 <
Line 1,166 ⟶ 1,176:
println(toOnOff(plug.ringIndicator)) // print value of pin 9 by name
}</lang>
 
=={{header|Tcl}}==
This Tcl implementation represents the fields as bits in an integer. It provides two functions to get from symbolic pin names to the integer, and vice versa.
149

edits