1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
/*!
This crate contains members to aid in the construction of a Rust [Lens Module](https://github.com/lens-vm/spec#abi---wasm-module-functions).
To get started, see [define](macro.define.html).
*/
use mem;
use ManuallyDrop;
use Iterator;
use PhantomData;
use ;
use ;
use ;
/// [Result](https://doc.rust-lang.org/std/result/enum.Result.html) type alias returned by lens_sdk.
/// Error types returned by lens_sdk.
/// Option type returned by lens_sdk.
/// Alias for an sdk [Error](error/enum.Error.html).
pub type Error = Error;
/// Alias for an sdk [Result](result/type.Result.html).
pub type Result<T> = Result;
/// Alias for an sdk [StreamOption](option/enum.StreamOption.html).
pub type StreamOption<T> = StreamOption;
/// A type id that denotes a simple string-based error.
///
/// If present at the beginning of a byte array being read by a [lens host](https://github.com/sourcenetwork/lens#Hosts)
/// or [try_from_mem](fn.try_from_mem.html), the byte array will be treated as an error and will be
/// handled accordingly.
pub const ERROR_TYPE_ID: i8 = -1;
/// A type id that denotes a nil value.
pub const NIL_TYPE_ID: i8 = 0;
/// A type id that denotes a json value.
///
/// If present at the beginning of a byte array being read by a [lens host](https://github.com/sourcenetwork/lens#Hosts)
/// or [try_from_mem](fn.try_from_mem.html), the byte array will be treated as a json value and will be
/// handled accordingly.
pub const JSON_TYPE_ID: i8 = 1;
/// A type id that donates the end of stream.
///
/// If recieved it signals that the end of the stream has been reached and that the source will no longer yield
/// new values.
pub const EOS_TYPE_ID: i8 = i8MAX;
/// Returns a nil pointer.
///
/// The pointer points to a zeroed byte, and will be interpretted by a [lens host](https://github.com/sourcenetwork/lens#Hosts)
/// as a nil value.
/// Allocate the given `size` number of bytes in memory and returns a pointer to
/// the first byte.
///
/// The runtime will be instructed to manually drop this memory and not dispose of it now - the value
/// that is to be held at this location should be written before any other calls are made into
/// the wasm instance.
/// Manually drop the memory of the given size at the given location.
///
/// It should only be called on pointers to manually managed memory.
pub unsafe
/// Manually drop the memory occupied by a transport buffer at the given location.
///
/// Items are transported across the host-wasm boundary as manually managed memory buffers, the
/// allocation for which is handled by [alloc](fn.alloc.html). The pointer to this manually managed memory
/// is returned by the `next` host function imported by LensVM wasm modules.
///
/// Once the item has been consumed by the transform, the memory allocated must be manually dropped,
/// typically via this function.
///
/// # Safety
///
/// This function assumes that the pointer points to a transport buffer, passing a pointer to anything else
/// will result in undefined behaviour.
///
/// The pointer should not be used after calling this function. The memory it points to will have been unreserved,
/// and may have been replaced by other stuff by the runtime.
///
/// # Errors
///
/// This function will return an [Error](error/enum.Error.html) if the data at the given location is not in the expected
/// format.
pub unsafe
/// Read the data held at the given location in memory as the given `TOutput` type.
///
/// The bytes at the given location are expected to be in the correct format for the first (`type_id`) byte.
///
/// `type_id` | Type | Expected format
/// --- | --- | ---
/// < 0 | error | N/A - unsupported, will return an [InputErrorUnsupportedError](error/enum.LensError.html#variant.InputErrorUnsupportedError)
/// 0 | null value | N/A - will return [None](https://doc.rust-lang.org/std/option/enum.Option.html#variant.None)
/// \> 0 | JSON | \[`len`\]\[`json_string`\] where len is the length of bytes in the json_string
///
/// # Safety
///
/// The pointer given to this function will typically be result of calls to the `next` host function imported by LensVM wasm modules. It is
/// manually managed memory, and calling this function will free the memory located at the given `ptr` - it must not be used after this call.
///
/// # Errors
///
/// This function will return an [Error](error/enum.Error.html) if the data at the given location is not in the expected
/// format.
pub unsafe
/// Write the given `message` bytes to memory, returning a pointer to the first byte.
///
/// Bytes are written in the same format as expected by [lens hosts](https://github.com/sourcenetwork/lens#Hosts) and
/// [try_from_mem](fn.try_from_mem.html) \- `[type_id][len][json_string]`.
///
/// # Errors
///
/// This function may return the same errors that [io::write](https://doc.rust-lang.org/std/io/trait.Write.html#tymethod.write)
/// may return.
/// Write the given `message` bytes to memory, returning a pointer to the first byte.
///
/// Bytes are written in the same format as expected by [lens hosts](https://github.com/sourcenetwork/lens#Hosts) and
/// [try_from_mem](fn.try_from_mem.html) \- `[type_id][len][json_string]`.
///
/// This function wraps [try_to_mem](fn.try_to_mem.html), if an error was generated by that internal function call
/// this function will attempt to write the error to memory, if that generates an error, it will attempt to write
/// a [FailedToWriteErrorToMemError](error/enum.LensError.html#variant.FailedToWriteErrorToMemError) to memory,
/// if that fails this function will panic.
///
/// # Panics
///
/// This function will panic if an error was generated internally and all attempts to write it to memory failed.
/// Execute the given `transform` once, returning a pointer to the (serialized for transport) output.
///
/// The returned pointer can be sent across the wasm boundary to the executing lens-engine.
///
/// The given `transform` will be given an iterator that yields items of type `TInput`, `transform` may iterate
/// through zero-to-many items before returning.
///
/// # Errors
///
/// The iterator given to `transform` may yield a [StreamOption](option/enum.StreamOption.html) if `next` returns
/// and invalid pointer. Implmentors of `transform`s may handle that however they choose, although panicing is discouraged.
///
/// `transform` is free to return any [Error] kinds that they like. [next] will serialize any returned errors, returning a
/// pointer to the serialized content which may then be passed across the wasm boundary and handled by the executing lens engine.
///
/// # Examples
///
/// The following example lens contains a simple filter, only yielding inputs where the `type_name` property equals `"pass"`.
///
/// ```
/// # use std::error::Error;
/// # use std::iter::Iterator;
/// # use serde::{Serialize, Deserialize};
/// # use lens_sdk::StreamOption;
/// #
/// # #[link(wasm_import_module = "lens")]
/// # unsafe extern "C" {
/// # fn next() -> *mut u8;
/// # }
/// #
/// # #[derive(Serialize, Deserialize)]
/// # pub struct Value {
/// # pub name: String,
/// # pub type_name: String,
/// # }
/// #
/// # #[unsafe(no_mangle)]
/// # pub extern "C" fn alloc(size: usize) -> *mut u8 {
/// # lens_sdk::alloc(size)
/// # }
/// #
/// #[unsafe(no_mangle)]
/// pub extern "C" fn transform() -> *mut u8 {
/// lens_sdk::next(|| -> *mut u8 { unsafe { next() } }, try_transform)
/// }
///
/// fn try_transform(
/// iter: &mut dyn Iterator<Item = lens_sdk::Result<Option<Value>>>,
/// ) -> Result<StreamOption<Value>, Box<dyn Error>> {
/// for item in iter {
/// let input = match item? {
/// Some(v) => v,
/// None => continue,
/// };
///
/// if input.type_name == "pass" {
/// return Ok(StreamOption::Some(input))
/// }
/// }
///
/// Ok(StreamOption::EndOfStream)
/// }
/// ```
/// Define the mandatory `alloc` function for this Lens.
///
/// It is responsible for allocating memory for input items and will be called by the Lens engine.
/// Define the mandatory `next` function for this Lens.
///
/// It is responsible for pulling the pointer to the next input item from the Lens engine.
/// Define the mandatory `transform` function for this Lens.
///
/// This macro wraps the provided `try_transform` function, providing the boilerplate required to handle input items
/// sent across the WASM boundary from the Lens engine. The resultant function is responsible for transforming
/// input items pulled in by [next()](macro.define_next.html) and yields a pointer to the serialized result.
///
/// It assumes that a `next()` function exists within the calling scope.
/// Define the optional `inverse` function for this Lens.
///
/// This macro wraps the provided `try_inverse` function, providing the boilerplate required to handle input items
/// sent across the WASM boundary from the Lens engine. The resultant function is responsible for inversing transforms
/// on input items pulled in by [next()](macro.define_next.html) and yields a pointer to the serialized result.
///
/// It assumes that a `next()` function exists within the calling scope.
/// Define the optional `set_param` function for this Lens.
///
/// `set_param` is used to recieve static parameters from the Lens engine. If parameters are provided to the Lens
/// engine, this function will be called once on initialization, before items are are fed through the transform/inverse
/// functions. This macro defines the boiler plate required to recieve them.
///
/// It takes the name of the variable in which the parameter should be stored, and the type of the parameter.
///
/// # Examples
///
/// ```
/// # use std::sync::RwLock;
/// # use serde::Deserialize;
/// #
/// #[derive(Deserialize, Clone)]
/// pub struct Parameters {
/// pub src: String,
/// pub dst: String,
/// }
///
/// static PARAMETERS: RwLock<Option<Parameters>> = RwLock::new(None);
///
/// lens_sdk::define_set_param!(PARAMETERS: Parameters);
/// ```
/// Define the boilerplate for the Lens.
///
/// This macro is the easiest way to setup your Lens file - provide this with a transform function and
/// you should have a valid Lens.
///
/// This macro handles multiple patterns, each handled pattern will generate a different set of functions.
///
/// - [next()](macro.define_next.html) and [alloc()](macro.define_alloc.html) will always be defined.
/// - [transform()](macro.define_transform.html) will be defined if given a single transform function.
/// - [transform()](macro.define_transform.html) and [inverse()](macro.define_inverse.html) will be
/// defined if given the identities of two transform/inverse functions.
/// - [set_param()](macro.define_set_param.html) will be defined if given the name of a variable to hold a param,
/// and its type.
///
/// # Examples
///
/// The following example contains a complete Lens that transforms inputs by incrementing input.age by 1.
///
/// ```
/// # use serde::{ Deserialize, Serialize };
/// # use lens_sdk::StreamOption;
/// # use std::error::Error;
/// #
/// lens_sdk::define!(try_transform);
///
/// #[derive(Serialize, Deserialize)]
/// pub struct Value {
/// pub name: String,
/// pub age: i64,
/// }
///
/// fn try_transform(
/// iter: &mut dyn Iterator<Item = lens_sdk::Result<Option<Value>>>,
/// ) -> Result<StreamOption<Value>, Box<dyn Error>> {
/// for item in iter {
/// let input = match item? {
/// Some(v) => v,
/// None => return Ok(StreamOption::None),
/// };
///
/// let result = Value {
/// name: input.name,
/// age: input.age + 1,
/// };
///
/// return Ok(StreamOption::Some(result))
/// }
///
/// Ok(StreamOption::EndOfStream)
/// }
/// ```
///
/// The next example contains a complete Lens that transforms, and inverses, the incrementing of input.age by the amount
/// provided by the configured paramter.
///
/// ```
/// # use std::sync::RwLock;
/// # use serde::{ Deserialize, Serialize };
/// # use lens_sdk::StreamOption;
/// # use lens_sdk::error::LensError;
/// # use std::error::Error;
/// #
/// lens_sdk::define!(PARAMETERS: Parameters, try_transform, try_inverse);
///
/// #[derive(Deserialize, Clone)]
/// pub struct Parameters {
/// pub magnitude: i64,
/// }
///
/// static PARAMETERS: RwLock<Option<Parameters>> = RwLock::new(None);
///
/// #[derive(Serialize, Deserialize)]
/// pub struct Value {
/// pub name: String,
/// pub age: i64,
/// }
///
/// fn try_transform(
/// iter: &mut dyn Iterator<Item = lens_sdk::Result<Option<Value>>>,
/// ) -> Result<StreamOption<Value>, Box<dyn Error>> {
/// let params = PARAMETERS.read()?
/// .clone()
/// .ok_or(LensError::ParametersNotSetError)?;
///
/// for item in iter {
/// let input = match item? {
/// Some(v) => v,
/// None => return Ok(StreamOption::None),
/// };
///
/// let result = Value {
/// name: input.name,
/// age: input.age + params.magnitude,
/// };
///
/// return Ok(StreamOption::Some(result))
/// }
///
/// Ok(StreamOption::EndOfStream)
/// }
///
/// fn try_inverse(
/// iter: &mut dyn Iterator<Item = lens_sdk::Result<Option<Value>>>,
/// ) -> Result<StreamOption<Value>, Box<dyn Error>> {
/// let params = PARAMETERS.read()?
/// .clone()
/// .ok_or(LensError::ParametersNotSetError)?;
///
/// for item in iter {
/// let input = match item? {
/// Some(v) => v,
/// None => return Ok(StreamOption::None),
/// };
///
/// let result = Value {
/// name: input.name,
/// age: input.age - params.magnitude,
/// };
///
/// return Ok(StreamOption::Some(result))
/// }
///
/// Ok(StreamOption::EndOfStream)
/// }
/// ```