@@ -5387,20 +5387,68 @@ subroutine json_value_get_child_by_index(json, p, idx, child, found)
53875387
53885388 if (associated (p% children)) then
53895389
5390- child = > p% children
5390+ ! If getting first or last child, we can do this quickly.
5391+ ! Otherwise, traverse the list.
5392+ if (idx== 1 ) then
53915393
5392- do i = 1 , idx - 1
5394+ child = > p % children ! first one
53935395
5394- if (associated (child% next)) then
5395- child = > child% next
5396+ elseif (idx== p% n_children) then
5397+
5398+ if (associated (p% tail)) then
5399+ child = > p% tail ! last one
53965400 else
53975401 call json% throw_exception(' Error in json_value_get_child_by_index:' // &
5398- ' child%next is not associated.' )
5399- nullify(child)
5400- exit
5402+ ' child%tail is not associated.' )
54015403 end if
54025404
5403- end do
5405+ elseif (idx< 1 .or. idx> p% n_children) then
5406+
5407+ call json% throw_exception(' Error in json_value_get_child_by_index:' // &
5408+ ' idx is out of range.' )
5409+
5410+ else
5411+
5412+ ! if idx is closer to the end, we traverse the list backward from tail,
5413+ ! otherwise we traverse it forward from children:
5414+
5415+ if (p% n_children- idx < idx) then ! traverse backward
5416+
5417+ child = > p% tail
5418+
5419+ do i = 1 , p% n_children - idx
5420+
5421+ if (associated (child% previous)) then
5422+ child = > child% previous
5423+ else
5424+ call json% throw_exception(' Error in json_value_get_child_by_index:' // &
5425+ ' child%previous is not associated.' )
5426+ nullify(child)
5427+ exit
5428+ end if
5429+
5430+ end do
5431+
5432+ else ! traverse forward
5433+
5434+ child = > p% children
5435+
5436+ do i = 1 , idx - 1
5437+
5438+ if (associated (child% next)) then
5439+ child = > child% next
5440+ else
5441+ call json% throw_exception(' Error in json_value_get_child_by_index:' // &
5442+ ' child%next is not associated.' )
5443+ nullify(child)
5444+ exit
5445+ end if
5446+
5447+ end do
5448+
5449+ end if
5450+
5451+ end if
54045452
54055453 else
54065454
0 commit comments