如何在 Ada 中方便地解析明文文件的特定块?

问题描述 投票:0回答:1

我正在尝试从 Ada 中的 Tahoe-LAFS 读取共享的 URI 扩展块。它看起来像这样:

codec_name:3:crs,codec_params:11:131073-3-10,crypttext_hash:32:..G.3u1~A..o;.w..k,..3.h....K.gk,crypttext_root_hash:32:.}...I3P..Z...A.....tkq.{..'...G,needed_shares:1:3,num_segments:2:52,segment_size:6:131073,share_root_hash:32:.Q>.hGmr.9^J..........size:7:6694675,tail_codec_params:9:9954-3-10,total_shares:2:10,

现在,我试图想出一个解决方案,如何将其变成 Record 类型,但我没有成功。我想到了一些:

  1. 将所有值放入 Map(String)String 中,然后将它们转换为实际类型。
  2. 检查值的第一个组成部分,并立即使用 switch case 语句处理它
data-structures ada
1个回答
0
投票

你似乎有一个具有以下结构的字符串

field{,field}

其中

field
是结构化的

<name>:<length>:<value>

<value>
的长度为
<length>
个字符。使用标准库中的
Ada.Strings.Fixed.Index
可以轻松解析:

function Parsed (Line : in String) return Whatever is
   Result  : Whatever;
   Start   : Positive := Line'First;
   Colon_1 : Positive; -- Constraint_Error will be raised if a colon is missing
   Colon_2 : Positive;
begin -- Parsed;
   All_Fields : loop
      exit All_Fields when Start > Line'Last;

      Colon_1 := Ada.Strings.Fixed.Index (Line, ":", Start);
      Colon_2 := Ada.Strings.Fixed.Index (Line, ":", Colon_1 + 1);

      One_Field : declare
         Name   : constant String   := Line (Start .. Colon_1 - 1);
         Length : constant Positive := Integer'Value (Line (Colon_1 + 1 .. Colon_2 - 1) );
         Value  : constant String   := Line (Colon_2 + 1 .. Colon_2 + Length);
      begin -- One_Field
         -- Update Result using Name and Value
         Start := Colon_2 + Length + 2;
      end One_Field;
   end loop All_Fields;

   return Result;
end Parsed;
© www.soinside.com 2019 - 2024. All rights reserved.