1 //
2 // Copyright (c) 2010-2024 Antmicro
3 //
4 // This file is licensed under the MIT License.
5 // Full license text is available in 'licenses/MIT.txt'.
6 //
7 using System.Collections.Generic;
8 using Antmicro.Renode.Logging;
9 
10 namespace Antmicro.Renode.Peripherals.Miscellaneous.S32K3XX_FlexIOModel
11 {
12     public class ResourceBlocksManager<T> where T : ResourceBlock
13     {
ResourceBlocksManager(IEmulationElement owner, string resourceBlockName, IReadOnlyList<T> resourceBlocks)14         public ResourceBlocksManager(IEmulationElement owner, string resourceBlockName, IReadOnlyList<T> resourceBlocks)
15         {
16             logger = owner;
17             blockName = resourceBlockName;
18             blocks = resourceBlocks;
19         }
20 
TryGet(uint identifier, out T block)21         public bool TryGet(uint identifier, out T block)
22         {
23             var exists = identifier < blocks.Count;
24             block = exists ? blocks[(int)identifier] : null;
25             return exists;
26         }
27 
Reserve(IPeripheral reserver, uint identifier, out T block)28         public bool Reserve(IPeripheral reserver, uint identifier, out T block)
29         {
30             var exists = TryGet(identifier, out block);
31             if(exists)
32             {
33                 if(reservations.ContainsKey(block))
34                 {
35                     // Sharing blocks may be valid for more complex scenarios
36                     logger.Log(LogLevel.Warning, "The {0} with the {1} identifier is already used by another peripheral, sharing a {0} between peripherals may cause an unexpected result", blockName, identifier);
37                 }
38                 reservations[block] = reserver;
39             }
40             return exists;
41         }
42 
43         private readonly string blockName;
44         private readonly IReadOnlyList<T> blocks;
45         private readonly IEmulationElement logger;
46         private readonly IDictionary<T, IPeripheral> reservations = new Dictionary<T, IPeripheral>();
47     }
48 }
49