1 //===-- runtime/connection.cpp --------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "connection.h"
10 #include "environment.h"
11 #include "io-stmt.h"
12 #include <algorithm>
13 
14 namespace Fortran::runtime::io {
15 
16 std::size_t ConnectionState::RemainingSpaceInRecord() const {
17   auto recl{recordLength.value_or(
18       executionEnvironment.listDirectedOutputLineLengthLimit)};
19   return positionInRecord >= recl ? 0 : recl - positionInRecord;
20 }
21 
22 bool ConnectionState::NeedAdvance(std::size_t width) const {
23   return positionInRecord > 0 && width > RemainingSpaceInRecord();
24 }
25 
26 bool ConnectionState::IsAtEOF() const {
27   return endfileRecordNumber && currentRecordNumber >= *endfileRecordNumber;
28 }
29 
30 void ConnectionState::HandleAbsolutePosition(std::int64_t n) {
31   positionInRecord = std::max(n, std::int64_t{0}) + leftTabLimit.value_or(0);
32 }
33 
34 void ConnectionState::HandleRelativePosition(std::int64_t n) {
35   positionInRecord = std::max(leftTabLimit.value_or(0), positionInRecord + n);
36 }
37 
38 SavedPosition::SavedPosition(IoStatementState &io) : io_{io} {
39   ConnectionState &conn{io_.GetConnectionState()};
40   saved_ = conn;
41   conn.pinnedFrame = true;
42 }
43 
44 SavedPosition::~SavedPosition() {
45   ConnectionState &conn{io_.GetConnectionState()};
46   while (conn.currentRecordNumber > saved_.currentRecordNumber) {
47     io_.BackspaceRecord();
48   }
49   conn.leftTabLimit = saved_.leftTabLimit;
50   conn.furthestPositionInRecord = saved_.furthestPositionInRecord;
51   conn.positionInRecord = saved_.positionInRecord;
52   conn.pinnedFrame = saved_.pinnedFrame;
53 }
54 } // namespace Fortran::runtime::io
55