Ei kuvausta
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SavedState.cs 2.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. namespace UnityEngine.InputSystem.Utilities
  3. {
  4. /// <summary>
  5. /// Provides type erasure and an abstraction of a saved state that
  6. /// will (must) be restored at a later point.
  7. /// </summary>
  8. internal interface ISavedState
  9. {
  10. /// <summary>
  11. /// Dispose current state, should be invoked before RestoreSavedState()
  12. /// to dispose the current state before restoring a saved state.
  13. /// </summary>
  14. void StaticDisposeCurrentState();
  15. /// <summary>
  16. /// Restore previous state, should be invoked after StaticDisposeCurrentState().
  17. /// </summary>
  18. void RestoreSavedState();
  19. }
  20. /// <summary>
  21. /// Provides functionality to store and support later restoration of a saved
  22. /// state. The state is expected to be a value-type. If the state is not restored
  23. /// it must be disposed to not leak resources.
  24. /// </summary>
  25. /// <typeparam name="T">The value-type representing the state to be stored.</typeparam>
  26. internal sealed class SavedStructState<T> : ISavedState where T : struct
  27. {
  28. public delegate void TypedRestore(ref T state);
  29. /// <summary>
  30. /// Constructs a SavedStructState.
  31. /// </summary>
  32. /// <param name="state">The value-type state to be saved.</param>
  33. /// <param name="restoreAction">The action to be carried out to restore state.</param>
  34. /// <param name="staticDisposeCurrentState">The action to be carried out to dispose current state. May be null.</param>
  35. internal SavedStructState(ref T state, TypedRestore restoreAction, Action staticDisposeCurrentState = null)
  36. {
  37. Debug.Assert(restoreAction != null, "Restore action is required");
  38. m_State = state; // copy
  39. m_RestoreAction = restoreAction;
  40. m_StaticDisposeCurrentState = staticDisposeCurrentState;
  41. }
  42. public void StaticDisposeCurrentState()
  43. {
  44. if (m_StaticDisposeCurrentState != null)
  45. {
  46. m_StaticDisposeCurrentState();
  47. m_StaticDisposeCurrentState = null;
  48. }
  49. }
  50. public void RestoreSavedState()
  51. {
  52. Debug.Assert(m_StaticDisposeCurrentState == null,
  53. $"Should have been disposed via {nameof(StaticDisposeCurrentState)} before invoking {nameof(RestoreSavedState)}");
  54. Debug.Assert(m_RestoreAction != null, $"Only invoke {nameof(RestoreSavedState)} once ");
  55. m_RestoreAction(ref m_State);
  56. m_RestoreAction = null;
  57. }
  58. private T m_State;
  59. private TypedRestore m_RestoreAction;
  60. private Action m_StaticDisposeCurrentState;
  61. }
  62. }