stcarrez / ada-util

Ada Utility Library - Composing streams, processes, logs, serialization, encoders and more
Apache License 2.0
69 stars 14 forks source link

util-files.adb "Into : out unbounded_string" not initialized #46

Closed CoghettoR closed 8 months ago

CoghettoR commented 1 year ago

The code

with Ada.Strings.Unbounded;
with Ada.Text_IO; use Ada.Text_IO;
with Util.Files;

procedure testa is
   content : Ada.Strings.Unbounded.Unbounded_String;
begin
   Util.Files.Write_File ("file1", "text1A" & ASCII.LF & "text1B");
   Util.Files.Read_File ("file1", content);
   Put_Line ("file1");
   Put_Line (Ada.Strings.Unbounded.To_String (content));
   New_Line;

   --  procedure Read_File (Path     : in String;
   --                      Into     : out Unbounded_String;
   --                      Max_Size : in Natural := 0);
   Put_Line ("file2");
   Util.Files.Write_File ("file2", "text2A" & ASCII.LF & "text2B");
   Util.Files.Read_File ("file2", content);
   Put_Line ("file2=" & Ada.Strings.Unbounded.To_String (content));
end testa;

The output

file1
text1A
text1B

file2
file2=text1A
text1Btext2A
text2B

Expected result

file1
text1A
text1B

file2
file2=text2A
text2B

Cause

out parameter not initialized

Solution

In procedure Read_File (util-files.adb), add Into := Null_Unbounded_String;

 procedure Read_File (Path     : in String;
                        Into     : out Unbounded_String;
                        Max_Size : in Natural := 0) is
      use Ada.Streams;
      use Ada.Streams.Stream_IO;

      F      : File_Type;
      Buffer : Stream_Element_Array (1 .. 10_000);
      Pos    : Positive_Count := 1;
      Last   : Stream_Element_Offset;
      Space  : Natural;
   begin
      Into := Null_Unbounded_String;
      if Max_Size = 0 then
         Space := Natural'Last;
      else
         Space := Max_Size;
      end if;

alr

alr with utilada

Source

https://stackoverflow.com/questions/40621326/ada-out-parameter

stcarrez commented 1 year ago

Yes, another option could be to declare the Content parameter as in out and make it clear that the Read_File procedure appends the file content to the target unbounded string.