Skip to content

Commit 7b3ea12

Browse files
committed
support persistent_load
1 parent 02fc330 commit 7b3ea12

File tree

2 files changed

+43
-3
lines changed

2 files changed

+43
-3
lines changed

examples/persistent_id.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
2+
import pickle
3+
from collections import namedtuple
4+
5+
MemoRecord = namedtuple("MemoRecord", "key, task")
6+
7+
class MyPickler(pickle.Pickler):
8+
9+
def persistent_id(self, obj):
10+
# Instead of pickling MemoRecord as a regular class instance, we emit a
11+
# persistent ID.
12+
if isinstance(obj, MemoRecord):
13+
# Here, our persistent ID is simply a tuple, containing a tag and a
14+
# key, which refers to a specific record in the database.
15+
print('persistent_id set')
16+
return ("MemoRecord", obj.key)
17+
else:
18+
# If obj does not have a persistent ID, return None. This means obj
19+
# needs to be pickled as usual.
20+
return None
21+
22+
def main():
23+
memo = MemoRecord("aa", "bb")
24+
filehandler = open(b"persistent_id.pkl", "wb")
25+
MyPickler(filehandler).dump(memo)
26+
27+
if __name__ == '__main__':
28+
main()

src/parser.ts

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,17 @@ import { Registry } from './registry';
55

66
export class Parser {
77
private _reader: Reader;
8+
public persistent_load: (pid: string) => any;
89

910
registry: Registry = new Registry();
1011

11-
constructor(buffer: Uint8Array | Int8Array | Uint8ClampedArray) {
12+
constructor(buffer: Uint8Array | Int8Array | Uint8ClampedArray, persistent_load?: (pid: string) => any) {
1213
this._reader = new Reader(buffer);
14+
this.persistent_load =
15+
persistent_load ||
16+
((pid: string) => {
17+
throw new Error(`Unsupported persistent id: \`${pid}\`.`);
18+
});
1319
}
1420

1521
load() {
@@ -20,6 +26,8 @@ export class Parser {
2026
while (reader.hasNext()) {
2127
const opcode = reader.byte();
2228
// console.log(`${(reader.position - 1).toString()} ${opcode}`);
29+
// console.log('metastack:', metastack, '\nstack:', stack);
30+
// console.log('\nmemo:', Array.from(memo.entries()));
2331
switch (opcode) {
2432
// Structural
2533
case OP.PROTO: {
@@ -296,6 +304,12 @@ export class Parser {
296304
stack.push(obj);
297305
break;
298306
}
307+
case OP.PERSID:
308+
stack.push(this.persistent_load(reader.line()));
309+
break;
310+
case OP.BINPERSID:
311+
stack.push(this.persistent_load(stack.pop()));
312+
break;
299313
case OP.BUILD: {
300314
const state = stack.pop();
301315
const obj = stack[stack.length - 1];
@@ -318,8 +332,6 @@ export class Parser {
318332
}
319333

320334
default:
321-
// console.log('metastack:', metastack, '\nstack:', stack);
322-
// console.log('\nmemo:', Array.from(memo.entries()));
323335
throw new Error(`Unsupported opcode '${opcode}'.`);
324336
}
325337
}

0 commit comments

Comments
 (0)