1 //===-- runtime/unit-map.h --------------------------------------*- C++ -*-===//
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 // Maps Fortran unit numbers to their ExternalFileUnit instances.
10 // A simple hash table with forward-linked chains per bucket.
11 
12 #ifndef FORTRAN_RUNTIME_UNIT_MAP_H_
13 #define FORTRAN_RUNTIME_UNIT_MAP_H_
14 
15 #include "lock.h"
16 #include "memory.h"
17 #include "unit.h"
18 
19 namespace Fortran::runtime::io {
20 
21 class UnitMap {
22 public:
23   ExternalFileUnit *LookUp(int n) {
24     CriticalSection critical{lock_};
25     return Find(n);
26   }
27 
28   ExternalFileUnit &LookUpOrCreate(
29       int n, const Terminator &terminator, bool *wasExtant) {
30     CriticalSection critical{lock_};
31     auto *p{Find(n)};
32     if (wasExtant) {
33       *wasExtant = p != nullptr;
34     }
35     if (p) {
36       return *p;
37     }
38     return Create(n, terminator);
39   }
40 
41   ExternalFileUnit &NewUnit(const Terminator &terminator) {
42     CriticalSection critical{lock_};
43     return Create(nextNewUnit_--, terminator);
44   }
45 
46   // To prevent races, the unit is removed from the map if it exists,
47   // and put on the closing_ list until DestroyClosed() is called.
48   ExternalFileUnit *LookUpForClose(int);
49 
50   void DestroyClosed(ExternalFileUnit &);
51   void CloseAll(IoErrorHandler &);
52 
53 private:
54   struct Chain {
55     explicit Chain(int n) : unit{n} {}
56     ExternalFileUnit unit;
57     OwningPtr<Chain> next{nullptr};
58   };
59 
60   static constexpr int buckets_{1031}; // must be prime
61   int Hash(int n) { return n % buckets_; }
62 
63   ExternalFileUnit *Find(int n) {
64     Chain *previous{nullptr};
65     int hash{Hash(n)};
66     for (Chain *p{bucket_[hash].get()}; p; previous = p, p = p->next.get()) {
67       if (p->unit.unitNumber() == n) {
68         if (previous) {
69           // Move found unit to front of chain for quicker lookup next time
70           previous->next.swap(p->next); // now p->next.get() == p
71           bucket_[hash].swap(p->next); // now bucket_[hash].get() == p
72         }
73         return &p->unit;
74       }
75     }
76     return nullptr;
77   }
78 
79   ExternalFileUnit &Create(int, const Terminator &);
80 
81   Lock lock_;
82   OwningPtr<Chain> bucket_[buckets_]{}; // all owned by *this
83   int nextNewUnit_{-1000}; // see 12.5.6.12 in Fortran 2018
84   OwningPtr<Chain> closing_{nullptr}; // units during CLOSE statement
85 };
86 } // namespace Fortran::runtime::io
87 #endif // FORTRAN_RUNTIME_UNIT_MAP_H_
88