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
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
/*! Rust interface to the [`sciter::value`](https://github.com/c-smile/sciter-sdk/blob/master/include/value.h).

Sciter `Value` holds superset of JSON objects.

It can contain as pure JSON objects (numbers, strings, maps and arrays) as internal objects like DOM elements,
proxies of script functions, objects and arrays.


## Basic usage

You can create an empty (undefined) sciter `Value` with `new()`:

```
use sciter::Value;

let v = Value::new();
assert!(v.is_undefined());
assert!(!v.is_null());
```

Or explicitly create `Value` for specified type:

```
use sciter::Value;

let v = Value::null();
assert!(v.is_null());

let v = Value::symbol("hello");
assert!(v.is_symbol());
assert!(v.is_string());

let v = Value::error("hello");
assert!(v.is_error_string());
assert!(v.is_string());

// allocate a new array with 4 empty elements
let v = Value::array(4);
assert!(v.is_array());
assert!(v.len() == 4);

// allocate a new value with map type
let v = Value::map();
assert!(v.is_map());
assert!(v.len() == 0);

```

Also there is conversion from Rust types:

```
use sciter::Value;

let v = Value::from(true);
assert!(v.is_bool());

let v = Value::from(1);
assert!(v.is_int());

let v = Value::from(1.0);
assert!(v.is_float());

let v = Value::from("hello");
assert!(v.is_string());

let v = Value::from(b"123".as_ref());
assert!(v.is_bytes());
```

And from sequence of objects:

```
use sciter::Value;

let v: Value = ["1","2","3"].iter().cloned().collect();
assert!(v.is_array());
assert_eq!(v.len(), 3);

assert_eq!(v[0], Value::from("1"));
```

To access its contents you should use one of `to_` methods:

```
use sciter::Value;

let v = Value::from(4);
assert_eq!(v.to_int(), Some(4));
```

Note that there is two functions that converts `Value` to JSON and back:

```
use sciter::Value;

let mut v: Value = "[1, 2, 3, 4]".parse().unwrap();
let json_str = v.into_string();
```

Array access:

```
use sciter::Value;

let mut v: Value = "[10, 20]".parse().unwrap();
assert_eq!(v[0], Value::from(10));

// explicit arguments:
v.set(1, Value::from(21));
v.set(2, Value::from(22));

// implicit arguments:
v.set(1, 21);
v.set(2, 22);

assert_eq!(v.len(), 3);

assert!(v.get(0).is_int());
```

Map access:

```
use sciter::Value;

let mut v: Value = "{one: 1, two: 2}".parse().unwrap();
assert_eq!(v["one"], 1.into());
assert_eq!(v.get_item("one"), 1.into());
assert_eq!(v[Value::from("one")], Value::from(1));

v.set_item("three", 3);
assert!(v.get_item("one").is_int());
```

.
*/

use ::{_API};
use capi::sctypes::*;
use capi::scvalue::{VALUE, VALUE_UNIT_TYPE_STRING};
pub use capi::scvalue::{VALUE_RESULT, VALUE_STRING_CVT_TYPE, VALUE_TYPE};


// TODO: `get`, `get_item` methods should return `Option<Value>`

/// `sciter::value` wrapper.
///
/// See the [module-level](index.html) documentation.
pub struct Value
{
	data: VALUE,
	tmp: * mut Value,
}

/// `sciter::Value` can be transferred across thread boundaries.
unsafe impl Send for Value {}

impl Value {

	/// Return a new sciter value object ([undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined)).
	pub fn new() -> Value {
		Value { data: VALUE::default(), tmp: ::std::ptr::null_mut() }
	}

	/// Make explicit [array](https://sciter.com/docs/content/script/Array.htm) value with the given length.
	pub fn array(length: usize) -> Value {
		let mut me = Value::new();
		(_API.ValueIntDataSet)(me.as_ptr(), length as i32, VALUE_TYPE::T_ARRAY as UINT, 0);
		return me;
	}

	/// Make explicit [map](https://sciter.com/docs/content/script/Object.htm) value.
	pub fn map() -> Value {
		let mut me = Value::new();
		(_API.ValueIntDataSet)(me.as_ptr(), 0i32, VALUE_TYPE::T_MAP as UINT, 0);
		return me;
	}

	/// Make explicit json [null](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null) value.
	pub fn null() -> Value {
		let mut me = Value::new();
		me.data.t = VALUE_TYPE::T_NULL;
		return me;
	}

	/// Make sciter [symbol](https://sciter.com/docs/content/script/language/Syntax.htm#symbol-literals) value.
	pub fn symbol(val: &str) -> Value {
		let mut me = Value::new();
		me.assign_str(val, VALUE_UNIT_TYPE_STRING::SYMBOL);
		return me;
	}

	/// Make sciter [error](https://sciter.com/docs/content/script/Error.htm) value.
	pub fn error(val: &str) -> Value {
		let mut me = Value::new();
		me.assign_str(val, VALUE_UNIT_TYPE_STRING::ERROR);
		return me;
	}

	/// Make sciter [color](https://sciter.com/docs/content/script/Color.htm) value, in 0xAABBGGRR form.
	pub fn color(val: u32) -> Value {
		let mut me = Value::new();
		(_API.ValueIntDataSet)(me.as_ptr(), val as i32, VALUE_TYPE::T_COLOR as u32, 0);
		return me;
	}

	/// Make sciter [duration](https://sciter.com/docs/content/script/language/Types.htm) value, in seconds.
	pub fn duration(val: f64) -> Value {
		let mut me = Value::new();
		(_API.ValueFloatDataSet)(me.as_ptr(), val, VALUE_TYPE::T_DURATION as u32, 0);
		return me;
	}

	/// Make sciter [angle](https://sciter.com/docs/content/script/Angle.htm) value, in radians.
	pub fn angle(val: f64) -> Value {
		let mut me = Value::new();
		(_API.ValueFloatDataSet)(me.as_ptr(), val, VALUE_TYPE::T_ANGLE as u32, 0);
		return me;
	}

	/// Parse json string into value.
	pub fn parse(val: &str) -> Result<Value, u32> {
		return Value::parse_as(val, VALUE_STRING_CVT_TYPE::JSON_LITERAL);
	}

	/// Parse json string into value. Returns number of chars left unparsed in case of error.
	pub fn parse_as(val: &str, how: VALUE_STRING_CVT_TYPE) -> Result<Value, u32> {
		let mut me = Value::new();
		let (s,n) = s2w!(val);
		let ok: u32 = (_API.ValueFromString)(me.as_ptr(), s.as_ptr(), n, how);
		if ok == 0 {
			Ok(me)
		} else {
			Err(ok)
		}
	}

	#[doc(hidden)]
	pub fn as_ptr(&mut self) -> *mut VALUE {
		&mut self.data as *mut VALUE
	}

	#[doc(hidden)]
	pub fn as_cptr(&self) -> *const VALUE {
		&self.data as *const VALUE
	}

	#[doc(hidden)]
	pub fn as_mut_ptr(&self) -> * mut VALUE {
		unsafe { ::std::mem::transmute(self.as_cptr()) }
	}

	/// Get inner value type.
	pub fn get_type(&self) -> VALUE_TYPE {
		return self.data.t;
	}

	/// Get inner value type and its subtype (e.g. units).
	pub fn full_type(&self) -> (VALUE_TYPE, UINT) {
		return (self.data.t, self.data.u);
	}

	/// Convert T_OBJECT value type to JSON T_MAP or T_ARRAY.
	/// Also must be used if you need to pass values between different threads.
	pub fn isolate(&mut self) {
		(_API.ValueIsolate)(self.as_ptr());
	}

	/// Clear the VALUE and deallocates all assosiated structures that are not used anywhere else.
	pub fn clear(&mut self) -> &mut Value {
		(_API.ValueClear)(self.as_ptr());
		self
	}

	/// Return the number of items in the T_ARRAY, T_MAP, T_FUNCTION and T_OBJECT sciter::value.
	pub fn len(&self) -> usize {
		let mut n: INT = 0;
		(_API.ValueElementsCount)(self.as_cptr(), &mut n);
		return n as usize;
	}

	/// Append value to the end of T_ARRAY sciter::value.
	pub fn push<T: Into<Value>>(&mut self, src: T) {
		(_API.ValueNthElementValueSet)(self.as_ptr(), self.len() as INT, src.into().as_cptr());
	}

	/// Insert or set value at given `index` of T_ARRAY, T_MAP, T_FUNCTION and T_OBJECT sciter::value.
	pub fn set<T: Into<Value>>(&mut self, index: usize, src: T) {
		(_API.ValueNthElementValueSet)(self.as_ptr(), index as INT, src.into().as_cptr());
	}

	/// Retreive value of sub-element at `index`
	///
	/// * `T_ARRAY` - nth element of the array;
	/// * `T_MAP` - value of nth key/value pair in the map;
	/// * `T_FUNCTION` - value of nth argument of the function.
	///
	pub fn get(&self, index: usize) -> Value {
		let mut v = Value::new();
		(_API.ValueNthElementValue)(self.as_cptr(), index as INT, v.as_ptr());
		return v;
	}

	/// Insert or set value of sub-element by key.
	///
	/// * if it is a map - sets named value in the map;
	/// * if it is a function - sets named argument of the function;
	/// * if it is a object - sets value of property of the object;
	/// * otherwise it converts this to map and adds key/value to it.
	///
	pub fn set_item<TKey: Into<Value>, TValue: Into<Value>>(&mut self, key: TKey, value: TValue) {
		(_API.ValueSetValueToKey)(self.as_ptr(), key.into().as_cptr(), value.into().as_cptr());
	}

	/// Retrieve the value of a sub-element by key.
	pub fn get_item<T: Into<Value>>(&self, key: T) -> Value {
		let mut v = Value::new();
		(_API.ValueGetValueOfKey)(self.as_cptr(), key.into().as_cptr(), v.as_ptr());
		return v;
	}

	/// Retrieve the key of a sub-element by index.
	pub fn key_at(&self, index: usize) -> Value {
		let mut v = Value::new();
		(_API.ValueNthElementKey)(self.as_cptr(), index as INT, v.as_ptr());
		return v;
	}

	/// An iterator visiting all keys of key/value pairs in the map.
	///
	/// * `T_MAP` - keys of key/value pairs in the map;
	/// * `T_OBJECT` - names of key/value properties in the object;
	/// * `T_FUNCTION` - names of arguments of the function (if any).
	///
	pub fn keys(&self) -> KeyIterator {
		KeyIterator {
			base: self,
			index: 0,
			count: self.len(),
		}
	}

	/// An iterator visiting all values in arbitrary order.
	///
	/// * `T_ARRAY` - elements of the array;
	/// * `T_MAP` - values of key/value pairs in the map;
	/// * `T_OBJECT` - values of key/value properties in the object;
	/// * `T_FUNCTION` - values of arguments of the function.
	///
	pub fn values(&self) -> SeqIterator {
		SeqIterator {
			base: self,
			index: 0,
			count: self.len(),
		}
	}

	/// An iterator visiting all key-value pairs in arbitrary order.
	///
	/// The iterator element type is `(Value, Value)`.
	/// The `Value` must has a key-value type (map, object, function).
	pub fn items(&self) -> Vec<(Value, Value)> {
		type Pair = Vec<(Value, Value)>;
		let result = Box::new(Vec::with_capacity(self.len()));

		extern "system" fn on_pair(param: LPVOID, pkey: *const VALUE, pval: *const VALUE) -> BOOL {
			assert!(!param.is_null());
			unsafe {
				let mut result = Box::from_raw(param as *mut Pair);
				let src = (Value::copy_from(pkey), Value::copy_from(pval));
				result.push(src);
				Box::into_raw(result);	// prevent free
			}
			return true as BOOL;
		}

		let ptr = Box::into_raw(result);
		(_API.ValueEnumElements)(self.as_cptr(), on_pair, ptr as LPVOID);

		let result = unsafe { Box::from_raw(ptr) };
		return *result;
	}

	/// Value to integer.
	pub fn to_int(&self) -> Option<i32> {
		let mut val = 0i32;
		match (_API.ValueIntData)(self.as_cptr(), &mut val) {
			VALUE_RESULT::OK => Some(val),
			_ => None
		}
	}

	/// Value to bool.
	pub fn to_bool(&self) -> Option<bool> {
		let mut val = 0i32;
		match (_API.ValueIntData)(self.as_cptr(), &mut val) {
			VALUE_RESULT::OK => Some(val != 0),
			_ => None
		}
	}

	/// Value to float.
	pub fn to_float(&self) -> Option<f64> {
		let mut val = 0f64;
		match (_API.ValueFloatData)(self.as_cptr(), &mut val) {
			VALUE_RESULT::OK => Some(val),
			_ => None
		}
	}

	/// Value to color.
	pub fn to_color(&self) -> Option<u32> {
		let mut val = 0i32;
		match (_API.ValueIntData)(self.as_cptr(), &mut val) {
			VALUE_RESULT::OK => Some(val as u32),
			_ => None
		}
	}

	/// Value to duration.
	pub fn to_duration(&self) -> Option<f64> {
		let mut val = 0f64;
		match (_API.ValueFloatData)(self.as_cptr(), &mut val) {
			VALUE_RESULT::OK => Some(val),
			_ => None
		}
	}

	/// Value to angle.
	pub fn to_angle(&self) -> Option<f64> {
		let mut val = 0f64;
		match (_API.ValueFloatData)(self.as_cptr(), &mut val) {
			VALUE_RESULT::OK => Some(val),
			_ => None
		}
	}

	/// Value as string for T_STRING type.
	pub fn as_string(&self) -> Option<String> {
		let mut s = 0 as LPCWSTR;
		let mut n = 0 as UINT;
		match (_API.ValueStringData)(self.as_cptr(), &mut s, &mut n) {
			VALUE_RESULT::OK => Some(::utf::w2sn(s, n as usize)),
			_ => None
		}
	}

	/// Value to json string (converted in-place). _Subject to change._
	pub fn into_string(mut self) -> String {
		(_API.ValueToString)(self.as_ptr(), VALUE_STRING_CVT_TYPE::JSON_LITERAL);
		return self.as_string().unwrap();
	}

	/// Value as byte slice for T_BYTES type.
	pub fn as_bytes(&self) -> Option<&[u8]> {
		let mut s = 0 as LPCBYTE;
		let mut n = 0 as UINT;
		match (_API.ValueBinaryData)(self.as_cptr(), &mut s, &mut n) {
			VALUE_RESULT::OK => Some(unsafe { ::std::slice::from_raw_parts(s, n as usize) }),
			_ => None
		}
	}

	/// Value to byte vector for T_BYTES type.
	pub fn to_bytes(&self) -> Option<Vec<u8>> {
		match self.as_bytes() {
			Some(r) => Some(r.to_owned()),
			None => None,
		}
	}

	/// Function invocation for T_OBJECT/UT_OBJECT_FUNCTION.
	///
	/// Calls the tiscript function or method holded at `Value` with context of `this` object
	/// that will be known as _this_ inside that function (it is optional for global functions).
	/// `name` here is an url or name of the script - used for error reporting in the script.
	/// You can use the `make_args!(a,b,c)` macro which help you construct script arguments from Rust types.
	pub fn call(&self, this: Option<Value>, args: &[Value], name: Option<&str>) -> Result<Value, VALUE_RESULT> {
		let mut rv = Value::new();
		let argv = Value::pack_args(args);
		let (name,_) = s2w!(name.unwrap_or(""));
		let ok = (_API.ValueInvoke)(self.as_cptr(), this.unwrap_or_default().as_ptr(),
			argv.len() as UINT, argv.as_ptr(), rv.as_ptr(), name.as_ptr());
		match ok {
			VALUE_RESULT::OK => Ok(rv),
			_ => Err(ok)
		}
	}

	#[doc(hidden)]
	pub fn pack_to(&self, dst: &mut VALUE) {
		(_API.ValueCopy)(dst, self.as_cptr());
	}

	#[doc(hidden)]
	pub fn pack_args(args: &[Value]) -> Vec<VALUE> {
		let argc = args.len();
		let mut argv: Vec<VALUE> = Vec::with_capacity(argc);
		argv.resize(argc, VALUE::default());
		for i in 0..argc {
			args[i].pack_to(&mut argv[i]);
		}
		return argv;
	}

	#[doc(hidden)]
	pub unsafe fn unpack_from(args: * const VALUE, count: UINT) -> Vec<Value> {
		let argc = count as usize;
		let mut argv: Vec<Value> = Vec::with_capacity(argc);
		assert!(argc == 0 || !args.is_null());
		let args = ::std::slice::from_raw_parts(args, argc);
		for arg in args {
			argv.push(Value::copy_from(arg));
		}
		return argv;
	}

	#[doc(hidden)]
	unsafe fn copy_from(ptr: *const VALUE) -> Value {
		let mut v = Value::new();
		(_API.ValueCopy)(v.as_ptr(), ptr);
		return v;
	}

	fn ensure_tmp_mut(&self) -> &mut Value {
		let cp = self as *const Value;
		let mp = cp as *mut Value;
		let me = unsafe { &mut *mp };
		return me.ensure_tmp();
	}

	fn ensure_tmp(&mut self) -> &mut Value {
		if self.tmp.is_null() {
			let tmp = Box::new(Value::new());
			self.tmp = Box::into_raw(tmp);
		}
		return unsafe { &mut *self.tmp };
	}

	// TODO: keys, values, items

	/// Returns `true` is `self` is `undefined` or has zero elements.
	pub fn is_empty(&self) -> bool {
		self.is_undefined() || self.len() == 0
	}

	#[allow(missing_docs)]
	pub fn is_undefined(&self) -> bool {
		self.data.t == VALUE_TYPE::T_UNDEFINED
	}
	#[allow(missing_docs)]
	pub fn is_null(&self) -> bool {
		self.data.t == VALUE_TYPE::T_NULL
	}
	#[allow(missing_docs)]
	pub fn is_bool(&self) -> bool {
		self.data.t == VALUE_TYPE::T_BOOL
	}
	#[allow(missing_docs)]
	pub fn is_int(&self) -> bool {
		self.data.t == VALUE_TYPE::T_INT
	}
	#[allow(missing_docs)]
	pub fn is_float(&self) -> bool {
		self.data.t == VALUE_TYPE::T_FLOAT
	}
	#[allow(missing_docs)]
	pub fn is_bytes(&self) -> bool {
		self.data.t == VALUE_TYPE::T_BYTES
	}
	#[allow(missing_docs)]
	pub fn is_string(&self) -> bool {
		self.data.t == VALUE_TYPE::T_STRING
	}
	#[allow(missing_docs)]
	pub fn is_symbol(&self) -> bool {
		self.data.t == VALUE_TYPE::T_STRING && self.data.u == VALUE_UNIT_TYPE_STRING::SYMBOL as UINT
	}
	#[allow(missing_docs)]
	pub fn is_error_string(&self) -> bool {
		self.data.t == VALUE_TYPE::T_STRING && self.data.u == VALUE_UNIT_TYPE_STRING::ERROR as UINT
	}
	#[allow(missing_docs)]
	pub fn is_date(&self) -> bool {
		self.data.t == VALUE_TYPE::T_DATE
	}
	#[allow(missing_docs)]
	pub fn is_currency(&self) -> bool {
		self.data.t == VALUE_TYPE::T_CURRENCY
	}
	#[allow(missing_docs)]
	pub fn is_color(&self) -> bool {
		self.data.t == VALUE_TYPE::T_COLOR
	}
	#[allow(missing_docs)]
	pub fn is_duration(&self) -> bool {
		self.data.t == VALUE_TYPE::T_DURATION
	}
	#[allow(missing_docs)]
	pub fn is_angle(&self) -> bool {
		self.data.t == VALUE_TYPE::T_ANGLE
	}
	#[allow(missing_docs)]
	pub fn is_map(&self) -> bool {
		self.data.t == VALUE_TYPE::T_MAP
	}
	#[allow(missing_docs)]
	pub fn is_array(&self) -> bool {
		self.data.t == VALUE_TYPE::T_ARRAY
	}
	#[allow(missing_docs)]
	pub fn is_function(&self) -> bool {
		self.data.t == VALUE_TYPE::T_FUNCTION
	}
	#[allow(missing_docs)]
	pub fn is_native_function(&self) -> bool {
		(_API.ValueIsNativeFunctor)(self.as_cptr()) != 0
	}
	#[allow(missing_docs)]
	pub fn is_object(&self) -> bool {
		self.data.t == VALUE_TYPE::T_OBJECT
	}
	#[allow(missing_docs)]
	pub fn is_dom_element(&self) -> bool {
		self.data.t == VALUE_TYPE::T_DOM_OBJECT
	}

	fn assign_str(&mut self, val: &str, unit: VALUE_UNIT_TYPE_STRING) -> VALUE_RESULT {
		let (s,n) = s2w!(val);
		return (_API.ValueStringDataSet)(self.as_ptr(), s.as_ptr(), n, unit as UINT);
	}
}


/// Print `Value` as json string
impl ::std::fmt::Display for Value {
	fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
		let copy = self.clone();
		let re = copy.into_string();
		f.write_str(&re)
	}
}

/// Print `Value` as json string with explicit type showed.
impl ::std::fmt::Debug for Value {
	fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {

		let mut tname = format!("{:?}", self.data.t);

		if self.is_undefined() || self.is_null() {
			return f.write_str(&tname[2..].to_lowercase());

		} else if self.is_string() && self.data.u != 0 {
			// VALUE_UNIT_TYPE_STRING
			let units = [("file", 0xfffe), ("symbol", 0xffff), ("string", 0), ("error", 1), ("secure", 2)];
			let item = units.iter().find(|&&x| x.1 == self.data.u);
			tname.push_str(":");
			if item.is_some() {
				tname.push_str(item.unwrap().0);
			} else {
				tname.push_str(&self.data.u.to_string());
			}

		} else if self.is_object() {
			// VALUE_UNIT_TYPE_OBJECT
			let units = ["array", "object", "class", "native", "function", "error"];
			let u = self.data.u as usize;
			tname.push_str(":");
			if u < units.len() {
				tname.push_str(units[u]);
			} else {
				tname.push_str(&u.to_string());
			}

		} else if self.data.u != 0 {
			// VALUE_UNIT_TYPE
			// redundant? like "length:7:12px" instead of "length:12px" (7 == `UT_PX`).

			// tname.push_str(":");
			// tname.push_str(&self.data.u.to_string());
		}
		try!(f.write_str(&tname[2..].to_lowercase()));
		try!(f.write_str(":"));
		write!(f, "{}", &self)
	}
}

/// Destroy pointed value.
impl Drop for Value {
	fn drop(&mut self) {
		if !self.tmp.is_null() {
			unsafe { Box::from_raw(self.tmp) };
		}
		(_API.ValueClear)(self.as_ptr());
	}
}

/// Return default value (`undefined`).
impl Default for Value {
	fn default() -> Self {
		return Value::new();
	}
}

/// Copies value.
///
/// All allocated objects are reference counted so copying is just a matter of increasing reference counts.
impl Clone for Value {
	fn clone(&self) -> Self {
		let mut dst = Value::new();
		(_API.ValueCopy)(dst.as_ptr(), self.as_cptr());
		return dst;
	}
}

/// Compare two values.
impl ::std::cmp::PartialEq for Value {
	fn eq(&self, other: &Self) -> bool {
		match (_API.ValueCompare)(self.as_cptr(), other.as_cptr()) {
			VALUE_RESULT::OK_TRUE => true,
			// VALUE_RESULT::OK => false,
			_ => false
		}
	}
}

/// Get item by index for array type.
impl ::std::ops::Index<usize> for Value {
	type Output = Value;
	fn index(&self, index: usize) -> &Self::Output {
		let tmp = self.ensure_tmp_mut();
		(_API.ValueNthElementValue)(self.as_cptr(), index as INT, tmp.as_mut_ptr());
		return tmp;
	}
}

/// Set item by index for array type.
#[cfg(notworking)]
impl ::std::ops::IndexMut<usize> for Value {
	fn index_mut(&mut self, index: usize) -> &mut Value {
		let tmp = self.ensure_tmp_mut();
		(_API.ValueNthElementValue)(self.as_cptr(), index as INT, tmp.as_ptr());
		return tmp;
	}
}

/// Get item by key for map type.
impl ::std::ops::Index<Value> for Value {
	type Output = Value;
	fn index(&self, key: Value) -> &Self::Output {
		let tmp = self.ensure_tmp_mut();
		(_API.ValueGetValueOfKey)(self.as_cptr(), key.as_cptr(), tmp.as_mut_ptr());
		return tmp;
	}
}

/// Get item by string key for map type.
impl ::std::ops::Index<&'static str> for Value {
	type Output = Value;
	fn index(&self, key: &'static str) -> &Self::Output {
		let tmp = self.ensure_tmp_mut();
		(_API.ValueGetValueOfKey)(self.as_cptr(), Value::from(key).as_cptr(), tmp.as_mut_ptr());
		return tmp;
	}
}

/// Set item by key for map type.
#[cfg(notworking)]
impl ::std::ops::IndexMut<Value> for Value {
	fn index_mut<'a>(&'a mut self, key: Value) -> &'a mut Value {
		let ptr = self.as_ptr();
		let tmp = self.ensure_tmp();
		(_API.ValueSetValueToKey)(ptr, key.as_cptr(), tmp.as_ptr());
		return tmp;
	}
}

/// Value from integer.
impl From<i32> for Value {
	// Note that there is no generic 64-bit integers at Sciter, only Date/Currency types.
	// There is a double (f64) for large numbers as workaround.
	fn from(val: i32) -> Self {
		let mut me = Value::new();
		(_API.ValueIntDataSet)(me.as_ptr(), val as i32, VALUE_TYPE::T_INT as UINT, 0);
		return me;
	}
}

/// Value from float.
impl From<f64> for Value {
	fn from(val: f64) -> Self {
		let mut me = Value::new();
		(_API.ValueFloatDataSet)(me.as_ptr(), val as f64, VALUE_TYPE::T_FLOAT as UINT, 0);
		return me;
	}
}

/// Value from bool.
impl From<bool> for Value {
	fn from(val: bool) -> Self {
		let mut me = Value::new();
		(_API.ValueIntDataSet)(me.as_ptr(), val as INT, VALUE_TYPE::T_BOOL as UINT, 0);
		return me;
	}
}

/// Value from string.
impl<'a> From<&'a str> for Value {
	fn from(val: &'a str) -> Self {
		let mut me = Value::new();
		me.assign_str(val, VALUE_UNIT_TYPE_STRING::STRING);
		return me;
	}
}

/// Value from string.
impl From<String> for Value {
	fn from(val: String) -> Self {
		let mut me = Value::new();
		me.assign_str(&val, VALUE_UNIT_TYPE_STRING::STRING);
		return me;
	}
}

/// Value from json string.
impl ::std::str::FromStr for Value {
	type Err = VALUE_RESULT;
	fn from_str(val: &str) -> Result<Self, Self::Err> {
		Value::parse(val).or(Err(VALUE_RESULT::BAD_PARAMETER))
	}
}

/// Value from binary array (sequence of bytes).
impl<'a> From<&'a [u8]> for Value {
	fn from(val: &'a [u8]) -> Self {
		let mut me = Value::new();
		(_API.ValueBinaryDataSet)(me.as_ptr(), val.as_ptr(), val.len() as UINT, VALUE_TYPE::T_BYTES as UINT, 0);
		return me;
	}
}

/// Value from sequence of `i32`.
impl ::std::iter::FromIterator<i32> for Value {
	fn from_iter<I: IntoIterator<Item=i32>>(iterator: I) -> Self {
		let mut v = Value::new();
		for i in iterator {
			v.push(Value::from(i));
		}
		return v;
	}
}

/// Value from sequence of `f64`.
impl ::std::iter::FromIterator<f64> for Value {
	fn from_iter<I: IntoIterator<Item=f64>>(iterator: I) -> Self {
		let mut v = Value::new();
		for i in iterator {
			v.push(Value::from(i));
		}
		return v;
	}
}

/// Value from sequence of `&str`.
impl<'a> ::std::iter::FromIterator<&'a str> for Value {
	fn from_iter<I: IntoIterator<Item=&'a str>>(iterator: I) -> Self {
		let mut v = Value::new();
		for i in iterator {
			v.push(Value::from(i));
		}
		return v;
	}
}

/// Value from sequence of `String`.
impl ::std::iter::FromIterator<String> for Value {
	fn from_iter<I: IntoIterator<Item=String>>(iterator: I) -> Self {
		let mut v = Value::new();
		for i in iterator {
			v.push(Value::from(i));
		}
		return v;
	}
}

/// Value from function.
impl<F> From<F> for Value where F: Fn(&[Value]) -> Value {
	fn from(f: F) -> Value {
		let mut v = Value::new();
		let boxed = Box::new(f);
		let ptr = Box::into_raw(boxed);
		(_API.ValueNativeFunctorSet)(v.as_ptr(), _functor_invoke::<F>, _functor_release::<F>, ptr as LPVOID);
		return v;
	}
}

extern "C" fn _functor_release<F>(tag: LPVOID)
{
	// reconstruct handler from pointer
	let ptr = tag as *mut F;
	let boxed = unsafe { Box::from_raw(ptr) };
	// and forget it
	drop(boxed);
}

extern "C" fn _functor_invoke<F>(tag: LPVOID, argc: UINT, argv: *const VALUE, retval: *mut VALUE) where F: Fn(&[Value]) -> Value
{
	// reconstruct handler from pointer
	let ptr = tag as *mut F;
	let me = unsafe { &mut *ptr };
	let retval = unsafe { &mut *retval };
	let args = unsafe { Value::unpack_from(argv, argc) };
	let rv = me(&args);
	rv.pack_to(retval)
}


/// Helper trait
pub trait FromValue {
	/// Converts value to specified type.
	fn from_value(v: &Value) -> Option<Self> where Self: Sized;
}

impl FromValue for Value {
	fn from_value(v: &Value) -> Option<Self> {
		Some(v.clone())
	}
}

impl FromValue for bool {
	fn from_value(v: &Value) -> Option<Self> {
		v.to_bool()
	}
}

impl FromValue for i32 {
	fn from_value(v: &Value) -> Option<Self> {
		v.to_int()
	}
}

impl FromValue for f64 {
	fn from_value(v: &Value) -> Option<Self> {
		v.to_float()
	}
}

impl FromValue for Vec<u8> {
	fn from_value(v: &Value) -> Option<Self> {
		v.to_bytes()
	}
}

impl FromValue for String {
	fn from_value(v: &Value) -> Option<Self> {
		v.as_string()
	}
}


/// An iterator visiting all keys of key/value pairs in the map-like `Value` objects.
pub struct KeyIterator<'a> {
	base: &'a Value,
	index: usize,
	count: usize,
}

impl<'a> ::std::iter::Iterator for KeyIterator<'a> {
	type Item = Value;

	fn next(&mut self) -> Option<Self::Item> {
		if self.index < self.count {
			self.index += 1;
			Some(self.base.key_at(self.index - 1))
		} else {
			None
		}
	}

	fn size_hint(&self) -> (usize, Option<usize>) {
		let remain = self.count - self.index;
		(remain, Some(remain))
	}

	fn count(self) -> usize {
		self.count
	}
}

/// An iterator able to yield keys from both `Value`'s ends.
impl<'a> ::std::iter::DoubleEndedIterator for KeyIterator<'a> {
	fn next_back(&mut self) -> Option<Self::Item> {
		if self.index == self.count || self.count == 0 {
			None
		} else {
			self.count -= 1;
			Some(self.base.key_at(self.count))
		}
	}
}



/// An iterator over the sub-elements of a `Value`.
pub struct SeqIterator<'a> {
	base: &'a Value,
	index: usize,
	count: usize,
}

impl<'a> ::std::iter::Iterator for SeqIterator<'a> {
	type Item = Value;

	fn next(&mut self) -> Option<Self::Item> {
		if self.index < self.count {
			self.index += 1;
			Some(self.base.get(self.index - 1))
		} else {
			None
		}
	}

	fn size_hint(&self) -> (usize, Option<usize>) {
		let remain = self.count - self.index;
		(remain, Some(remain))
	}

	fn count(self) -> usize {
		self.count
	}
}

/// An iterator able to yield sub-elements from both `Value`'s ends.
impl<'a> ::std::iter::DoubleEndedIterator for SeqIterator<'a> {
	fn next_back(&mut self) -> Option<Self::Item> {
		if self.index == self.count || self.count == 0 {
			None
		} else {
			self.count -= 1;
			Some(self.base.get(self.count))
		}
	}
}

/// Conversion into an `Iterator`.
///
/// Adds the `for` loop syntax support: `for subitem in &value {]`.
impl<'a> ::std::iter::IntoIterator for &'a Value {
	type Item = Value;
	type IntoIter = SeqIterator<'a>;

	fn into_iter(self) -> Self::IntoIter {
		self.values()
	}
}




#[cfg(test)]
mod tests {
	#![allow(unused_imports)]

	use super::{Value, FromValue};
	use capi::scvalue::{VALUE, VALUE_TYPE};
	use std::mem;
	use ::{_API};

	fn check1(a: i32) {
		assert_eq!(a, 12);
	}

	#[test]
	fn test_from_value() {
		let v = Value::from(12);
		check1(
			match FromValue::from_value(&v) {
				Some(x) => { x },
				None => { return; }
			}
		);
	}

	#[test]
	fn test_value_layout() {
		assert_eq!(mem::size_of::<VALUE_TYPE>(), 4);
		assert_eq!(mem::size_of::<VALUE>(), 16);
	}

	#[test]
	fn test_abi() {

		let mut data = VALUE { t: VALUE_TYPE::T_UNDEFINED, u: 0, d: 0 };
		assert_eq!(data.t, VALUE_TYPE::T_UNDEFINED);

		(_API.ValueInit)(&mut data);
		assert_eq!(data.t, VALUE_TYPE::T_UNDEFINED);

		(_API.ValueClear)(&mut data);
		assert_eq!(data.t, VALUE_TYPE::T_UNDEFINED);
	}
}