-----------------------------------------------------------------
--         Copyright (C) 2007-2017, AdaCore                    --
-----------------------------------------------------------------

--   Run with no command line argument to get performance measurements.
--   Run with one random argument to just run the test once to check
--      that we can indeed load large files.

with Ada.Command_Line;        use Ada.Command_Line;
with Ada.Calendar;            use Ada.Calendar;
with Ada.Text_IO;             use Ada.Text_IO;
with GNATCOLL.Mmap;           use GNATCOLL.Mmap;
with System.Storage_Elements; use System.Storage_Elements;

procedure Mmap_Large is
   Do_Perfs : constant Boolean := Argument_Count = 0;

   procedure Run (Advice : Use_Advice) is
      File   : Mapped_File;
      Region : Mapped_Region;
      Start  : Time;
   begin
      Start := Clock;

      File := Open_Read ("foo.txt");
      Region := Read (File, Offset => 0, Length => 3_000_000_000,
                      Advice => Advice);
      Close (File);   --  no need to keep the file descriptor open

      if Long.Last (Region) /= 3_000_000_000 then
         raise Program_Error with "Invalid size of region "
            & Long.Last (Region)'Img;
      end if;

      for A in 1 .. Long.Last (Region) loop
         if Long.Data (Region)(A) /= ASCII.NUL then
            raise Program_Error with "Invalid character at index" & A'Img;
         end if;
      end loop;

      if Do_Perfs then
         Put_Line (Advice'Img & ": " & Duration'Image (Clock - Start));
      end if;

      Free (Region);
   end Run;

begin

   if Do_Perfs then
      for Advice in Use_Advice loop
         Run (Advice);
      end loop;
   else
      Run (Use_Normal);
   end if;
end Mmap_Large;
