A game framework written with osu! in mind.
1// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
2// See the LICENCE file in the repository root for full licence text.
3
4using osu.Framework.Statistics;
5using System;
6
7namespace osu.Framework.Caching
8{
9 public class Cached<T>
10 {
11 private T value;
12
13 public T Value
14 {
15 get
16 {
17 if (!IsValid)
18 throw new InvalidOperationException($"May not query {nameof(Value)} of an invalid {nameof(Cached<T>)}.");
19
20 return value;
21 }
22
23 set
24 {
25 this.value = value;
26 IsValid = true;
27 FrameStatistics.Increment(StatisticsCounterType.Refreshes);
28 }
29 }
30
31 public bool IsValid { get; private set; }
32
33 public static implicit operator T(Cached<T> value) => value.Value;
34
35 /// <summary>
36 /// Invalidate the cache of this object.
37 /// </summary>
38 /// <returns>True if we invalidated from a valid state.</returns>
39 public bool Invalidate()
40 {
41 if (IsValid)
42 {
43 IsValid = false;
44 FrameStatistics.Increment(StatisticsCounterType.Invalidations);
45 return true;
46 }
47
48 return false;
49 }
50 }
51
52 public class Cached
53 {
54 public bool IsValid { get; private set; }
55
56 /// <summary>
57 /// Invalidate the cache of this object.
58 /// </summary>
59 /// <returns>True if we invalidated from a valid state.</returns>
60 public bool Invalidate()
61 {
62 if (IsValid)
63 {
64 IsValid = false;
65 FrameStatistics.Increment(StatisticsCounterType.Invalidations);
66 return true;
67 }
68
69 return false;
70 }
71
72 public void Validate()
73 {
74 IsValid = true;
75 FrameStatistics.Increment(StatisticsCounterType.Refreshes);
76 }
77 }
78}