| 1 | (************************************************************************) |
| 2 | (* * The Rocq Prover / The Rocq Development Team *) |
| 3 | (* v * Copyright INRIA, CNRS and contributors *) |
| 4 | (* <O___,, * (see version control and CREDITS file for authors & dates) *) |
| 5 | (* \VV/ **************************************************************) |
| 6 | (* // * This file is distributed under the terms of the *) |
| 7 | (* * GNU Lesser General Public License Version 2.1 *) |
| 8 | (* * (see LICENSE file for the text of the license) *) |
| 9 | (************************************************************************) |
| 10 | |
| 11 | (* Use case: |
| 12 | You have a data structure that needs to be marshalled but it contains |
| 13 | unmarshallable data (like a closure, or a file descriptor). Actually |
| 14 | you don't need this data to be preserved by marshalling, it just happens |
| 15 | to be there. |
| 16 | You could produced a trimmed down data structure, but then, once |
| 17 | unmarshalled, you can't used the very same code to process it, unless you |
| 18 | re-inject the trimmed down data structure into the standard one, using |
| 19 | dummy values for the unmarshallable stuff. |
| 20 | Similarly you could change your data structure turning all types [bad] |
| 21 | into [bad option], then just before marshalling you set all values of type |
| 22 | [bad option] to [None]. Still this pruning may be expensive and you have |
| 23 | to code it. |
| 24 | |
| 25 | Desiderata: |
| 26 | The marshalling operation automatically discards values that cannot be |
| 27 | marshalled or cannot be properly unmarshalled. |
| 28 | |
| 29 | Proposed solution: |
| 30 | Turn all occurrences of [bad] into [bad key] in your data structure. |
| 31 | Use [create bad_val] to obtain a unique key [k] for [bad_val], and store |
| 32 | [k] in the data structure. Use [get k] to obtain [bad_val]. |
| 33 | |
| 34 | An ['a key] can always be marshalled. When marshalled, a key loses its |
| 35 | value. The function [get] raises Not_found on unmarshalled keys. |
| 36 | |
| 37 | If a key is garbage collected, the corresponding value is garbage |
| 38 | collected too (unless extra references to it exist). |
| 39 | In short no memory management hassle, keys can just replace their |
| 40 | corresponding value in the data structure. *) |
| 41 | |
| 42 | type 'a key |
| 43 | |
| 44 | val create : 'a -> 'a key |
| 45 | |
| 46 | exception InvalidKey |
| 47 | |
| 48 | val get : 'a key -> 'a |
| 49 | (** May raise InvalidKey *) |
| 50 | |
| 51 | val default : 'a key -> 'a -> 'a |
| 52 | (** Never fails. *) |
| 53 | |
| 54 | val clean : unit -> unit |