aboutsummaryrefslogtreecommitdiff
path: root/doc/client_lua_api.txt
blob: 24d23b0b5f6dfeb05e59196169945c1202eb9ed9 (plain)
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
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
Minetest Lua Client Modding API Reference 5.5.0
================================================
* More information at <http://www.minetest.net/>
* Developer Wiki: <http://dev.minetest.net/>

Introduction
------------

** WARNING: The client API is currently unstable, and may break/change without warning. **

Content and functionality can be added to Minetest 0.4.15-dev+ by using Lua
scripting in run-time loaded mods.

A mod is a self-contained bunch of scripts, textures and other related
things that is loaded by and interfaces with Minetest.

Transferring client-sided mods from the server to the client is planned, but not implemented yet.

If you see a deficiency in the API, feel free to attempt to add the
functionality in the engine and API. You can send such improvements as
source code patches on GitHub (https://github.com/minetest/minetest).

Programming in Lua
------------------
If you have any difficulty in understanding this, please read
[Programming in Lua](http://www.lua.org/pil/).

Startup
-------
Mods are loaded during client startup from the mod load paths by running
the `init.lua` scripts in a shared environment.

In order to load client-side mods, the following conditions need to be satisfied:

1) `$path_user/minetest.conf` contains the setting `enable_client_modding = true`

2) The client-side mod located in `$path_user/clientmods/<modname>` is added to
    `$path_user/clientmods/mods.conf` as `load_mod_<modname> = true`.

Note: Depending on the remote server's settings, client-side mods might not
be loaded or have limited functionality. See setting `csm_restriction_flags` for reference.

Paths
-----
* `RUN_IN_PLACE=1` (Windows release, local build)
    * `$path_user`: `<build directory>`
    * `$path_share`: `<build directory>`
* `RUN_IN_PLACE=0`: (Linux release)
    * `$path_share`:
        * Linux: `/usr/share/minetest`
        * Windows: `<install directory>/minetest-0.4.x`
    * `$path_user`:
        * Linux: `$HOME/.minetest`
        * Windows: `C:/users/<user>/AppData/minetest` (maybe)

Mod load path
-------------
Generic:

* `$path_share/clientmods/`
* `$path_user/clientmods/` (User-installed mods)

In a run-in-place version (e.g. the distributed windows version):

* `minetest-0.4.x/clientmods/` (User-installed mods)

On an installed version on Linux:

* `/usr/share/minetest/clientmods/`
* `$HOME/.minetest/clientmods/` (User-installed mods)

Modpack support
----------------

Mods can be put in a subdirectory, if the parent directory, which otherwise
should be a mod, contains a file named `modpack.conf`.
The file is a key-value store of modpack details.

* `name`: The modpack name.
* `description`: Description of mod to be shown in the Mods tab of the main
                 menu.

Mod directory structure
------------------------

    clientmods
    ├── modname
    │   ├── mod.conf
    │   ├── init.lua
    └── another

### modname

The location of this directory.

### mod.conf

An (optional) settings file that provides meta information about the mod.

* `name`: The mod name. Allows Minetest to determine the mod name even if the
          folder is wrongly named.
* `description`: Description of mod to be shown in the Mods tab of the main
                 menu.
* `depends`: A comma separated list of dependencies. These are mods that must be
             loaded before this mod.
* `optional_depends`: A comma separated list of optional dependencies.
                      Like a dependency, but no error if the mod doesn't exist.

### `init.lua`

The main Lua script. Running this script should register everything it
wants to register. Subsequent execution depends on minetest calling the
registered callbacks.

**NOTE**: Client mods currently can't provide textures, sounds, or models by
themselves. Any media referenced in function calls must already be loaded
(provided by mods that exist on the server).

Naming convention for registered textual names
----------------------------------------------
Registered names should generally be in this format:

    "modname:<whatever>" (<whatever> can have characters a-zA-Z0-9_)

This is to prevent conflicting names from corrupting maps and is
enforced by the mod loader.

### Example
In the mod `experimental`, there is the ideal item/node/entity name `tnt`.
So the name should be `experimental:tnt`.

Enforcement can be overridden by prefixing the name with `:`. This can
be used for overriding the registrations of some other mod.

Example: Any mod can redefine `experimental:tnt` by using the name

    :experimental:tnt

when registering it.
(also that mod is required to have `experimental` as a dependency)

The `:` prefix can also be used for maintaining backwards compatibility.

Sounds
------
**NOTE: Connecting sounds to objects is not implemented.**

Only Ogg Vorbis files are supported.

For positional playing of sounds, only single-channel (mono) files are
supported. Otherwise OpenAL will play them non-positionally.

Mods should generally prefix their sounds with `modname_`, e.g. given
the mod name "`foomod`", a sound could be called:

    foomod_foosound.ogg

Sounds are referred to by their name with a dot, a single digit and the
file extension stripped out. When a sound is played, the actual sound file
is chosen randomly from the matching sounds.

When playing the sound `foomod_foosound`, the sound is chosen randomly
from the available ones of the following files:

* `foomod_foosound.ogg`
* `foomod_foosound.0.ogg`
* `foomod_foosound.1.ogg`
* (...)
* `foomod_foosound.9.ogg`

Examples of sound parameter tables:

    -- Play locationless
    {
        gain = 1.0, -- default
    }
    -- Play locationless, looped
    {
        gain = 1.0, -- default
        loop = true,
    }
    -- Play in a location
    {
        pos = {x = 1, y = 2, z = 3},
        gain = 1.0, -- default
    }
    -- Play connected to an object, looped
    {
        object = <an ObjectRef>,
        gain = 1.0, -- default
        loop = true,
    }

Looped sounds must either be connected to an object or played locationless.

### SimpleSoundSpec
* e.g. `""`
* e.g. `"default_place_node"`
* e.g. `{}`
* e.g. `{name = "default_place_node"}`
* e.g. `{name = "default_place_node", gain = 1.0}`

Representations of simple things
--------------------------------

### Position/vector

    {x=num, y=num, z=num}

For helper functions see "Vector helpers".

### pointed_thing
* `{type="nothing"}`
* `{type="node", under=pos, above=pos}`
* `{type="object", id=ObjectID}`

Flag Specifier Format
---------------------
Flags using the standardized flag specifier format can be specified in either of
two ways, by string or table.

The string format is a comma-delimited set of flag names; whitespace and
unrecognized flag fields are ignored. Specifying a flag in the string sets the
flag, and specifying a flag prefixed by the string `"no"` explicitly
clears the flag from whatever the default may be.

In addition to the standard string flag format, the schematic flags field can
also be a table of flag names to boolean values representing whether or not the
flag is set. Additionally, if a field with the flag name prefixed with `"no"`
is present, mapped to a boolean of any value, the specified flag is unset.

E.g. A flag field of value

    {place_center_x = true, place_center_y=false, place_center_z=true}

is equivalent to

    {place_center_x = true, noplace_center_y=true, place_center_z=true}

which is equivalent to

    "place_center_x, noplace_center_y, place_center_z"

or even

    "place_center_x, place_center_z"

since, by default, no schematic attributes are set.

Formspec
--------
Formspec defines a menu. It is a string, with a somewhat strange format.

Spaces and newlines can be inserted between the blocks, as is used in the
examples.

### Examples

#### Chest

    size[8,9]
    list[context;main;0,0;8,4;]
    list[current_player;main;0,5;8,4;]

#### Furnace

    size[8,9]
    list[context;fuel;2,3;1,1;]
    list[context;src;2,1;1,1;]
    list[context;dst;5,1;2,2;]
    list[current_player;main;0,5;8,4;]

#### Minecraft-like player inventory

    size[8,7.5]
    image[1,0.6;1,2;player.png]
    list[current_player;main;0,3.5;8,4;]
    list[current_player;craft;3,0;3,3;]
    list[current_player;craftpreview;7,1;1,1;]

### Elements

#### `size[<W>,<H>,<fixed_size>]`
* Define the size of the menu in inventory slots
* `fixed_size`: `true`/`false` (optional)
* deprecated: `invsize[<W>,<H>;]`

#### `container[<X>,<Y>]`
* Start of a container block, moves all physical elements in the container by (X, Y)
* Must have matching container_end
* Containers can be nested, in which case the offsets are added
  (child containers are relative to parent containers)

#### `container_end[]`
* End of a container, following elements are no longer relative to this container

#### `list[<inventory location>;<list name>;<X>,<Y>;<W>,<H>;]`
* Show an inventory list

#### `list[<inventory location>;<list name>;<X>,<Y>;<W>,<H>;<starting item index>]`
* Show an inventory list

#### `listring[<inventory location>;<list name>]`
* Allows to create a ring of inventory lists
* Shift-clicking on items in one element of the ring
  will send them to the next inventory list inside the ring
* The first occurrence of an element inside the ring will
  determine the inventory where items will be sent to

#### `listring[]`
* Shorthand for doing `listring[<inventory location>;<list name>]`
  for the last two inventory lists added by list[...]

#### `listcolors[<slot_bg_normal>;<slot_bg_hover>]`
* Sets background color of slots as `ColorString`
* Sets background color of slots on mouse hovering

#### `listcolors[<slot_bg_normal>;<slot_bg_hover>;<slot_border>]`
* Sets background color of slots as `ColorString`
* Sets background color of slots on mouse hovering
* Sets color of slots border

#### `listcolors[<slot_bg_normal>;<slot_bg_hover>;<slot_border>;<tooltip_bgcolor>;<tooltip_fontcolor>]`
* Sets background color of slots as `ColorString`
* Sets background color of slots on mouse hovering
* Sets color of slots border
* Sets default background color of tooltips
* Sets default font color of tooltips

#### `tooltip[<gui_element_name>;<tooltip_text>;<bgcolor>,<fontcolor>]`
* Adds tooltip for an element
* `<bgcolor>` tooltip background color as `ColorString` (optional)
* `<fontcolor>` tooltip font color as `ColorString` (optional)

#### `image[<X>,<Y>;<W>,<H>;<texture name>]`
* Show an image
* Position and size units are inventory slots

#### `item_image[<X>,<Y>;<W>,<H>;<item name>]`
* Show an inventory image of registered item/node
* Position and size units are inventory slots

#### `bgcolor[<color>;<fullscreen>]`
* Sets background color of formspec as `ColorString`
* If `true`, the background color is drawn fullscreen (does not effect the size of the formspec)

#### `background[<X>,<Y>;<W>,<H>;<texture name>]`
* Use a background. Inventory rectangles are not drawn then.
* Position and size units are inventory slots
* Example for formspec 8x4 in 16x resolution: image shall be sized
  8 times 16px  times  4 times 16px.

#### `background[<X>,<Y>;<W>,<H>;<texture name>;<auto_clip>]`
* Use a background. Inventory rectangles are not drawn then.
* Position and size units are inventory slots
* Example for formspec 8x4 in 16x resolution:
  image shall be sized 8 times 16px  times  4 times 16px
* If `true` the background is clipped to formspec size
  (`x` and `y` are used as offset values, `w` and `h` are ignored)

#### `pwdfield[<X>,<Y>;<W>,<H>;<name>;<label>]`
* Textual password style field; will be sent to server when a button is clicked
* When enter is pressed in field, fields.key_enter_field will be sent with the name
  of this field.
* `x` and `y` position the field relative to the top left of the menu
* `w` and `h` are the size of the field
* Fields are a set height, but will be vertically centred on `h`
* Position and size units are inventory slots
* `name` is the name of the field as returned in fields to `on_receive_fields`
* `label`, if not blank, will be text printed on the top left above the field
* See field_close_on_enter to stop enter closing the formspec

#### `field[<X>,<Y>;<W>,<H>;<name>;<label>;<default>]`
* Textual field; will be sent to server when a button is clicked
* When enter is pressed in field, fields.key_enter_field will be sent with the name
  of this field.
* `x` and `y` position the field relative to the top left of the menu
* `w` and `h` are the size of the field
* Fields are a set height, but will be vertically centred on `h`
* Position and size units are inventory slots
* `name` is the name of the field as returned in fields to `on_receive_fields`
* `label`, if not blank, will be text printed on the top left above the field
* `default` is the default value of the field
    * `default` may contain variable references such as `${text}'` which
      will fill the value from the metadata value `text`
    * **Note**: no extra text or more than a single variable is supported ATM.
* See field_close_on_enter to stop enter closing the formspec

#### `field[<name>;<label>;<default>]`
* As above, but without position/size units
* When enter is pressed in field, fields.key_enter_field will be sent with the name
  of this field.
* Special field for creating simple forms, such as sign text input
* Must be used without a `size[]` element
* A "Proceed" button will be added automatically
* See field_close_on_enter to stop enter closing the formspec

#### `field_close_on_enter[<name>;<close_on_enter>]`
* <name> is the name of the field
* if <close_on_enter> is false, pressing enter in the field will submit the form but not close it
* defaults to true when not specified (ie: no tag for a field)

#### `textarea[<X>,<Y>;<W>,<H>;<name>;<label>;<default>]`
* Same as fields above, but with multi-line input

#### `label[<X>,<Y>;<label>]`
* `x` and `y` work as per field
* `label` is the text on the label
* Position and size units are inventory slots

#### `vertlabel[<X>,<Y>;<label>]`
* Textual label drawn vertically
* `x` and `y` work as per field
* `label` is the text on the label
* Position and size units are inventory slots

#### `button[<X>,<Y>;<W>,<H>;<name>;<label>]`
* Clickable button. When clicked, fields will be sent.
* `x`, `y` and `name` work as per field
* `w` and `h` are the size of the button
* Fixed button height. It will be vertically centred on `h`
* `label` is the text on the button
* Position and size units are inventory slots

#### `image_button[<X>,<Y>;<W>,<H>;<texture name>;<name>;<label>]`
* `x`, `y`, `w`, `h`, and `name` work as per button
* `texture name` is the filename of an image
* Position and size units are inventory slots

#### `image_button[<X>,<Y>;<W>,<H>;<texture name>;<name>;<label>;<noclip>;<drawborder>;<pressed texture name>]`
* `x`, `y`, `w`, `h`, and `name` work as per button
* `texture name` is the filename of an image
* Position and size units are inventory slots
* `noclip=true` means the image button doesn't need to be within specified formsize
* `drawborder`: draw button border or not
* `pressed texture name` is the filename of an image on pressed state

#### `item_image_button[<X>,<Y>;<W>,<H>;<item name>;<name>;<label>]`
* `x`, `y`, `w`, `h`, `name` and `label` work as per button
* `item name` is the registered name of an item/node,
   tooltip will be made out of its description
   to override it use tooltip element
* Position and size units are inventory slots

#### `button_exit[<X>,<Y>;<W>,<H>;<name>;<label>]`
* When clicked, fields will be sent and the form will quit.

#### `image_button_exit[<X>,<Y>;<W>,<H>;<texture name>;<name>;<label>]`
* When clicked, fields will be sent and the form will quit.

#### `textlist[<X>,<Y>;<W>,<H>;<name>;<listelem 1>,<listelem 2>,...,<listelem n>]`
* Scrollable item list showing arbitrary text elements
* `x` and `y` position the itemlist relative to the top left of the menu
* `w` and `h` are the size of the itemlist
* `name` fieldname sent to server on doubleclick value is current selected element
* `listelements` can be prepended by #color in hexadecimal format RRGGBB (only),
     * if you want a listelement to start with "#" write "##".

#### `textlist[<X>,<Y>;<W>,<H>;<name>;<listelem 1>,<listelem 2>,...,<listelem n>;<selected idx>;<transparent>]`
* Scrollable itemlist showing arbitrary text elements
* `x` and `y` position the item list relative to the top left of the menu
* `w` and `h` are the size of the item list
* `name` fieldname sent to server on doubleclick value is current selected element
* `listelements` can be prepended by #RRGGBB (only) in hexadecimal format
     * if you want a listelement to start with "#" write "##"
* Index to be selected within textlist
* `true`/`false`: draw transparent background
* See also `minetest.explode_textlist_event` (main menu: `engine.explode_textlist_event`)

#### `tabheader[<X>,<Y>;<name>;<caption 1>,<caption 2>,...,<caption n>;<current_tab>;<transparent>;<draw_border>]`
* Show a tab**header** at specific position (ignores formsize)
* `x` and `y` position the itemlist relative to the top left of the menu
* `name` fieldname data is transferred to Lua
* `caption 1`...: name shown on top of tab
* `current_tab`: index of selected tab 1...
* `transparent` (optional): show transparent
* `draw_border` (optional): draw border

#### `box[<X>,<Y>;<W>,<H>;<color>]`
* Simple colored semitransparent box
* `x` and `y` position the box relative to the top left of the menu
* `w` and `h` are the size of box
* `color` is color specified as a `ColorString`

#### `dropdown[<X>,<Y>;<W>;<name>;<item 1>,<item 2>, ...,<item n>;<selected idx>]`
* Show a dropdown field
* **Important note**: There are two different operation modes:
     1. handle directly on change (only changed dropdown is submitted)
     2. read the value on pressing a button (all dropdown values are available)
* `x` and `y` position of dropdown
* Width of dropdown
* Fieldname data is transferred to Lua
* Items to be shown in dropdown
* Index of currently selected dropdown item

#### `checkbox[<X>,<Y>;<name>;<label>;<selected>]`
* Show a checkbox
* `x` and `y`: position of checkbox
* `name` fieldname data is transferred to Lua
* `label` to be shown left of checkbox
* `selected` (optional): `true`/`false`

#### `scrollbar[<X>,<Y>;<W>,<H>;<orientation>;<name>;<value>]`
* Show a scrollbar
* There are two ways to use it:
     1. handle the changed event (only changed scrollbar is available)
     2. read the value on pressing a button (all scrollbars are available)
* `x` and `y`: position of trackbar
* `w` and `h`: width and height
* `orientation`:  `vertical`/`horizontal`
* Fieldname data is transferred to Lua
* Value this trackbar is set to (`0`-`1000`)
* See also `minetest.explode_scrollbar_event` (main menu: `engine.explode_scrollbar_event`)

#### `table[<X>,<Y>;<W>,<H>;<name>;<cell 1>,<cell 2>,...,<cell n>;<selected idx>]`
* Show scrollable table using options defined by the previous `tableoptions[]`
* Displays cells as defined by the previous `tablecolumns[]`
* `x` and `y`: position the itemlist relative to the top left of the menu
* `w` and `h` are the size of the itemlist
* `name`: fieldname sent to server on row select or doubleclick
* `cell 1`...`cell n`: cell contents given in row-major order
* `selected idx`: index of row to be selected within table (first row = `1`)
* See also `minetest.explode_table_event` (main menu: `engine.explode_table_event`)

#### `tableoptions[<opt 1>;<opt 2>;...]`
* Sets options for `table[]`
* `color=#RRGGBB`
     * default text color (`ColorString`), defaults to `#FFFFFF`
* `background=#RRGGBB`
     * table background color (`ColorString`), defaults to `#000000`
* `border=<true/false>`
     * should the table be drawn with a border? (default: `true`)
* `highlight=#RRGGBB`
     * highlight background color (`ColorString`), defaults to `#466432`
* `highlight_text=#RRGGBB`
     * highlight text color (`ColorString`), defaults to `#FFFFFF`
* `opendepth=<value>`
     * all subtrees up to `depth < value` are open (default value = `0`)
     * only useful when there is a column of type "tree"

#### `tablecolumns[<type 1>,<opt 1a>,<opt 1b>,...;<type 2>,<opt 2a>,<opt 2b>;...]`
* Sets columns for `table[]`
* Types: `text`, `image`, `color`, `indent`, `tree`
    * `text`:   show cell contents as text
    * `image`:  cell contents are an image index, use column options to define images
    * `color`:   cell contents are a ColorString and define color of following cell
    * `indent`: cell contents are a number and define indentation of following cell
    * `tree`:   same as indent, but user can open and close subtrees (treeview-like)
* Column options:
    * `align=<value>`
        * for `text` and `image`: content alignment within cells.
          Available values: `left` (default), `center`, `right`, `inline`
    * `width=<value>`
        * for `text` and `image`: minimum width in em (default: `0`)
        * for `indent` and `tree`: indent width in em (default: `1.5`)
    * `padding=<value>`: padding left of the column, in em (default `0.5`).
      Exception: defaults to 0 for indent columns
    * `tooltip=<value>`: tooltip text (default: empty)
    * `image` column options:
        * `0=<value>` sets image for image index 0
        * `1=<value>` sets image for image index 1
        * `2=<value>` sets image for image index 2
        * and so on; defined indices need not be contiguous empty or
          non-numeric cells are treated as `0`.
    * `color` column options:
        * `span=<value>`: number of following columns to affect (default: infinite)

**Note**: do _not_ use a element name starting with `key_`; those names are reserved to
pass key press events to formspec!

Spatial Vectors
---------------
* `vector.new(a[, b, c])`: returns a vector:
    * A copy of `a` if `a` is a vector.
    * `{x = a, y = b, z = c}`, if all `a, b, c` are defined
* `vector.direction(p1, p2)`: returns a vector
* `vector.distance(p1, p2)`: returns a number
* `vector.length(v)`: returns a number
* `vector.normalize(v)`: returns a vector
* `vector.floor(v)`: returns a vector, each dimension rounded down
* `vector.round(v)`: returns a vector, each dimension rounded to nearest int
* `vector.apply(v, func)`: returns a vector
* `vector.equals(v1, v2)`: returns a boolean

For the following functions `x` can be either a vector or a number:

* `vector.add(v, x)`: returns a vector
* `vector.subtract(v, x)`: returns a vector
* `vector.multiply(v, x)`: returns a scaled vector or Schur product
* `vector.divide(v, x)`: returns a scaled vector or Schur quotient

Helper functions
----------------
* `dump2(obj, name="_", dumped={})`
     * Return object serialized as a string, handles reference loops
* `dump(obj, dumped={})`
    * Return object serialized as a string
* `math.hypot(x, y)`
    * Get the hypotenuse of a triangle with legs x and y.
      Useful for distance calculation.
* `math.sign(x, tolerance)`
    * Get the sign of a number.
      Optional: Also returns `0` when the absolute value is within the tolerance (default: `0`)
* `string.split(str, separator=",", include_empty=false, max_splits=-1, sep_is_pattern=false)`
    * If `max_splits` is negative, do not limit splits.
    * `sep_is_pattern` specifies if separator is a plain string or a pattern (regex).
    * e.g. `string:split("a,b", ",") == {"a","b"}`
* `string:trim()`
    * e.g. `string.trim("\n \t\tfoo bar\t ") == "foo bar"`
* `minetest.wrap_text(str, limit)`: returns a string
    * Adds new lines to the string to keep it within the specified character limit
    * limit: Maximal amount of characters in one line
* `minetest.pos_to_string({x=X,y=Y,z=Z}, decimal_places))`: returns string `"(X,Y,Z)"`
    * Convert position to a printable string
      Optional: 'decimal_places' will round the x, y and z of the pos to the given decimal place.
* `minetest.string_to_pos(string)`: returns a position
    * Same but in reverse. Returns `nil` if the string can't be parsed to a position.
* `minetest.string_to_area("(X1, Y1, Z1) (X2, Y2, Z2)")`: returns two positions
    * Converts a string representing an area box into two positions
* `minetest.is_yes(arg)`
    * returns whether `arg` can be interpreted as yes
* `minetest.is_nan(arg)`
    * returns true when the passed number represents NaN.
* `table.copy(table)`: returns a table
    * returns a deep copy of `table`

Minetest namespace reference
------------------------------

### Utilities

* `minetest.get_current_modname()`: returns the currently loading mod's name, when we are loading a mod
* `minetest.get_modpath(modname)`: returns virtual path of given mod including
   the trailing separator. This is useful to load additional Lua files
   contained in your mod:
   e.g. `dofile(minetest.get_modpath(minetest.get_current_modname()) .. "stuff.lua")`
* `minetest.get_language()`: returns two strings
   * the current gettext locale
   * the current language code (the same as used for client-side translations)
* `minetest.get_version()`: returns a table containing components of the
   engine version.  Components:
    * `project`: Name of the project, eg, "Minetest"
    * `string`: Simple version, eg, "1.2.3-dev"
    * `hash`: Full git version (only set if available), eg, "1.2.3-dev-01234567-dirty"
  Use this for informational purposes only. The information in the returned
  table does not represent the capabilities of the engine, nor is it
  reliable or verifiable. Compatible forks will have a different name and
  version entirely. To check for the presence of engine features, test
  whether the functions exported by the wanted features exist. For example:
  `if minetest.check_for_falling then ... end`.
* `minetest.sha1(data, [raw])`: returns the sha1 hash of data
    * `data`: string of data to hash
    * `raw`: return raw bytes instead of hex digits, default: false
* `minetest.colorspec_to_colorstring(colorspec)`: Converts a ColorSpec to a
  ColorString. If the ColorSpec is invalid, returns `nil`.
    * `colorspec`: The ColorSpec to convert
* `minetest.get_csm_restrictions()`: returns a table of `Flags` indicating the
   restrictions applied to the current mod.
   * If a flag in this table is set to true, the feature is RESTRICTED.
   * Possible flags: `load_client_mods`, `chat_messages`, `read_itemdefs`,
                   `read_nodedefs`, `lookup_nodes`, `read_playerinfo`

### Logging
* `minetest.debug(...)`
    * Equivalent to `minetest.log(table.concat({...}, "\t"))`
* `minetest.log([level,] text)`
    * `level` is one of `"none"`, `"error"`, `"warning"`, `"action"`,
      `"info"`, or `"verbose"`.  Default is `"none"`.

### Global callback registration functions
Call these functions only at load time!

* `minetest.register_globalstep(function(dtime))`
    * Called every client environment step, usually interval of 0.1s
* `minetest.register_on_mods_loaded(function())`
    * Called just after mods have finished loading.
* `minetest.register_on_shutdown(function())`
    * Called before client shutdown
    * **Warning**: If the client terminates abnormally (i.e. crashes), the registered
      callbacks **will likely not be run**. Data should be saved at
      semi-frequent intervals as well as on server shutdown.
* `minetest.register_on_receiving_chat_message(function(message))`
    * Called always when a client receive a message
    * Return `true` to mark the message as handled, which means that it will not be shown to chat
* `minetest.register_on_sending_chat_message(function(message))`
    * Called always when a client send a message from chat
    * Return `true` to mark the message as handled, which means that it will not be sent to server
* `minetest.register_chatcommand(cmd, chatcommand definition)`
    * Adds definition to minetest.registered_chatcommands
* `minetest.unregister_chatcommand(name)`
    * Unregisters a chatcommands registered with register_chatcommand.
* `minetest.register_on_chatcommand(function(command, params))`
    * Called always when a chatcommand is triggered, before `minetest.registered_chatcommands`
      is checked to see if that the command exists, but after the input is parsed.
    * Return `true` to mark the command as handled, which means that the default
      handlers will be prevented.
* `minetest.register_on_death(function())`
    * Called when the local player dies
* `minetest.register_on_hp_modification(function(hp))`
    * Called when server modified player's HP
* `minetest.register_on_damage_taken(function(hp))`
    * Called when the local player take damages
* `minetest.register_on_formspec_input(function(formname, fields))`
    * Called when a button is pressed in the local player's inventory form
    * Newest functions are called first
    * If function returns `true`, remaining functions are not called
* `minetest.register_on_dignode(function(pos, node))`
    * Called when the local player digs a node
    * Newest functions are called first
    * If any function returns true, the node isn't dug
* `minetest.register_on_punchnode(function(pos, node))`
    * Called when the local player punches a node
    * Newest functions are called first
    * If any function returns true, the punch is ignored
* `minetest.register_on_placenode(function(pointed_thing, node))`
    * Called when a node has been placed
* `minetest.register_on_item_use(function(item, pointed_thing))`
    * Called when the local player uses an item.
    * Newest functions are called first.
    * If any function returns true, the item use is not sent to server.
* `minetest.register_on_modchannel_message(function(channel_name, sender, message))`
    * Called when an incoming mod channel message is received
    * You must have joined some channels before, and server must acknowledge the
      join request.
    * If message comes from a server mod, `sender` field is an empty string.
* `minetest.register_on_modchannel_signal(function(channel_name, signal))`
    * Called when a valid incoming mod channel signal is received
    * Signal id permit to react to server mod channel events
    * Possible values are:
      0: join_ok
      1: join_failed
      2: leave_ok
      3: leave_failed
      4: event_on_not_joined_channel
      5: state_changed
* `minetest.register_on_inventory_open(function(inventory))`
    * Called when the local player open inventory
    * Newest functions are called first
    * If any function returns true, inventory doesn't open
### Sounds
* `minetest.sound_play(spec, parameters)`: returns a handle
    * `spec` is a `SimpleSoundSpec`
    * `parameters` is a sound parameter table
* `minetest.sound_stop(handle)`
    * `handle` is a handle returned by `minetest.sound_play`
* `minetest.sound_fade(handle, step, gain)`
    * `handle` is a handle returned by `minetest.sound_play`
    * `step` determines how fast a sound will fade.
      Negative step will lower the sound volume, positive step will increase
      the sound volume.
    * `gain` the target gain for the fade.

### Timing
* `minetest.after(time, func, ...)`
    * Call the function `func` after `time` seconds, may be fractional
    * Optional: Variable number of arguments that are passed to `func`
* `minetest.get_us_time()`
    * Returns time with microsecond precision. May not return wall time.
* `minetest.get_timeofday()`
    * Returns the time of day: `0` for midnight, `0.5` for midday

### Map
* `minetest.get_node_or_nil(pos)`
    * Returns the node at the given position as table in the format
      `{name="node_name", param1=0, param2=0}`, returns `nil`
      for unloaded areas or flavor limited areas.
* `minetest.get_node_light(pos, timeofday)`
    * Gets the light value at the given position. Note that the light value
      "inside" the node at the given position is returned, so you usually want
      to get the light value of a neighbor.
    * `pos`: The position where to measure the light.
    * `timeofday`: `nil` for current time, `0` for night, `0.5` for day
    * Returns a number between `0` and `15` or `nil`
* `minetest.find_node_near(pos, radius, nodenames, [search_center])`: returns pos or `nil`
    * `radius`: using a maximum metric
    * `nodenames`: e.g. `{"ignore", "group:tree"}` or `"default:dirt"`
    * `search_center` is an optional boolean (default: `false`)
      If true `pos` is also checked for the nodes
* `minetest.find_nodes_in_area(pos1, pos2, nodenames, [grouped])`
    * `pos1` and `pos2` are the min and max positions of the area to search.
    * `nodenames`: e.g. `{"ignore", "group:tree"}` or `"default:dirt"`
    * If `grouped` is true the return value is a table indexed by node name
      which contains lists of positions.
    * If `grouped` is false or absent the return values are as follows:
      first value: Table with all node positions
      second value: Table with the count of each node with the node name
      as index
    * Area volume is limited to 4,096,000 nodes
* `minetest.find_nodes_in_area_under_air(pos1, pos2, nodenames)`: returns a
  list of positions.
    * `nodenames`: e.g. `{"ignore", "group:tree"}` or `"default:dirt"`
    * Return value: Table with all node positions with a node air above
    * Area volume is limited to 4,096,000 nodes
* `minetest.line_of_sight(pos1, pos2)`: returns `boolean, pos`
    * Checks if there is anything other than air between pos1 and pos2.
    * Returns false if something is blocking the sight.
    * Returns the position of the blocking node when `false`
    * `pos1`: First position
    * `pos2`: Second position
* `minetest.raycast(pos1, pos2, objects, liquids)`: returns `Raycast`
    * Creates a `Raycast` object.
    * `pos1`: start of the ray
    * `pos2`: end of the ray
    * `objects`: if false, only nodes will be returned. Default is `true`.
    * `liquids`: if false, liquid nodes won't be returned. Default is `false`.

* `minetest.find_nodes_with_meta(pos1, pos2)`
    * Get a table of positions of nodes that have metadata within a region
      {pos1, pos2}.
* `minetest.get_meta(pos)`
    * Get a `NodeMetaRef` at that position
* `minetest.get_node_level(pos)`
    * get level of leveled node (water, snow)
* `minetest.get_node_max_level(pos)`
    * get max available level for leveled node

### Player
* `minetest.send_chat_message(message)`
    * Act as if `message` was typed by the player into the terminal.
* `minetest.run_server_chatcommand(cmd, param)`
    * Alias for `minetest.send_chat_message("/" .. cmd .. " " .. param)`
* `minetest.clear_out_chat_queue()`
    * Clears the out chat queue
* `minetest.localplayer`
    * Reference to the LocalPlayer object. See [`LocalPlayer`](#localplayer) class reference for methods.

### Privileges
* `minetest.get_privilege_list()`
    * Returns a list of privileges the current player has in the format `{priv1=true,...}`
* `minetest.string_to_privs(str)`: returns `{priv1=true,...}`
* `minetest.privs_to_string(privs)`: returns `"priv1,priv2,..."`
    * Convert between two privilege representations

### Client Environment
* `minetest.get_player_names()`
    * Returns list of player names on server (nil if CSM_RF_READ_PLAYERINFO is enabled by server)
* `minetest.disconnect()`
    * Disconnect from the server and exit to main menu.
    * Returns `false` if the client is already disconnecting otherwise returns `true`.
* `minetest.get_server_info()`
    * Returns [server info](#server-info).
* `minetest.send_respawn()`
    * Sends a respawn request to the server.

### Storage API
* `minetest.get_mod_storage()`:
    * returns reference to mod private `StorageRef`
    * must be called during mod load time

### Mod channels
![Mod channels communication scheme](docs/mod channels.png)

* `minetest.mod_channel_join(channel_name)`
    * Client joins channel `channel_name`, and creates it, if necessary. You
      should listen from incoming messages with `minetest.register_on_modchannel_message`
      call to receive incoming messages. Warning, this function is asynchronous.

### Particles
* `minetest.add_particle(particle definition)`

* `minetest.add_particlespawner(particlespawner definition)`
    * Add a `ParticleSpawner`, an object that spawns an amount of particles over `time` seconds
    * Returns an `id`, and -1 if adding didn't succeed

* `minetest.delete_particlespawner(id)`
    * Delete `ParticleSpawner` with `id` (return value from `minetest.add_particlespawner`)

### Misc.
* `minetest.parse_json(string[, nullvalue])`: returns something
    * Convert a string containing JSON data into the Lua equivalent
    * `nullvalue`: returned in place of the JSON null; defaults to `nil`
    * On success returns a table, a string, a number, a boolean or `nullvalue`
    * On failure outputs an error message and returns `nil`
    * Example: `parse_json("[10, {\"a\":false}]")`, returns `{10, {a = false}}`
* `minetest.write_json(data[, styled])`: returns a string or `nil` and an error message
    * Convert a Lua table into a JSON string
    * styled: Outputs in a human-readable format if this is set, defaults to false
    * Unserializable things like functions and userdata are saved as null.
    * **Warning**: JSON is more strict than the Lua table format.
        1. You can only use strings and positive integers of at least one as keys.
        2. You can not mix string and integer keys.
           This is due to the fact that JSON has two distinct array and object values.
    * Example: `write_json({10, {a = false}})`, returns `"[10, {\"a\": false}]"`
* `minetest.serialize(table)`: returns a string
    * Convert a table containing tables, strings, numbers, booleans and `nil`s
      into string form readable by `minetest.deserialize`
    * Example: `serialize({foo='bar'})`, returns `'return { ["foo"] = "bar" }'`
* `minetest.deserialize(string)`: returns a table
    * Convert a string returned by `minetest.deserialize` into a table
    * `string` is loaded in an empty sandbox environment.
    * Will load functions, but they cannot access the global environment.
    * Example: `deserialize('return { ["foo"] = "bar" }')`, returns `{foo='bar'}`
    * Example: `deserialize('print("foo")')`, returns `nil` (function call fails)
        * `error:[string "print("foo")"]:1: attempt to call global 'print' (a nil value)`
* `minetest.compress(data, method, ...)`: returns `compressed_data`
    * Compress a string of data.
    * `method` is a string identifying the compression method to be used.
    * Supported compression methods:
    *     Deflate (zlib): `"deflate"`
    * `...` indicates method-specific arguments.  Currently defined arguments are:
    *     Deflate: `level` - Compression level, `0`-`9` or `nil`.
* `minetest.decompress(compressed_data, method, ...)`: returns data
    * Decompress a string of data (using ZLib).
    * See documentation on `minetest.compress()` for supported compression methods.
    * currently supported.
    * `...` indicates method-specific arguments. Currently, no methods use this.
* `minetest.rgba(red, green, blue[, alpha])`: returns a string
    * Each argument is a 8 Bit unsigned integer
    * Returns the ColorString from rgb or rgba values
    * Example: `minetest.rgba(10, 20, 30, 40)`, returns `"#0A141E28"`
* `minetest.encode_base64(string)`: returns string encoded in base64
    * Encodes a string in base64.
* `minetest.decode_base64(string)`: returns string or nil on failure
    * Padding characters are only supported starting at version 5.4.0, where
      5.5.0 and newer perform proper checks.
    * Decodes a string encoded in base64.
* `minetest.gettext(string)` : returns string
    * look up the translation of a string in the gettext message catalog
* `fgettext_ne(string, ...)`
    * call minetest.gettext(string), replace "$1"..."$9" with the given
      extra arguments and return the result
* `fgettext(string, ...)` : returns string
    * same as fgettext_ne(), but calls minetest.formspec_escape before returning result
* `minetest.pointed_thing_to_face_pos(placer, pointed_thing)`: returns a position
    * returns the exact position on the surface of a pointed node
* `minetest.global_exists(name)`
    * Checks if a global variable has been set, without triggering a warning.

### UI
* `minetest.ui.minimap`
    * Reference to the minimap object. See [`Minimap`](#minimap) class reference for methods.
    * If client disabled minimap (using enable_minimap setting) this reference will be nil.
* `minetest.camera`
    * Reference to the camera object. See [`Camera`](#camera) class reference for methods.
* `minetest.show_formspec(formname, formspec)` : returns true on success
	* Shows a formspec to the player
* `minetest.display_chat_message(message)` returns true on success
	* Shows a chat message to the current player.

Class reference
---------------

### ModChannel

An interface to use mod channels on client and server

#### Methods
* `leave()`: leave the mod channel.
    * Client leaves channel `channel_name`.
    * No more incoming or outgoing messages can be sent to this channel from client mods.
    * This invalidate all future object usage
    * Ensure your set mod_channel to nil after that to free Lua resources
* `is_writeable()`: returns true if channel is writable and mod can send over it.
* `send_all(message)`: Send `message` though the mod channel.
    * If mod channel is not writable or invalid, message will be dropped.
    * Message size is limited to 65535 characters by protocol.

### Minimap
An interface to manipulate minimap on client UI

#### Methods
* `show()`: shows the minimap (if not disabled by server)
* `hide()`: hides the minimap
* `set_pos(pos)`: sets the minimap position on screen
* `get_pos()`: returns the minimap current position
* `set_angle(deg)`: sets the minimap angle in degrees
* `get_angle()`: returns the current minimap angle in degrees
* `set_mode(mode)`: sets the minimap mode (0 to 6)
* `get_mode()`: returns the current minimap mode
* `set_shape(shape)`: Sets the minimap shape. (0 = square, 1 = round)
* `get_shape()`: Gets the minimap shape. (0 = square, 1 = round)

### Camera
An interface to get or set information about the camera and camera-node.
Please do not try to access the reference until the camera is initialized, otherwise the reference will be nil.

#### Methods
* `set_camera_mode(mode)`
    * Pass `0` for first-person, `1` for third person, and `2` for third person front
* `get_camera_mode()`
    * Returns 0, 1, or 2 as described above
* `get_fov()`
    * Returns a table with X, Y, maximum and actual FOV in degrees:

```lua
     {
         x = number,
         y = number,
         max = number,
         actual = number
     }
```

* `get_pos()`
    * Returns position of camera with view bobbing
* `get_offset()`
    * Returns eye offset vector
* `get_look_dir()`
    * Returns eye direction unit vector
* `get_look_vertical()`
    * Returns pitch in radians
* `get_look_horizontal()`
    * Returns yaw in radians
* `get_aspect_ratio()`
    * Returns aspect ratio of screen

### LocalPlayer
An interface to retrieve information about the player.
This object will only be available after the client is initialized. Earlier accesses will yield a `nil` value.

Methods:

* `get_pos()`
    * returns current player current position
* `get_velocity()`
    * returns player speed vector
* `get_hp()`
    * returns player HP
* `get_name()`
    * returns player name
* `get_wield_index()`
    * returns the index of the wielded item
* `get_wielded_item()`
    * returns the itemstack the player is holding
* `is_attached()`
    * returns true if player is attached
* `is_touching_ground()`
    * returns true if player touching ground
* `is_in_liquid()`
    * returns true if player is in a liquid (This oscillates so that the player jumps a bit above the surface)
* `is_in_liquid_stable()`
    * returns true if player is in a stable liquid (This is more stable and defines the maximum speed of the player)
* `get_liquid_viscosity()`
    * returns liquid viscosity (Gets the viscosity of liquid to calculate friction)
* `is_climbing()`
    * returns true if player is climbing
* `swimming_vertical()`
    * returns true if player is swimming in vertical
* `get_physics_override()`
    * returns:

```lua
    {
        speed = float,
        jump = float,
        gravity = float,
        sneak = boolean,
        sneak_glitch = boolean,
        new_move = boolean,
    }
```

* `get_override_pos()`
    * returns override position
* `get_last_pos()`
    * returns last player position before the current client step
* `get_last_velocity()`
    * returns last player speed
* `get_breath()`
    * returns the player's breath
* `get_movement_acceleration()`
    * returns acceleration of the player in different environments:

```lua
    {
       fast = float,
       air = float,
       default = float,
    }
```

* `get_movement_speed()`
    * returns player's speed in different environments:

```lua
    {
       walk = float,
       jump = float,
       crouch = float,
       fast = float,
       climb = float,
    }
```

* `get_movement()`
    * returns player's movement in different environments:

```lua
    {
       liquid_fluidity = float,
       liquid_sink = float,
       liquid_fluidity_smooth = float,
       gravity = float,
    }
```

* `get_last_look_horizontal()`:
    * returns last look horizontal angle
* `get_last_look_vertical()`:
    * returns last look vertical angle
* `get_control()`:
    * returns pressed player controls

```lua
    {
       up = boolean,
       down = boolean,
       left = boolean,
       right = boolean,
       jump = boolean,
       aux1 = boolean,
       sneak = boolean,
       zoom = boolean,
       dig = boolean,
       place = boolean,
    }
```

* `get_armor_groups()`
    * returns a table with the armor group ratings
* `hud_add(definition)`
    * add a HUD element described by HUD def, returns ID number on success and `nil` on failure.
    * See [`HUD definition`](#hud-definition-hud_add-hud_get)
* `hud_get(id)`
    * returns the [`definition`](#hud-definition-hud_add-hud_get) of the HUD with that ID number or `nil`, if non-existent.
* `hud_remove(id)`
    * remove the HUD element of the specified id, returns `true` on success
* `hud_change(id, stat, value)`
    * change a value of a previously added HUD element
    * element `stat` values: `position`, `name`, `scale`, `text`, `number`, `item`, `dir`
    * Returns `true` on success, otherwise returns `nil`

### Settings
An interface to read config files in the format of `minetest.conf`.

It can be created via `Settings(filename)`.

#### Methods
* `get(key)`: returns a value
* `get_bool(key)`: returns a boolean
* `set(key, value)`
* `remove(key)`: returns a boolean (`true` for success)
* `get_names()`: returns `{key1,...}`
* `write()`: returns a boolean (`true` for success)
    * write changes to file
* `to_table()`: returns `{[key1]=value1,...}`

### NodeMetaRef
Node metadata: reference extra data and functionality stored in a node.
Can be obtained via `minetest.get_meta(pos)`.

#### Methods
* `get_string(name)`
* `get_int(name)`
* `get_float(name)`
* `to_table()`: returns `nil` or a table with keys:
    * `fields`: key-value storage
    * `inventory`: `{list1 = {}, ...}}`

### `Raycast`

A raycast on the map. It works with selection boxes.
Can be used as an iterator in a for loop as:

    local ray = Raycast(...)
    for pointed_thing in ray do
        ...
    end

The map is loaded as the ray advances. If the map is modified after the
`Raycast` is created, the changes may or may not have an effect on the object.

It can be created via `Raycast(pos1, pos2, objects, liquids)` or
`minetest.raycast(pos1, pos2, objects, liquids)` where:

* `pos1`: start of the ray
* `pos2`: end of the ray
* `objects`: if false, only nodes will be returned. Default is true.
* `liquids`: if false, liquid nodes won't be returned. Default is false.

#### Methods

* `next()`: returns a `pointed_thing` with exact pointing location
    * Returns the next thing pointed by the ray or nil.

-----------------
### Definitions
* `minetest.get_node_def(nodename)`
	* Returns [node definition](#node-definition) table of `nodename`
* `minetest.get_item_def(itemstring)`
	* Returns item definition table of `itemstring`

#### Node Definition

```lua
	{
		has_on_construct = bool,        -- Whether the node has the on_construct callback defined
		has_on_destruct = bool,         -- Whether the node has the on_destruct callback defined
		has_after_destruct = bool,      -- Whether the node has the after_destruct callback defined
		name = string,                  -- The name of the node e.g. "air", "default:dirt"
		groups = table,                 -- The groups of the node
		paramtype = string,             -- Paramtype of the node
		paramtype2 = string,            -- ParamType2 of the node
		drawtype = string,              -- Drawtype of the node
		mesh = <string>,                -- Mesh name if existant
		minimap_color = <Color>,        -- Color of node on minimap *May not exist*
		visual_scale = number,          -- Visual scale of node
		alpha = number,                 -- Alpha of the node. Only used for liquids
		color = <Color>,                -- Color of node *May not exist*
		palette_name = <string>,        -- Filename of palette *May not exist*
		palette = <{                    -- List of colors
			Color,
			Color
		}>,
		waving = number,                -- 0 of not waving, 1 if waving
		connect_sides = number,         -- Used for connected nodes
		connects_to = {                 -- List of nodes to connect to
			"node1",
			"node2"
		},
		post_effect_color = Color,      -- Color overlayed on the screen when the player is in the node
		leveled = number,               -- Max level for node
		sunlight_propogates = bool,     -- Whether light passes through the block
		light_source = number,          -- Light emitted by the block
		is_ground_content = bool,       -- Whether caves should cut through the node
		walkable = bool,                -- Whether the player collides with the node
		pointable = bool,               -- Whether the player can select the node
		diggable = bool,                -- Whether the player can dig the node
		climbable = bool,               -- Whether the player can climb up the node
		buildable_to = bool,            -- Whether the player can replace the node by placing a node on it
		rightclickable = bool,          -- Whether the player can place nodes pointing at this node
		damage_per_second = number,     -- HP of damage per second when the player is in the node
		liquid_type = <string>,         -- A string containing "none", "flowing", or "source" *May not exist*
		liquid_alternative_flowing = <string>, -- Alternative node for liquid *May not exist*
		liquid_alternative_source = <string>, -- Alternative node for liquid *May not exist*
		liquid_viscosity = <number>,    -- How fast the liquid flows *May not exist*
		liquid_renewable = <boolean>,   -- Whether the liquid makes an infinite source *May not exist*
		liquid_range = <number>,        -- How far the liquid flows *May not exist*
		drowning = bool,                -- Whether the player will drown in the node
		floodable = bool,               -- Whether nodes will be replaced by liquids (flooded)
		node_box = table,               -- Nodebox to draw the node with
		collision_box = table,          -- Nodebox to set the collision area
		selection_box = table,          -- Nodebox to set the area selected by the player
		sounds = {                      -- Table of sounds that the block makes
			sound_footstep = SimpleSoundSpec,
			sound_dig = SimpleSoundSpec,
			sound_dug = SimpleSoundSpec
		},
		legacy_facedir_simple = bool,   -- Whether to use old facedir
		legacy_wallmounted = bool       -- Whether to use old wallmounted
	}
```

#### Item Definition

```lua
	{
		name = string,                  -- Name of the item e.g. "default:stone"
		description = string,           -- Description of the item e.g. "Stone"
		type = string,                  -- Item type: "none", "node", "craftitem", "tool"
		inventory_image = string,       -- Image in the inventory
		wield_image = string,           -- Image in wieldmesh
		palette_image = string,         -- Image for palette
		color = Color,                  -- Color for item
		wield_scale = Vector,           -- Wieldmesh scale
		stack_max = number,             -- Number of items stackable together
		usable = bool,                  -- Has on_use callback defined
		liquids_pointable = bool,       -- Whether you can point at liquids with the item
		tool_capabilities = <table>,    -- If the item is a tool, tool capabilities of the item
		groups = table,                 -- Groups of the item
		sound_place = SimpleSoundSpec,  -- Sound played when placed
		sound_place_failed = SimpleSoundSpec, -- Sound played when placement failed
		node_placement_prediction = string -- Node placed in client until server catches up
	}
```
-----------------

### Chat command definition (`register_chatcommand`)

    {
        params = "<name> <privilege>", -- Short parameter description
        description = "Remove privilege from player", -- Full description
        func = function(param),        -- Called when command is run.
                                       -- Returns boolean success and text output.
    }
### Server info
```lua
{
	address = "minetest.example.org", -- The domain name/IP address of a remote server or "" for a local server.
	ip = "203.0.113.156",             -- The IP address of the server.
	port = 30000,                     -- The port the client is connected to.
	protocol_version = 30             -- Will not be accurate at start up as the client might not be connected to the server yet, in that case it will be 0.
}
```

### HUD Definition (`hud_add`, `hud_get`)
```lua
    {
        hud_elem_type = "image", -- see HUD element types, default "text"
    --  ^ type of HUD element, can be either of "image", "text", "statbar", or "inventory"
        position = {x=0.5, y=0.5},
    --  ^ Left corner position of element, default `{x=0,y=0}`.
        name = "<name>",    -- default ""
        scale = {x=2, y=2}, -- default {x=0,y=0}
        text = "<text>",    -- default ""
        number = 2,         -- default 0
        item = 3,           -- default 0
    --  ^ Selected item in inventory.  0 for no item selected.
        direction = 0,      -- default 0
    --  ^ Direction: 0: left-right, 1: right-left, 2: top-bottom, 3: bottom-top
        alignment = {x=0, y=0},   -- default {x=0, y=0}
    --  ^ See "HUD Element Types"
        offset = {x=0, y=0},      -- default {x=0, y=0}
    --  ^ See "HUD Element Types"
        size = { x=100, y=100 },  -- default {x=0, y=0}
    --  ^ Size of element in pixels
        style = 0,
    --  ^ For "text" elements sets font style: bitfield with 1 = bold, 2 = italic, 4 = monospace
    }
```

Escape sequences
----------------
Most text can contain escape sequences, that can for example color the text.
There are a few exceptions: tab headers, dropdowns and vertical labels can't.
The following functions provide escape sequences:
* `minetest.get_color_escape_sequence(color)`:
    * `color` is a [ColorString](#colorstring)
    * The escape sequence sets the text color to `color`
* `minetest.colorize(color, message)`:
    * Equivalent to:
      `minetest.get_color_escape_sequence(color) ..
       message ..
       minetest.get_color_escape_sequence("#ffffff")`
* `minetest.get_background_escape_sequence(color)`
    * `color` is a [ColorString](#colorstring)
    * The escape sequence sets the background of the whole text element to
      `color`. Only defined for item descriptions and tooltips.
* `minetest.strip_foreground_colors(str)`
    * Removes foreground colors added by `get_color_escape_sequence`.
* `minetest.strip_background_colors(str)`
    * Removes background colors added by `get_background_escape_sequence`.
* `minetest.strip_colors(str)`
    * Removes all color escape sequences.

`ColorString`
-------------
`#RGB` defines a color in hexadecimal format.

`#RGBA` defines a color in hexadecimal format and alpha channel.

`#RRGGBB` defines a color in hexadecimal format.

`#RRGGBBAA` defines a color in hexadecimal format and alpha channel.

Named colors are also supported and are equivalent to
[CSS Color Module Level 4](http://dev.w3.org/csswg/css-color/#named-colors).
To specify the value of the alpha channel, append `#A` or `#AA` to the end of
the color name (e.g. `colorname#08`).

`Color`
-------------
`{a = alpha, r = red, g = green, b = blue}` defines an ARGB8 color.

HUD element types
-----------------
The position field is used for all element types.

To account for differing resolutions, the position coordinates are the percentage
of the screen, ranging in value from `0` to `1`.

The name field is not yet used, but should contain a description of what the
HUD element represents. The direction field is the direction in which something
is drawn.

`0` draws from left to right, `1` draws from right to left, `2` draws from
top to bottom, and `3` draws from bottom to top.

The `alignment` field specifies how the item will be aligned. It ranges from `-1` to `1`,
with `0` being the center, `-1` is moved to the left/up, and `1` is to the right/down.
Fractional values can be used.

The `offset` field specifies a pixel offset from the position. Contrary to position,
the offset is not scaled to screen size. This allows for some precisely-positioned
items in the HUD.

**Note**: `offset` _will_ adapt to screen DPI as well as user defined scaling factor!

Below are the specific uses for fields in each type; fields not listed for that type are ignored.

**Note**: Future revisions to the HUD API may be incompatible; the HUD API is still
in the experimental stages.

### `image`
Displays an image on the HUD.

* `scale`: The scale of the image, with 1 being the original texture size.
  Only the X coordinate scale is used (positive values).
  Negative values represent that percentage of the screen it
  should take; e.g. `x=-100` means 100% (width).
* `text`: The name of the texture that is displayed.
* `alignment`: The alignment of the image.
* `offset`: offset in pixels from position.

### `text`
Displays text on the HUD.

* `scale`: Defines the bounding rectangle of the text.
  A value such as `{x=100, y=100}` should work.
* `text`: The text to be displayed in the HUD element.
* `number`: An integer containing the RGB value of the color used to draw the text.
  Specify `0xFFFFFF` for white text, `0xFF0000` for red, and so on.
* `alignment`: The alignment of the text.
* `offset`: offset in pixels from position.

### `statbar`
Displays a horizontal bar made up of half-images.

* `text`: The name of the texture that is used.
* `number`: The number of half-textures that are displayed.
  If odd, will end with a vertically center-split texture.
* `direction`
* `offset`: offset in pixels from position.
* `size`: If used, will force full-image size to this value (override texture pack image size)

### `inventory`
* `text`: The name of the inventory list to be displayed.
* `number`: Number of items in the inventory to be displayed.
* `item`: Position of item that is selected.
* `direction`
* `offset`: offset in pixels from position.

### `waypoint`

Displays distance to selected world position.

* `name`: The name of the waypoint.
* `text`: Distance suffix. Can be blank.
* `precision`: Waypoint precision, integer >= 0. Defaults to 10.
  If set to 0, distance is not shown. Shown value is `floor(distance*precision)/precision`.
  When the precision is an integer multiple of 10, there will be `log_10(precision)` digits after the decimal point.
  `precision = 1000`, for example, will show 3 decimal places (eg: `0.999`).
  `precision = 2` will show multiples of `0.5`; precision = 5 will show multiples of `0.2` and so on:
  `precision = n` will show multiples of `1/n`
* `number:` An integer containing the RGB value of the color used to draw the
  text.
* `world_pos`: World position of the waypoint.
* `offset`: offset in pixels from position.
* `alignment`: The alignment of the waypoint.

### `image_waypoint`

Same as `image`, but does not accept a `position`; the position is instead determined by `world_pos`, the world position of the waypoint.

* `scale`: The scale of the image, with 1 being the original texture size.
  Only the X coordinate scale is used (positive values).
  Negative values represent that percentage of the screen it
  should take; e.g. `x=-100` means 100% (width).
* `text`: The name of the texture that is displayed.
* `alignment`: The alignment of the image.
* `world_pos`: World position of the waypoint.
* `offset`: offset in pixels from position.

### Particle definition (`add_particle`)

    {
        pos = {x=0, y=0, z=0},
        velocity = {x=0, y=0, z=0},
        acceleration = {x=0, y=0, z=0},
    --  ^ Spawn particle at pos with velocity and acceleration
        expirationtime = 1,
    --  ^ Disappears after expirationtime seconds
        size = 1,
        collisiondetection = false,
    --  ^ collisiondetection: if true collides with physical objects
        collision_removal = false,
    --  ^ collision_removal: if true then particle is removed when it collides,
    --  ^ requires collisiondetection = true to have any effect
        vertical = false,
    --  ^ vertical: if true faces player using y axis only
        texture = "image.png",
    --  ^ Uses texture (string)
        animation = {Tile Animation definition},
    --  ^ optional, specifies how to animate the particle texture
        glow = 0
    --  ^ optional, specify particle self-luminescence in darkness
    }

### `ParticleSpawner` definition (`add_particlespawner`)

    {
        amount = 1,
        time = 1,
    --  ^ If time is 0 has infinite lifespan and spawns the amount on a per-second base
        minpos = {x=0, y=0, z=0},
        maxpos = {x=0, y=0, z=0},
        minvel = {x=0, y=0, z=0},
        maxvel = {x=0, y=0, z=0},
        minacc = {x=0, y=0, z=0},
        maxacc = {x=0, y=0, z=0},
        minexptime = 1,
        maxexptime = 1,
        minsize = 1,
        maxsize = 1,
    --  ^ The particle's properties are random values in between the bounds:
    --  ^ minpos/maxpos, minvel/maxvel (velocity), minacc/maxacc (acceleration),
    --  ^ minsize/maxsize, minexptime/maxexptime (expirationtime)
        collisiondetection = false,
    --  ^ collisiondetection: if true uses collision detection
        collision_removal = false,
    --  ^ collision_removal: if true then particle is removed when it collides,
    --  ^ requires collisiondetection = true to have any effect
        vertical = false,
    --  ^ vertical: if true faces player using y axis only
        texture = "image.png",
    --  ^ Uses texture (string)
    }
92 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891
/*
   Basic Unicode string class for Irrlicht.
   Copyright (c) 2009-2011 John Norman

   This software is provided 'as-is', without any express or implied
   warranty. In no event will the authors be held liable for any
   damages arising from the use of this software.

   Permission is granted to anyone to use this software for any
   purpose, including commercial applications, and to alter it and
   redistribute it freely, subject to the following restrictions:

   1. The origin of this software must not be misrepresented; you
      must not claim that you wrote the original software. If you use
      this software in a product, an acknowledgment in the product
      documentation would be appreciated but is not required.

   2. Altered source versions must be plainly marked as such, and
      must not be misrepresented as being the original software.

   3. This notice may not be removed or altered from any source
      distribution.

   The original version of this class can be located at:
   http://irrlicht.suckerfreegames.com/

   John Norman
   john@suckerfreegames.com
*/

#pragma once

#if (__cplusplus > 199711L) || (_MSC_VER >= 1600) || defined(__GXX_EXPERIMENTAL_CXX0X__)
#	define USTRING_CPP0X
#	if defined(__GXX_EXPERIMENTAL_CXX0X__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5)))
#		define USTRING_CPP0X_NEWLITERALS
#	endif
#endif

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <cstddef>

#ifdef _WIN32
#define __BYTE_ORDER 0
#define __LITTLE_ENDIAN 0
#define __BIG_ENDIAN 1
#elif defined(__MACH__) && defined(__APPLE__)
#include <machine/endian.h>
#elif defined(__FreeBSD__) || defined(__DragonFly__)
#include <sys/endian.h>
#else
#include <endian.h>
#endif

#ifdef USTRING_CPP0X
#	include <utility>
#endif

#ifndef USTRING_NO_STL
#	include <string>
#	include <iterator>
#	include <ostream>
#endif

#include "irrTypes.h"
#include "irrAllocator.h"
#include "irrArray.h"
#include "irrMath.h"
#include "irrString.h"
#include "path.h"

//! UTF-16 surrogate start values.
static const irr::u16 UTF16_HI_SURROGATE = 0xD800;
static const irr::u16 UTF16_LO_SURROGATE = 0xDC00;

//! Is a UTF-16 code point a surrogate?
#define UTF16_IS_SURROGATE(c)		(((c) & 0xF800) == 0xD800)
#define UTF16_IS_SURROGATE_HI(c)	(((c) & 0xFC00) == 0xD800)
#define UTF16_IS_SURROGATE_LO(c)	(((c) & 0xFC00) == 0xDC00)


namespace irr
{

	// Define our character types.
#ifdef USTRING_CPP0X_NEWLITERALS	// C++0x
	typedef char32_t uchar32_t;
	typedef char16_t uchar16_t;
	typedef char uchar8_t;
#else
	typedef u32 uchar32_t;
	typedef u16 uchar16_t;
	typedef u8 uchar8_t;
#endif

namespace core
{

namespace unicode
{

//! The unicode replacement character.  Used to replace invalid characters.
const irr::u16 UTF_REPLACEMENT_CHARACTER = 0xFFFD;

//! Convert a UTF-16 surrogate pair into a UTF-32 character.
//! \param high The high value of the pair.
//! \param low The low value of the pair.
//! \return The UTF-32 character expressed by the surrogate pair.
inline uchar32_t toUTF32(uchar16_t high, uchar16_t low)
{
	// Convert the surrogate pair into a single UTF-32 character.
	uchar32_t x = ((high & ((1 << 6) -1)) << 10) | (low & ((1 << 10) -1));
	uchar32_t wu = ((high >> 6) & ((1 << 5) - 1)) + 1;
	return (wu << 16) | x;
}

//! Swaps the endianness of a 16-bit value.
//! \return The new value.
inline uchar16_t swapEndian16(const uchar16_t& c)
{
	return ((c >> 8) & 0x00FF) | ((c << 8) & 0xFF00);
}

//! Swaps the endianness of a 32-bit value.
//! \return The new value.
inline uchar32_t swapEndian32(const uchar32_t& c)
{
	return  ((c >> 24) & 0x000000FF) |
			((c >> 8)  & 0x0000FF00) |
			((c << 8)  & 0x00FF0000) |
			((c << 24) & 0xFF000000);
}

//! The Unicode byte order mark.
const u16 BOM = 0xFEFF;

//! The size of the Unicode byte order mark in terms of the Unicode character size.
const u8 BOM_UTF8_LEN = 3;
const u8 BOM_UTF16_LEN = 1;
const u8 BOM_UTF32_LEN = 1;

//! Unicode byte order marks for file operations.
const u8 BOM_ENCODE_UTF8[3] = { 0xEF, 0xBB, 0xBF };
const u8 BOM_ENCODE_UTF16_BE[2] = { 0xFE, 0xFF };
const u8 BOM_ENCODE_UTF16_LE[2] = { 0xFF, 0xFE };
const u8 BOM_ENCODE_UTF32_BE[4] = { 0x00, 0x00, 0xFE, 0xFF };
const u8 BOM_ENCODE_UTF32_LE[4] = { 0xFF, 0xFE, 0x00, 0x00 };

//! The size in bytes of the Unicode byte marks for file operations.
const u8 BOM_ENCODE_UTF8_LEN = 3;
const u8 BOM_ENCODE_UTF16_LEN = 2;
const u8 BOM_ENCODE_UTF32_LEN = 4;

//! Unicode encoding type.
enum EUTF_ENCODE
{
	EUTFE_NONE		= 0,
	EUTFE_UTF8,
	EUTFE_UTF16,
	EUTFE_UTF16_LE,
	EUTFE_UTF16_BE,
	EUTFE_UTF32,
	EUTFE_UTF32_LE,
	EUTFE_UTF32_BE
};

//! Unicode endianness.
enum EUTF_ENDIAN
{
	EUTFEE_NATIVE	= 0,
	EUTFEE_LITTLE,
	EUTFEE_BIG
};

//! Returns the specified unicode byte order mark in a byte array.
//! The byte order mark is the first few bytes in a text file that signifies its encoding.
/** \param mode The Unicode encoding method that we want to get the byte order mark for.
		If EUTFE_UTF16 or EUTFE_UTF32 is passed, it uses the native system endianness. **/
//! \return An array that contains a byte order mark.
inline core::array<u8> getUnicodeBOM(EUTF_ENCODE mode)
{
#define COPY_ARRAY(source, size) \
	memcpy(ret.pointer(), source, size); \
	ret.set_used(size)

	core::array<u8> ret(4);
	switch (mode)
	{
		case EUTFE_UTF8:
			COPY_ARRAY(BOM_ENCODE_UTF8, BOM_ENCODE_UTF8_LEN);
			break;
		case EUTFE_UTF16:
			#ifdef __BIG_ENDIAN__
				COPY_ARRAY(BOM_ENCODE_UTF16_BE, BOM_ENCODE_UTF16_LEN);
			#else
				COPY_ARRAY(BOM_ENCODE_UTF16_LE, BOM_ENCODE_UTF16_LEN);
			#endif
			break;
		case EUTFE_UTF16_BE:
			COPY_ARRAY(BOM_ENCODE_UTF16_BE, BOM_ENCODE_UTF16_LEN);
			break;
		case EUTFE_UTF16_LE:
			COPY_ARRAY(BOM_ENCODE_UTF16_LE, BOM_ENCODE_UTF16_LEN);
			break;
		case EUTFE_UTF32:
			#ifdef __BIG_ENDIAN__
				COPY_ARRAY(BOM_ENCODE_UTF32_BE, BOM_ENCODE_UTF32_LEN);
			#else
				COPY_ARRAY(BOM_ENCODE_UTF32_LE, BOM_ENCODE_UTF32_LEN);
			#endif
			break;
		case EUTFE_UTF32_BE:
			COPY_ARRAY(BOM_ENCODE_UTF32_BE, BOM_ENCODE_UTF32_LEN);
			break;
		case EUTFE_UTF32_LE:
			COPY_ARRAY(BOM_ENCODE_UTF32_LE, BOM_ENCODE_UTF32_LEN);
			break;
		case EUTFE_NONE:
			// TODO sapier: fixed warning only,
			// don't know if something needs to be done here
			break;
	}
	return ret;

#undef COPY_ARRAY
}

//! Detects if the given data stream starts with a unicode BOM.
//! \param data The data stream to check.
//! \return The unicode BOM associated with the data stream, or EUTFE_NONE if none was found.
inline EUTF_ENCODE determineUnicodeBOM(const char* data)
{
	if (memcmp(data, BOM_ENCODE_UTF8, 3) == 0) return EUTFE_UTF8;
	if (memcmp(data, BOM_ENCODE_UTF16_BE, 2) == 0) return EUTFE_UTF16_BE;
	if (memcmp(data, BOM_ENCODE_UTF16_LE, 2) == 0) return EUTFE_UTF16_LE;
	if (memcmp(data, BOM_ENCODE_UTF32_BE, 4) == 0) return EUTFE_UTF32_BE;
	if (memcmp(data, BOM_ENCODE_UTF32_LE, 4) == 0) return EUTFE_UTF32_LE;
	return EUTFE_NONE;
}

} // end namespace unicode


//! UTF-16 string class.
template <typename TAlloc = irrAllocator<uchar16_t> >
class ustring16
{
public:

	///------------------///
	/// iterator classes ///
	///------------------///

	//! Access an element in a unicode string, allowing one to change it.
	class _ustring16_iterator_access
	{
		public:
			_ustring16_iterator_access(const ustring16<TAlloc>* s, u32 p) : ref(s), pos(p) {}

			//! Allow the class to be interpreted as a single UTF-32 character.
			operator uchar32_t() const
			{
				return _get();
			}

			//! Allow one to change the character in the unicode string.
			//! \param c The new character to use.
			//! \return Myself.
			_ustring16_iterator_access& operator=(const uchar32_t c)
			{
				_set(c);
				return *this;
			}

			//! Increments the value by 1.
			//! \return Myself.
			_ustring16_iterator_access& operator++()
			{
				_set(_get() + 1);
				return *this;
			}

			//! Increments the value by 1, returning the old value.
			//! \return A unicode character.
			uchar32_t operator++(int)
			{
				uchar32_t old = _get();
				_set(old + 1);
				return old;
			}

			//! Decrements the value by 1.
			//! \return Myself.
			_ustring16_iterator_access& operator--()
			{
				_set(_get() - 1);
				return *this;
			}

			//! Decrements the value by 1, returning the old value.
			//! \return A unicode character.
			uchar32_t operator--(int)
			{
				uchar32_t old = _get();
				_set(old - 1);
				return old;
			}

			//! Adds to the value by a specified amount.
			//! \param val The amount to add to this character.
			//! \return Myself.
			_ustring16_iterator_access& operator+=(int val)
			{
				_set(_get() + val);
				return *this;
			}

			//! Subtracts from the value by a specified amount.
			//! \param val The amount to subtract from this character.
			//! \return Myself.
			_ustring16_iterator_access& operator-=(int val)
			{
				_set(_get() - val);
				return *this;
			}

			//! Multiples the value by a specified amount.
			//! \param val The amount to multiply this character by.
			//! \return Myself.
			_ustring16_iterator_access& operator*=(int val)
			{
				_set(_get() * val);
				return *this;
			}

			//! Divides the value by a specified amount.
			//! \param val The amount to divide this character by.
			//! \return Myself.
			_ustring16_iterator_access& operator/=(int val)
			{
				_set(_get() / val);
				return *this;
			}

			//! Modulos the value by a specified amount.
			//! \param val The amount to modulo this character by.
			//! \return Myself.
			_ustring16_iterator_access& operator%=(int val)
			{
				_set(_get() % val);
				return *this;
			}

			//! Adds to the value by a specified amount.
			//! \param val The amount to add to this character.
			//! \return A unicode character.
			uchar32_t operator+(int val) const
			{
				return _get() + val;
			}

			//! Subtracts from the value by a specified amount.
			//! \param val The amount to subtract from this character.
			//! \return A unicode character.
			uchar32_t operator-(int val) const
			{
				return _get() - val;
			}

			//! Multiplies the value by a specified amount.
			//! \param val The amount to multiply this character by.
			//! \return A unicode character.
			uchar32_t operator*(int val) const
			{
				return _get() * val;
			}

			//! Divides the value by a specified amount.
			//! \param val The amount to divide this character by.
			//! \return A unicode character.
			uchar32_t operator/(int val) const
			{
				return _get() / val;
			}

			//! Modulos the value by a specified amount.
			//! \param val The amount to modulo this character by.
			//! \return A unicode character.
			uchar32_t operator%(int val) const
			{
				return _get() % val;
			}

		private:
			//! Gets a uchar32_t from our current position.
			uchar32_t _get() const
			{
				const uchar16_t* a = ref->c_str();
				if (!UTF16_IS_SURROGATE(a[pos]))
					return static_cast<uchar32_t>(a[pos]);
				else
				{
					if (pos + 1 >= ref->size_raw())
						return 0;

					return unicode::toUTF32(a[pos], a[pos + 1]);
				}
			}

			//! Sets a uchar32_t at our current position.
			void _set(uchar32_t c)
			{
				ustring16<TAlloc>* ref2 = const_cast<ustring16<TAlloc>*>(ref);
				const uchar16_t* a = ref2->c_str();
				if (c > 0xFFFF)
				{
					// c will be multibyte, so split it up into the high and low surrogate pairs.
					uchar16_t x = static_cast<uchar16_t>(c);
					uchar16_t vh = UTF16_HI_SURROGATE | ((((c >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10);
					uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1));

					// If the previous position was a surrogate pair, just replace them.  Else, insert the low pair.
					if (UTF16_IS_SURROGATE_HI(a[pos]) && pos + 1 != ref2->size_raw())
						ref2->replace_raw(vl, static_cast<u32>(pos) + 1);
					else ref2->insert_raw(vl, static_cast<u32>(pos) + 1);

					ref2->replace_raw(vh, static_cast<u32>(pos));
				}
				else
				{
					// c will be a single byte.
					uchar16_t vh = static_cast<uchar16_t>(c);

					// If the previous position was a surrogate pair, remove the extra byte.
					if (UTF16_IS_SURROGATE_HI(a[pos]))
						ref2->erase_raw(static_cast<u32>(pos) + 1);

					ref2->replace_raw(vh, static_cast<u32>(pos));
				}
			}

			const ustring16<TAlloc>* ref;
			u32 pos;
	};
	typedef typename ustring16<TAlloc>::_ustring16_iterator_access access;


	//! Iterator to iterate through a UTF-16 string.
#ifndef USTRING_NO_STL
	class _ustring16_const_iterator : public std::iterator<
		std::bidirectional_iterator_tag,	// iterator_category
		access,								// value_type
		ptrdiff_t,							// difference_type
		const access,						// pointer
		const access						// reference
	>
#else
	class _ustring16_const_iterator
#endif
	{
		public:
			typedef _ustring16_const_iterator _Iter;
			typedef std::iterator<std::bidirectional_iterator_tag, access, ptrdiff_t, const access, const access> _Base;
			typedef const access const_pointer;
			typedef const access const_reference;

#ifndef USTRING_NO_STL
			typedef typename _Base::value_type value_type;
			typedef typename _Base::difference_type difference_type;
			typedef typename _Base::difference_type distance_type;
			typedef typename _Base::pointer pointer;
			typedef const_reference reference;
#else
			typedef access value_type;
			typedef u32 difference_type;
			typedef u32 distance_type;
			typedef const_pointer pointer;
			typedef const_reference reference;
#endif

			//! Constructors.
			_ustring16_const_iterator(const _Iter& i) : ref(i.ref), pos(i.pos) {}
			_ustring16_const_iterator(const ustring16<TAlloc>& s) : ref(&s), pos(0) {}
			_ustring16_const_iterator(const ustring16<TAlloc>& s, const u32 p) : ref(&s), pos(0)
			{
				if (ref->size_raw() == 0 || p == 0)
					return;

				// Go to the appropriate position.
				u32 i = p;
				u32 sr = ref->size_raw();
				const uchar16_t* a = ref->c_str();
				while (i != 0 && pos < sr)
				{
					if (UTF16_IS_SURROGATE_HI(a[pos]))
						pos += 2;
					else ++pos;
					--i;
				}
			}

			//! Test for equalness.
			bool operator==(const _Iter& iter) const
			{
				if (ref == iter.ref && pos == iter.pos)
					return true;
				return false;
			}

			//! Test for unequalness.
			bool operator!=(const _Iter& iter) const
			{
				if (ref != iter.ref || pos != iter.pos)
					return true;
				return false;
			}

			//! Switch to the next full character in the string.
			_Iter& operator++()
			{	// ++iterator
				if (pos == ref->size_raw()) return *this;
				const uchar16_t* a = ref->c_str();
				if (UTF16_IS_SURROGATE_HI(a[pos]))
					pos += 2;			// TODO: check for valid low surrogate?
				else ++pos;
				if (pos > ref->size_raw()) pos = ref->size_raw();
				return *this;
			}

			//! Switch to the next full character in the string, returning the previous position.
			_Iter operator++(int)
			{	// iterator++
				_Iter _tmp(*this);
				++*this;
				return _tmp;
			}

			//! Switch to the previous full character in the string.
			_Iter& operator--()
			{	// --iterator
				if (pos == 0) return *this;
				const uchar16_t* a = ref->c_str();
				--pos;
				if (UTF16_IS_SURROGATE_LO(a[pos]) && pos != 0)	// low surrogate, go back one more.
					--pos;
				return *this;
			}

			//! Switch to the previous full character in the string, returning the previous position.
			_Iter operator--(int)
			{	// iterator--
				_Iter _tmp(*this);
				--*this;
				return _tmp;
			}

			//! Advance a specified number of full characters in the string.
			//! \return Myself.
			_Iter& operator+=(const difference_type v)
			{
				if (v == 0) return *this;
				if (v < 0) return operator-=(v * -1);

				if (pos >= ref->size_raw())
					return *this;

				// Go to the appropriate position.
				// TODO: Don't force u32 on an x64 OS.  Make it agnostic.
				u32 i = (u32)v;
				u32 sr = ref->size_raw();
				const uchar16_t* a = ref->c_str();
				while (i != 0 && pos < sr)
				{
					if (UTF16_IS_SURROGATE_HI(a[pos]))
						pos += 2;
					else ++pos;
					--i;
				}
				if (pos > sr)
					pos = sr;

				return *this;
			}

			//! Go back a specified number of full characters in the string.
			//! \return Myself.
			_Iter& operator-=(const difference_type v)
			{
				if (v == 0) return *this;
				if (v > 0) return operator+=(v * -1);

				if (pos == 0)
					return *this;

				// Go to the appropriate position.
				// TODO: Don't force u32 on an x64 OS.  Make it agnostic.
				u32 i = (u32)v;
				const uchar16_t* a = ref->c_str();
				while (i != 0 && pos != 0)
				{
					--pos;
					if (UTF16_IS_SURROGATE_LO(a[pos]) != 0 && pos != 0)
						--pos;
					--i;
				}

				return *this;
			}

			//! Return a new iterator that is a variable number of full characters forward from the current position.
			_Iter operator+(const difference_type v) const
			{
				_Iter ret(*this);
				ret += v;
				return ret;
			}

			//! Return a new iterator that is a variable number of full characters backward from the current position.
			_Iter operator-(const difference_type v) const
			{
				_Iter ret(*this);
				ret -= v;
				return ret;
			}

			//! Returns the distance between two iterators.
			difference_type operator-(const _Iter& iter) const
			{
				// Make sure we reference the same object!
				if (ref != iter.ref)
					return difference_type();

				_Iter i = iter;
				difference_type ret;

				// Walk up.
				if (pos > i.pos)
				{
					while (pos > i.pos)
					{
						++i;
						++ret;
					}
					return ret;
				}

				// Walk down.
				while (pos < i.pos)
				{
					--i;
					--ret;
				}
				return ret;
			}

			//! Accesses the full character at the iterator's position.
			const_reference operator*() const
			{
				if (pos >= ref->size_raw())
				{
					const uchar16_t* a = ref->c_str();
					u32 p = ref->size_raw();
					if (UTF16_IS_SURROGATE_LO(a[p]))
						--p;
					reference ret(ref, p);
					return ret;
				}
				const_reference ret(ref, pos);
				return ret;
			}

			//! Accesses the full character at the iterator's position.
			reference operator*()
			{
				if (pos >= ref->size_raw())
				{
					const uchar16_t* a = ref->c_str();
					u32 p = ref->size_raw();
					if (UTF16_IS_SURROGATE_LO(a[p]))
						--p;
					reference ret(ref, p);
					return ret;
				}
				reference ret(ref, pos);
				return ret;
			}

			//! Accesses the full character at the iterator's position.
			const_pointer operator->() const
			{
				return operator*();
			}

			//! Accesses the full character at the iterator's position.
			pointer operator->()
			{
				return operator*();
			}

			//! Is the iterator at the start of the string?
			bool atStart() const
			{
				return pos == 0;
			}

			//! Is the iterator at the end of the string?
			bool atEnd() const
			{
				const uchar16_t* a = ref->c_str();
				if (UTF16_IS_SURROGATE(a[pos]))
					return (pos + 1) >= ref->size_raw();
				else return pos >= ref->size_raw();
			}

			//! Moves the iterator to the start of the string.
			void toStart()
			{
				pos = 0;
			}

			//! Moves the iterator to the end of the string.
			void toEnd()
			{
				pos = ref->size_raw();
			}

			//! Returns the iterator's position.
			//! \return The iterator's position.
			u32 getPos() const
			{
				return pos;
			}

		protected:
			const ustring16<TAlloc>* ref;
			u32 pos;
	};

	//! Iterator to iterate through a UTF-16 string.
	class _ustring16_iterator : public _ustring16_const_iterator
	{
		public:
			typedef _ustring16_iterator _Iter;
			typedef _ustring16_const_iterator _Base;
			typedef typename _Base::const_pointer const_pointer;
			typedef typename _Base::const_reference const_reference;


			typedef typename _Base::value_type value_type;
			typedef typename _Base::difference_type difference_type;
			typedef typename _Base::distance_type distance_type;
			typedef access pointer;
			typedef access reference;

			using _Base::pos;
			using _Base::ref;

			//! Constructors.
			_ustring16_iterator(const _Iter& i) : _ustring16_const_iterator(i) {}
			_ustring16_iterator(const ustring16<TAlloc>& s) : _ustring16_const_iterator(s) {}
			_ustring16_iterator(const ustring16<TAlloc>& s, const u32 p) : _ustring16_const_iterator(s, p) {}

			//! Accesses the full character at the iterator's position.
			reference operator*() const
			{
				if (pos >= ref->size_raw())
				{
					const uchar16_t* a = ref->c_str();
					u32 p = ref->size_raw();
					if (UTF16_IS_SURROGATE_LO(a[p]))
						--p;
					reference ret(ref, p);
					return ret;
				}
				reference ret(ref, pos);
				return ret;
			}

			//! Accesses the full character at the iterator's position.
			reference operator*()
			{
				if (pos >= ref->size_raw())
				{
					const uchar16_t* a = ref->c_str();
					u32 p = ref->size_raw();
					if (UTF16_IS_SURROGATE_LO(a[p]))
						--p;
					reference ret(ref, p);
					return ret;
				}
				reference ret(ref, pos);
				return ret;
			}

			//! Accesses the full character at the iterator's position.
			pointer operator->() const
			{
				return operator*();
			}

			//! Accesses the full character at the iterator's position.
			pointer operator->()
			{
				return operator*();
			}
	};

	typedef typename ustring16<TAlloc>::_ustring16_iterator iterator;
	typedef typename ustring16<TAlloc>::_ustring16_const_iterator const_iterator;

	///----------------------///
	/// end iterator classes ///
	///----------------------///

	//! Default constructor
	ustring16()
	: array(0), allocated(1), used(0)
	{
#if __BYTE_ORDER == __BIG_ENDIAN
		encoding = unicode::EUTFE_UTF16_BE;
#else
		encoding = unicode::EUTFE_UTF16_LE;
#endif
		array = allocator.allocate(1); // new u16[1];
		array[0] = 0x0;
	}


	//! Constructor
	ustring16(const ustring16<TAlloc>& other)
	: array(0), allocated(0), used(0)
	{
#if __BYTE_ORDER == __BIG_ENDIAN
		encoding = unicode::EUTFE_UTF16_BE;
#else
		encoding = unicode::EUTFE_UTF16_LE;
#endif
		*this = other;
	}


	//! Constructor from other string types
	template <class B, class A>
	ustring16(const string<B, A>& other)
	: array(0), allocated(0), used(0)
	{
#if __BYTE_ORDER == __BIG_ENDIAN
		encoding = unicode::EUTFE_UTF16_BE;
#else
		encoding = unicode::EUTFE_UTF16_LE;
#endif
		*this = other;
	}


#ifndef USTRING_NO_STL
	//! Constructor from std::string
	template <class B, class A, typename Alloc>
	ustring16(const std::basic_string<B, A, Alloc>& other)
	: array(0), allocated(0), used(0)
	{
#if __BYTE_ORDER == __BIG_ENDIAN
		encoding = unicode::EUTFE_UTF16_BE;
#else
		encoding = unicode::EUTFE_UTF16_LE;
#endif
		*this = other.c_str();
	}


	//! Constructor from iterator.
	template <typename Itr>
	ustring16(Itr first, Itr last)
	: array(0), allocated(0), used(0)
	{
#if __BYTE_ORDER == __BIG_ENDIAN
		encoding = unicode::EUTFE_UTF16_BE;
#else
		encoding = unicode::EUTFE_UTF16_LE;
#endif
		reserve(std::distance(first, last));
		array[used] = 0;

		for (; first != last; ++first)
			append((uchar32_t)*first);
	}
#endif


#ifndef USTRING_CPP0X_NEWLITERALS
	//! Constructor for copying a character string from a pointer.
	ustring16(const char* const c)
	: array(0), allocated(0), used(0)
	{
#if __BYTE_ORDER == __BIG_ENDIAN
		encoding = unicode::EUTFE_UTF16_BE;
#else
		encoding = unicode::EUTFE_UTF16_LE;
#endif

		loadDataStream(c, strlen(c));
		//append((uchar8_t*)c);
	}


	//! Constructor for copying a character string from a pointer with a given length.
	ustring16(const char* const c, u32 length)
	: array(0), allocated(0), used(0)
	{
#if __BYTE_ORDER == __BIG_ENDIAN
		encoding = unicode::EUTFE_UTF16_BE;
#else
		encoding = unicode::EUTFE_UTF16_LE;
#endif

		loadDataStream(c, length);
	}
#endif


	//! Constructor for copying a UTF-8 string from a pointer.
	ustring16(const uchar8_t* const c)
	: array(0), allocated(0), used(0)
	{
#if __BYTE_ORDER == __BIG_ENDIAN
		encoding = unicode::EUTFE_UTF16_BE;
#else
		encoding = unicode::EUTFE_UTF16_LE;
#endif

		append(c);
	}


	//! Constructor for copying a UTF-8 string from a single char.
	ustring16(const char c)
	: array(0), allocated(0), used(0)
	{
#if __BYTE_ORDER == __BIG_ENDIAN
		encoding = unicode::EUTFE_UTF16_BE;
#else
		encoding = unicode::EUTFE_UTF16_LE;
#endif

		append((uchar32_t)c);
	}


	//! Constructor for copying a UTF-8 string from a pointer with a given length.
	ustring16(const uchar8_t* const c, u32 length)
	: array(0), allocated(0), used(0)
	{
#if __BYTE_ORDER == __BIG_ENDIAN
		encoding = unicode::EUTFE_UTF16_BE;
#else
		encoding = unicode::EUTFE_UTF16_LE;
#endif

		append(c, length);
	}


	//! Constructor for copying a UTF-16 string from a pointer.
	ustring16(const uchar16_t* const c)
	: array(0), allocated(0), used(0)
	{
#if __BYTE_ORDER == __BIG_ENDIAN
		encoding = unicode::EUTFE_UTF16_BE;
#else
		encoding = unicode::EUTFE_UTF16_LE;
#endif

		append(c);
	}


	//! Constructor for copying a UTF-16 string from a pointer with a given length
	ustring16(const uchar16_t* const c, u32 length)
	: array(0), allocated(0), used(0)
	{
#if __BYTE_ORDER == __BIG_ENDIAN
		encoding = unicode::EUTFE_UTF16_BE;
#else
		encoding = unicode::EUTFE_UTF16_LE;
#endif

		append(c, length);
	}


	//! Constructor for copying a UTF-32 string from a pointer.
	ustring16(const uchar32_t* const c)
	: array(0), allocated(0), used(0)
	{
#if __BYTE_ORDER == __BIG_ENDIAN
		encoding = unicode::EUTFE_UTF16_BE;
#else
		encoding = unicode::EUTFE_UTF16_LE;
#endif

		append(c);
	}


	//! Constructor for copying a UTF-32 from a pointer with a given length.
	ustring16(const uchar32_t* const c, u32 length)
	: array(0), allocated(0), used(0)
	{
#if __BYTE_ORDER == __BIG_ENDIAN
		encoding = unicode::EUTFE_UTF16_BE;
#else
		encoding = unicode::EUTFE_UTF16_LE;
#endif

		append(c, length);
	}


	//! Constructor for copying a wchar_t string from a pointer.
	ustring16(const wchar_t* const c)
	: array(0), allocated(0), used(0)
	{
#if __BYTE_ORDER == __BIG_ENDIAN
		encoding = unicode::EUTFE_UTF16_BE;
#else
		encoding = unicode::EUTFE_UTF16_LE;
#endif

		if (sizeof(wchar_t) == 4)
			append(reinterpret_cast<const uchar32_t* const>(c));
		else if (sizeof(wchar_t) == 2)
			append(reinterpret_cast<const uchar16_t* const>(c));
		else if (sizeof(wchar_t) == 1)
			append(reinterpret_cast<const uchar8_t* const>(c));
	}


	//! Constructor for copying a wchar_t string from a pointer with a given length.
	ustring16(const wchar_t* const c, u32 length)
	: array(0), allocated(0), used(0)
	{
#if __BYTE_ORDER == __BIG_ENDIAN
		encoding = unicode::EUTFE_UTF16_BE;
#else
		encoding = unicode::EUTFE_UTF16_LE;
#endif

		if (sizeof(wchar_t) == 4)
			append(reinterpret_cast<const uchar32_t* const>(c), length);
		else if (sizeof(wchar_t) == 2)
			append(reinterpret_cast<const uchar16_t* const>(c), length);
		else if (sizeof(wchar_t) == 1)
			append(reinterpret_cast<const uchar8_t* const>(c), length);
	}


#ifdef USTRING_CPP0X
	//! Constructor for moving a ustring16
	ustring16(ustring16<TAlloc>&& other)
	: array(other.array), encoding(other.encoding), allocated(other.allocated), used(other.used)
	{
		//std::cout << "MOVE constructor" << std::endl;
		other.array = 0;
		other.allocated = 0;
		other.used = 0;
	}
#endif


	//! Destructor
	~ustring16()
	{
		allocator.deallocate(array); // delete [] array;
	}


	//! Assignment operator
	ustring16& operator=(const ustring16<TAlloc>& other)
	{
		if (this == &other)
			return *this;

		used = other.size_raw();
		if (used >= allocated)
		{
			allocator.deallocate(array); // delete [] array;
			allocated = used + 1;
			array = allocator.allocate(used + 1); //new u16[used];
		}

		const uchar16_t* p = other.c_str();
		for (u32 i=0; i<=used; ++i, ++p)
			array[i] = *p;

		array[used] = 0;

		// Validate our new UTF-16 string.
		validate();

		return *this;
	}


#ifdef USTRING_CPP0X
	//! Move assignment operator
	ustring16& operator=(ustring16<TAlloc>&& other)
	{
		if (this != &other)
		{
			//std::cout << "MOVE operator=" << std::endl;
			allocator.deallocate(array);

			array = other.array;
			allocated = other.allocated;
			encoding = other.encoding;
			used = other.used;
			other.array = 0;
			other.used = 0;
		}
		return *this;
	}
#endif


	//! Assignment operator for other string types
	template <class B, class A>
	ustring16<TAlloc>& operator=(const string<B, A>& other)
	{
		*this = other.c_str();
		return *this;
	}


	//! Assignment operator for UTF-8 strings
	ustring16<TAlloc>& operator=(const uchar8_t* const c)
	{
		if (!array)
		{
			array = allocator.allocate(1); //new u16[1];
			allocated = 1;
		}
		used = 0;
		array[used] = 0x0;
		if (!c) return *this;

		//! Append our string now.
		append(c);
		return *this;
	}


	//! Assignment operator for UTF-16 strings
	ustring16<TAlloc>& operator=(const uchar16_t* const c)
	{
		if (!array)
		{
			array = allocator.allocate(1); //new u16[1];
			allocated = 1;
		}
		used = 0;
		array[used] = 0x0;
		if (!c) return *this;

		//! Append our string now.
		append(c);
		return *this;
	}


	//! Assignment operator for UTF-32 strings
	ustring16<TAlloc>& operator=(const uchar32_t* const c)
	{
		if (!array)
		{
			array = allocator.allocate(1); //new u16[1];
			allocated = 1;
		}
		used = 0;
		array[used] = 0x0;
		if (!c) return *this;

		//! Append our string now.
		append(c);
		return *this;
	}


	//! Assignment operator for wchar_t strings.
	/** Note that this assumes that a correct unicode string is stored in the wchar_t string.
		Since wchar_t changes depending on its platform, it could either be a UTF-8, -16, or -32 string.
		This function assumes you are storing the correct unicode encoding inside the wchar_t string. **/
	ustring16<TAlloc>& operator=(const wchar_t* const c)
	{
		if (sizeof(wchar_t) == 4)
			*this = reinterpret_cast<const uchar32_t* const>(c);
		else if (sizeof(wchar_t) == 2)
			*this = reinterpret_cast<const uchar16_t* const>(c);
		else if (sizeof(wchar_t) == 1)
			*this = reinterpret_cast<const uchar8_t* const>(c);

		return *this;
	}


	//! Assignment operator for other strings.
	/** Note that this assumes that a correct unicode string is stored in the string. **/
	template <class B>
	ustring16<TAlloc>& operator=(const B* const c)
	{
		if (sizeof(B) == 4)
			*this = reinterpret_cast<const uchar32_t* const>(c);
		else if (sizeof(B) == 2)
			*this = reinterpret_cast<const uchar16_t* const>(c);
		else if (sizeof(B) == 1)
			*this = reinterpret_cast<const uchar8_t* const>(c);

		return *this;
	}


	//! Direct access operator
	access operator [](const u32 index)
	{
		_IRR_DEBUG_BREAK_IF(index>=size()) // bad index
		iterator iter(*this, index);
		return iter.operator*();
	}


	//! Direct access operator
	const access operator [](const u32 index) const
	{
		_IRR_DEBUG_BREAK_IF(index>=size()) // bad index
		const_iterator iter(*this, index);
		return iter.operator*();
	}


	//! Equality operator
	bool operator ==(const uchar16_t* const str) const
	{
		if (!str)
			return false;

		u32 i;
		for(i=0; array[i] && str[i]; ++i)
			if (array[i] != str[i])
				return false;

		return !array[i] && !str[i];
	}


	//! Equality operator
	bool operator ==(const ustring16<TAlloc>& other) const
	{
		for(u32 i=0; array[i] && other.array[i]; ++i)
			if (array[i] != other.array[i])
				return false;

		return used == other.used;
	}


	//! Is smaller comparator
	bool operator <(const ustring16<TAlloc>& other) const
	{
		for(u32 i=0; array[i] && other.array[i]; ++i)
		{
			s32 diff = array[i] - other.array[i];
			if ( diff )
				return diff < 0;
		}

		return used < other.used;
	}


	//! Inequality operator
	bool operator !=(const uchar16_t* const str) const
	{
		return !(*this == str);
	}


	//! Inequality operator
	bool operator !=(const ustring16<TAlloc>& other) const
	{
		return !(*this == other);
	}


	//! Returns the length of a ustring16 in full characters.
	//! \return Length of a ustring16 in full characters.
	u32 size() const
	{
		const_iterator i(*this, 0);
		u32 pos = 0;
		while (!i.atEnd())
		{
			++i;
			++pos;
		}
		return pos;
	}


	//! Informs if the ustring is empty or not.
	//! \return True if the ustring is empty, false if not.
	bool empty() const
	{
		return (size_raw() == 0);
	}


	//! Returns a pointer to the raw UTF-16 string data.
	//! \return pointer to C-style NUL terminated array of UTF-16 code points.
	const uchar16_t* c_str() const
	{
		return array;
	}


	//! Compares the first n characters of this string with another.
	//! \param other Other string to compare to.
	//! \param n Number of characters to compare.
	//! \return True if the n first characters of both strings are equal.
	bool equalsn(const ustring16<TAlloc>& other, u32 n) const
	{
		u32 i;
		const uchar16_t* oa = other.c_str();
		for(i=0; array[i] && oa[i] && i < n; ++i)
			if (array[i] != oa[i])
				return false;

		// if one (or both) of the strings was smaller then they
		// are only equal if they have the same length
		return (i == n) || (used == other.used);
	}


	//! Compares the first n characters of this string with another.
	//! \param str Other string to compare to.
	//! \param n Number of characters to compare.
	//! \return True if the n first characters of both strings are equal.
	bool equalsn(const uchar16_t* const str, u32 n) const
	{
		if (!str)
			return false;
		u32 i;
		for(i=0; array[i] && str[i] && i < n; ++i)
			if (array[i] != str[i])
				return false;

		// if one (or both) of the strings was smaller then they
		// are only equal if they have the same length
		return (i == n) || (array[i] == 0 && str[i] == 0);
	}


	//! Appends a character to this ustring16
	//! \param character The character to append.
	//! \return A reference to our current string.
	ustring16<TAlloc>& append(uchar32_t character)
	{
		if (used + 2 >= allocated)
			reallocate(used + 2);

		if (character > 0xFFFF)
		{
			used += 2;

			// character will be multibyte, so split it up into a surrogate pair.
			uchar16_t x = static_cast<uchar16_t>(character);
			uchar16_t vh = UTF16_HI_SURROGATE | ((((character >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10);
			uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1));
			array[used-2] = vh;
			array[used-1] = vl;
		}
		else
		{
			++used;
			array[used-1] = character;
		}
		array[used] = 0;

		return *this;
	}


	//! Appends a UTF-8 string to this ustring16
	//! \param other The UTF-8 string to append.
	//! \param length The length of the string to append.
	//! \return A reference to our current string.
	ustring16<TAlloc>& append(const uchar8_t* const other, u32 length=0xffffffff)
	{
		if (!other)
			return *this;

		// Determine if the string is long enough for a BOM.
		u32 len = 0;
		const uchar8_t* p = other;
		do
		{
			++len;
		} while (*p++ && len < unicode::BOM_ENCODE_UTF8_LEN);

		// Check for BOM.
		unicode::EUTF_ENCODE c_bom = unicode::EUTFE_NONE;
		if (len == unicode::BOM_ENCODE_UTF8_LEN)
		{
			if (memcmp(other, unicode::BOM_ENCODE_UTF8, unicode::BOM_ENCODE_UTF8_LEN) == 0)
				c_bom = unicode::EUTFE_UTF8;
		}

		// If a BOM was found, don't include it in the string.
		const uchar8_t* c2 = other;
		if (c_bom != unicode::EUTFE_NONE)
		{
			c2 = other + unicode::BOM_UTF8_LEN;
			length -= unicode::BOM_UTF8_LEN;
		}

		// Calculate the size of the string to read in.
		len = 0;
		p = c2;
		do
		{
			++len;
		} while(*p++ && len < length);
		if (len > length)
			len = length;

		// If we need to grow the array, do it now.
		if (used + len >= allocated)
			reallocate(used + (len * 2));
		u32 start = used;

		// Convert UTF-8 to UTF-16.
		u32 pos = start;
		for (u32 l = 0; l<len;)
		{
			++used;
			if (((c2[l] >> 6) & 0x03) == 0x02)
			{	// Invalid continuation byte.
				array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER;
				++l;
			}
			else if (c2[l] == 0xC0 || c2[l] == 0xC1)
			{	// Invalid byte - overlong encoding.
				array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER;
				++l;
			}
			else if ((c2[l] & 0xF8) == 0xF0)
			{	// 4 bytes UTF-8, 2 bytes UTF-16.
				// Check for a full string.
				if ((l + 3) >= len)
				{
					array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER;
					l += 3;
					break;
				}

				// Validate.
				bool valid = true;
				u8 l2 = 0;
				if (valid && (((c2[l+1] >> 6) & 0x03) == 0x02)) ++l2; else valid = false;
				if (valid && (((c2[l+2] >> 6) & 0x03) == 0x02)) ++l2; else valid = false;
				if (valid && (((c2[l+3] >> 6) & 0x03) == 0x02)) ++l2; else valid = false;
				if (!valid)
				{
					array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER;
					l += l2;
					continue;
				}

				// Decode.
				uchar8_t b1 = ((c2[l] & 0x7) << 2) | ((c2[l+1] >> 4) & 0x3);
				uchar8_t b2 = ((c2[l+1] & 0xF) << 4) | ((c2[l+2] >> 2) & 0xF);
				uchar8_t b3 = ((c2[l+2] & 0x3) << 6) | (c2[l+3] & 0x3F);
				uchar32_t v = b3 | ((uchar32_t)b2 << 8) | ((uchar32_t)b1 << 16);

				// Split v up into a surrogate pair.
				uchar16_t x = static_cast<uchar16_t>(v);
				uchar16_t vh = UTF16_HI_SURROGATE | ((((v >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10);
				uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1));

				array[pos++] = vh;
				array[pos++] = vl;
				l += 4;
				++used;		// Using two shorts this time, so increase used by 1.
			}
			else if ((c2[l] & 0xF0) == 0xE0)
			{	// 3 bytes UTF-8, 1 byte UTF-16.
				// Check for a full string.
				if ((l + 2) >= len)
				{
					array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER;
					l += 2;
					break;
				}

				// Validate.
				bool valid = true;
				u8 l2 = 0;
				if (valid && (((c2[l+1] >> 6) & 0x03) == 0x02)) ++l2; else valid = false;
				if (valid && (((c2[l+2] >> 6) & 0x03) == 0x02)) ++l2; else valid = false;
				if (!valid)
				{
					array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER;
					l += l2;
					continue;
				}

				// Decode.
				uchar8_t b1 = ((c2[l] & 0xF) << 4) | ((c2[l+1] >> 2) & 0xF);
				uchar8_t b2 = ((c2[l+1] & 0x3) << 6) | (c2[l+2] & 0x3F);
				uchar16_t ch = b2 | ((uchar16_t)b1 << 8);
				array[pos++] = ch;
				l += 3;
			}
			else if ((c2[l] & 0xE0) == 0xC0)
			{	// 2 bytes UTF-8, 1 byte UTF-16.
				// Check for a full string.
				if ((l + 1) >= len)
				{
					array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER;
					l += 1;
					break;
				}

				// Validate.
				if (((c2[l+1] >> 6) & 0x03) != 0x02)
				{
					array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER;
					++l;
					continue;
				}

				// Decode.
				uchar8_t b1 = (c2[l] >> 2) & 0x7;
				uchar8_t b2 = ((c2[l] & 0x3) << 6) | (c2[l+1] & 0x3F);
				uchar16_t ch = b2 | ((uchar16_t)b1 << 8);
				array[pos++] = ch;
				l += 2;
			}
			else
			{	// 1 byte UTF-8, 1 byte UTF-16.
				// Validate.
				if (c2[l] > 0x7F)
				{	// Values above 0xF4 are restricted and aren't used.  By now, anything above 0x7F is invalid.
					array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER;
				}
				else array[pos++] = static_cast<uchar16_t>(c2[l]);
				++l;
			}
		}
		array[used] = 0;

		// Validate our new UTF-16 string.
		validate();

		return *this;
	}


	//! Appends a UTF-16 string to this ustring16
	//! \param other The UTF-16 string to append.
	//! \param length The length of the string to append.
	//! \return A reference to our current string.
	ustring16<TAlloc>& append(const uchar16_t* const other, u32 length=0xffffffff)
	{
		if (!other)
			return *this;

		// Determine if the string is long enough for a BOM.
		u32 len = 0;
		const uchar16_t* p = other;
		do
		{
			++len;
		} while (*p++ && len < unicode::BOM_ENCODE_UTF16_LEN);

		// Check for the BOM to determine the string's endianness.
		unicode::EUTF_ENDIAN c_end = unicode::EUTFEE_NATIVE;
		if (memcmp(other, unicode::BOM_ENCODE_UTF16_LE, unicode::BOM_ENCODE_UTF16_LEN) == 0)
			c_end = unicode::EUTFEE_LITTLE;
		else if (memcmp(other, unicode::BOM_ENCODE_UTF16_BE, unicode::BOM_ENCODE_UTF16_LEN) == 0)
			c_end = unicode::EUTFEE_BIG;

		// If a BOM was found, don't include it in the string.
		const uchar16_t* c2 = other;
		if (c_end != unicode::EUTFEE_NATIVE)
		{
			c2 = other + unicode::BOM_UTF16_LEN;
			length -= unicode::BOM_UTF16_LEN;
		}

		// Calculate the size of the string to read in.
		len = 0;
		p = c2;
		do
		{
			++len;
		} while(*p++ && len < length);
		if (len > length)
			len = length;

		// If we need to grow the size of the array, do it now.
		if (used + len >= allocated)
			reallocate(used + (len * 2));
		u32 start = used;
		used += len;

		// Copy the string now.
		unicode::EUTF_ENDIAN m_end = getEndianness();
		for (u32 l = start; l < start + len; ++l)
		{
			array[l] = (uchar16_t)c2[l];
			if (c_end != unicode::EUTFEE_NATIVE && c_end != m_end)
				array[l] = unicode::swapEndian16(array[l]);
		}

		array[used] = 0;

		// Validate our new UTF-16 string.
		validate();
		return *this;
	}


	//! Appends a UTF-32 string to this ustring16
	//! \param other The UTF-32 string to append.
	//! \param length The length of the string to append.
	//! \return A reference to our current string.
	ustring16<TAlloc>& append(const uchar32_t* const other, u32 length=0xffffffff)
	{
		if (!other)
			return *this;

		// Check for the BOM to determine the string's endianness.
		unicode::EUTF_ENDIAN c_end = unicode::EUTFEE_NATIVE;
		if (memcmp(other, unicode::BOM_ENCODE_UTF32_LE, unicode::BOM_ENCODE_UTF32_LEN) == 0)
			c_end = unicode::EUTFEE_LITTLE;
		else if (memcmp(other, unicode::BOM_ENCODE_UTF32_BE, unicode::BOM_ENCODE_UTF32_LEN) == 0)
			c_end = unicode::EUTFEE_BIG;

		// If a BOM was found, don't include it in the string.
		const uchar32_t* c2 = other;
		if (c_end != unicode::EUTFEE_NATIVE)
		{
			c2 = other + unicode::BOM_UTF32_LEN;
			length -= unicode::BOM_UTF32_LEN;
		}

		// Calculate the size of the string to read in.
		u32 len = 0;
		const uchar32_t* p = c2;
		do
		{
			++len;
		} while(*p++ && len < length);
		if (len > length)
			len = length;

		// If we need to grow the size of the array, do it now.
		// In case all of the UTF-32 string is split into surrogate pairs, do len * 2.
		if (used + (len * 2) >= allocated)
			reallocate(used + ((len * 2) * 2));
		u32 start = used;

		// Convert UTF-32 to UTF-16.
		unicode::EUTF_ENDIAN m_end = getEndianness();
		u32 pos = start;
		for (u32 l = 0; l<len; ++l)
		{
			++used;

			uchar32_t ch = c2[l];
			if (c_end != unicode::EUTFEE_NATIVE && c_end != m_end)
				ch = unicode::swapEndian32(ch);

			if (ch > 0xFFFF)
			{
				// Split ch up into a surrogate pair as it is over 16 bits long.
				uchar16_t x = static_cast<uchar16_t>(ch);
				uchar16_t vh = UTF16_HI_SURROGATE | ((((ch >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10);
				uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1));
				array[pos++] = vh;
				array[pos++] = vl;
				++used;		// Using two shorts, so increased used again.
			}
			else if (ch >= 0xD800 && ch <= 0xDFFF)
			{
				// Between possible UTF-16 surrogates (invalid!)
				array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER;
			}
			else array[pos++] = static_cast<uchar16_t>(ch);
		}
		array[used] = 0;

		// Validate our new UTF-16 string.
		validate();

		return *this;
	}


	//! Appends a ustring16 to this ustring16
	//! \param other The string to append to this one.
	//! \return A reference to our current string.
	ustring16<TAlloc>& append(const ustring16<TAlloc>& other)
	{
		const uchar16_t* oa = other.c_str();

		u32 len = other.size_raw();

		if (used + len >= allocated)
			reallocate(used + len);

		for (u32 l=0; l<len; ++l)
			array[used+l] = oa[l];

		used += len;
		array[used] = 0;

		return *this;
	}


	//! Appends a certain amount of characters of a ustring16 to this ustring16.
	//! \param other The string to append to this one.
	//! \param length How many characters of the other string to add to this one.
	//! \return A reference to our current string.
	ustring16<TAlloc>& append(const ustring16<TAlloc>& other, u32 length)
	{
		if (other.size() == 0)
			return *this;

		if (other.size() < length)
		{
			append(other);
			return *this;
		}

		if (used + length * 2 >= allocated)
			reallocate(used + length * 2);

		const_iterator iter(other, 0);
		u32 l = length;
		while (!iter.atEnd() && l)
		{
			uchar32_t c = *iter;
			append(c);
			++iter;
			--l;
		}

		return *this;
	}


	//! Reserves some memory.
	//! \param count The amount of characters to reserve.
	void reserve(u32 count)
	{
		if (count < allocated)
			return;

		reallocate(count);
	}


	//! Finds first occurrence of character.
	//! \param c The character to search for.
	//! \return Position where the character has been found, or -1 if not found.
	s32 findFirst(uchar32_t c) const
	{
		const_iterator i(*this, 0);

		s32 pos = 0;
		while (!i.atEnd())
		{
			uchar32_t t = *i;
			if (c == t)
				return pos;
			++pos;
			++i;
		}

		return -1;
	}

	//! Finds first occurrence of a character of a list.
	//! \param c A list of characters to find. For example if the method should find the first occurrence of 'a' or 'b', this parameter should be "ab".
	//! \param count The amount of characters in the list. Usually, this should be strlen(c).
	//! \return Position where one of the characters has been found, or -1 if not found.
	s32 findFirstChar(const uchar32_t* const c, u32 count=1) const
	{
		if (!c || !count)
			return -1;

		const_iterator i(*this, 0);

		s32 pos = 0;
		while (!i.atEnd())
		{
			uchar32_t t = *i;
			for (u32 j=0; j<count; ++j)
				if (t == c[j])
					return pos;
			++pos;
			++i;
		}

		return -1;
	}


	//! Finds first position of a character not in a given list.
	//! \param c A list of characters to NOT find. For example if the method should find the first occurrence of a character not 'a' or 'b', this parameter should be "ab".
	//! \param count The amount of characters in the list. Usually, this should be strlen(c).
	//! \return Position where the character has been found, or -1 if not found.
	s32 findFirstCharNotInList(const uchar32_t* const c, u32 count=1) const
	{
		if (!c || !count)
			return -1;

		const_iterator i(*this, 0);

		s32 pos = 0;
		while (!i.atEnd())
		{
			uchar32_t t = *i;
			u32 j;
			for (j=0; j<count; ++j)
				if (t == c[j])
					break;

			if (j==count)
				return pos;
			++pos;
			++i;
		}

		return -1;
	}

	//! Finds last position of a character not in a given list.
	//! \param c A list of characters to NOT find. For example if the method should find the first occurrence of a character not 'a' or 'b', this parameter should be "ab".
	//! \param count The amount of characters in the list. Usually, this should be strlen(c).
	//! \return Position where the character has been found, or -1 if not found.
	s32 findLastCharNotInList(const uchar32_t* const c, u32 count=1) const
	{
		if (!c || !count)
			return -1;

		const_iterator i(end());
		--i;

		s32 pos = size() - 1;
		while (!i.atStart())
		{
			uchar32_t t = *i;
			u32 j;
			for (j=0; j<count; ++j)
				if (t == c[j])
					break;

			if (j==count)
				return pos;
			--pos;
			--i;
		}

		return -1;
	}

	//! Finds next occurrence of character.
	//! \param c The character to search for.
	//! \param startPos The position in the string to start searching.
	//! \return Position where the character has been found, or -1 if not found.
	s32 findNext(uchar32_t c, u32 startPos) const
	{
		const_iterator i(*this, startPos);

		s32 pos = startPos;
		while (!i.atEnd())
		{
			uchar32_t t = *i;
			if (t == c)
				return pos;
			++pos;
			++i;
		}

		return -1;
	}


	//! Finds last occurrence of character.
	//! \param c The character to search for.
	//! \param start The start position of the reverse search ( default = -1, on end ).
	//! \return Position where the character has been found, or -1 if not found.
	s32 findLast(uchar32_t c, s32 start = -1) const
	{
		u32 s = size();
		start = core::clamp ( start < 0 ? (s32)s : start, 0, (s32)s ) - 1;

		const_iterator i(*this, start);
		u32 pos = start;
		while (!i.atStart())
		{
			uchar32_t t = *i;
			if (t == c)
				return pos;
			--pos;
			--i;
		}

		return -1;
	}

	//! Finds last occurrence of a character in a list.
	//! \param c A list of strings to find. For example if the method should find the last occurrence of 'a' or 'b', this parameter should be "ab".
	//! \param count The amount of characters in the list. Usually, this should be strlen(c).
	//! \return Position where one of the characters has been found, or -1 if not found.
	s32 findLastChar(const uchar32_t* const c, u32 count=1) const
	{
		if (!c || !count)
			return -1;

		const_iterator i(end());
		--i;

		s32 pos = size();
		while (!i.atStart())
		{
			uchar32_t t = *i;
			for (u32 j=0; j<count; ++j)
				if (t == c[j])
					return pos;
			--pos;
			--i;
		}

		return -1;
	}


	//! Finds another ustring16 in this ustring16.
	//! \param str The string to find.
	//! \param start The start position of the search.
	//! \return Positions where the ustring16 has been found, or -1 if not found.
	s32 find(const ustring16<TAlloc>& str, const u32 start = 0) const
	{
		u32 my_size = size();
		u32 their_size = str.size();

		if (their_size == 0 || my_size - start < their_size)
			return -1;

		const_iterator i(*this, start);

		s32 pos = start;
		while (!i.atEnd())
		{
			const_iterator i2(i);
			const_iterator j(str, 0);
			uchar32_t t1 = (uchar32_t)*i2;
			uchar32_t t2 = (uchar32_t)*j;
			while (t1 == t2)
			{
				++i2;
				++j;
				if (j.atEnd())
					return pos;
				t1 = (uchar32_t)*i2;
				t2 = (uchar32_t)*j;
			}
			++i;
			++pos;
		}

		return -1;
	}


	//! Finds another ustring16 in this ustring16.
	//! \param str The string to find.
	//! \param start The start position of the search.
	//! \return Positions where the string has been found, or -1 if not found.
	s32 find_raw(const ustring16<TAlloc>& str, const u32 start = 0) const
	{
		const uchar16_t* data = str.c_str();
		if (data && *data)
		{
			u32 len = 0;

			while (data[len])
				++len;

			if (len > used)
				return -1;

			for (u32 i=start; i<=used-len; ++i)
			{
				u32 j=0;

				while(data[j] && array[i+j] == data[j])
					++j;

				if (!data[j])
					return i;
			}
		}

		return -1;
	}


	//! Returns a substring.
	//! \param begin: Start of substring.
	//! \param length: Length of substring.
	//! \return A reference to our current string.
	ustring16<TAlloc> subString(u32 begin, s32 length) const
	{
		u32 len = size();
		// if start after ustring16
		// or no proper substring length
		if ((length <= 0) || (begin>=len))
			return ustring16<TAlloc>("");
		// clamp length to maximal value
		if ((length+begin) > len)
			length = len-begin;

		ustring16<TAlloc> o;
		o.reserve((length+1) * 2);

		const_iterator i(*this, begin);
		while (!i.atEnd() && length)
		{
			o.append(*i);
			++i;
			--length;
		}

		return o;
	}


	//! Appends a character to this ustring16.
	//! \param c Character to append.
	//! \return A reference to our current string.
	ustring16<TAlloc>& operator += (char c)
	{
		append((uchar32_t)c);
		return *this;
	}


	//! Appends a character to this ustring16.
	//! \param c Character to append.
	//! \return A reference to our current string.
	ustring16<TAlloc>& operator += (uchar32_t c)
	{
		append(c);
		return *this;
	}


	//! Appends a number to this ustring16.
	//! \param c Number to append.
	//! \return A reference to our current string.
	ustring16<TAlloc>& operator += (short c)
	{
		append(core::stringc(c));
		return *this;
	}


	//! Appends a number to this ustring16.
	//! \param c Number to append.
	//! \return A reference to our current string.
	ustring16<TAlloc>& operator += (unsigned short c)
	{
		append(core::stringc(c));
		return *this;
	}


#ifdef USTRING_CPP0X_NEWLITERALS
	//! Appends a number to this ustring16.
	//! \param c Number to append.
	//! \return A reference to our current string.
	ustring16<TAlloc>& operator += (int c)
	{
		append(core::stringc(c));
		return *this;
	}


	//! Appends a number to this ustring16.
	//! \param c Number to append.
	//! \return A reference to our current string.
	ustring16<TAlloc>& operator += (unsigned int c)
	{
		append(core::stringc(c));
		return *this;
	}
#endif


	//! Appends a number to this ustring16.
	//! \param c Number to append.
	//! \return A reference to our current string.
	ustring16<TAlloc>& operator += (long c)
	{
		append(core::stringc(c));
		return *this;
	}


	//! Appends a number to this ustring16.
	//! \param c Number to append.
	//! \return A reference to our current string.
	ustring16<TAlloc>& operator += (unsigned long c)
	{
		append(core::stringc(c));
		return *this;
	}


	//! Appends a number to this ustring16.
	//! \param c Number to append.
	//! \return A reference to our current string.
	ustring16<TAlloc>& operator += (double c)
	{
		append(core::stringc(c));
		return *this;
	}


	//! Appends a char ustring16 to this ustring16.
	//! \param c Char ustring16 to append.
	//! \return A reference to our current string.
	ustring16<TAlloc>& operator += (const uchar16_t* const c)
	{
		append(c);
		return *this;
	}


	//! Appends a ustring16 to this ustring16.
	//! \param other ustring16 to append.
	//! \return A reference to our current string.
	ustring16<TAlloc>& operator += (const ustring16<TAlloc>& other)
	{
		append(other);
		return *this;
	}


	//! Replaces all characters of a given type with another one.
	//! \param toReplace Character to replace.
	//! \param replaceWith Character replacing the old one.
	//! \return A reference to our current string.
	ustring16<TAlloc>& replace(uchar32_t toReplace, uchar32_t replaceWith)
	{
		iterator i(*this, 0);
		while (!i.atEnd())
		{
			typename ustring16<TAlloc>::access a = *i;
			if ((uchar32_t)a == toReplace)
				a = replaceWith;
			++i;
		}
		return *this;
	}


	//! Replaces all instances of a string with another one.
	//! \param toReplace The string to replace.
	//! \param replaceWith The string replacing the old one.
	//! \return A reference to our current string.
	ustring16<TAlloc>& replace(const ustring16<TAlloc>& toReplace, const ustring16<TAlloc>& replaceWith)
	{
		if (toReplace.size() == 0)
			return *this;

		const uchar16_t* other = toReplace.c_str();
		const uchar16_t* replace = replaceWith.c_str();
		const u32 other_size = toReplace.size_raw();
		const u32 replace_size = replaceWith.size_raw();

		// Determine the delta.  The algorithm will change depending on the delta.
		s32 delta = replace_size - other_size;

		// A character for character replace.  The string will not shrink or grow.
		if (delta == 0)
		{
			s32 pos = 0;
			while ((pos = find_raw(other, pos)) != -1)
			{
				for (u32 i = 0; i < replace_size; ++i)
					array[pos + i] = replace[i];
				++pos;
			}
			return *this;
		}

		// We are going to be removing some characters.  The string will shrink.
		if (delta < 0)
		{
			u32 i = 0;
			for (u32 pos = 0; pos <= used; ++i, ++pos)
			{
				// Is this potentially a match?
				if (array[pos] == *other)
				{
					// Check to see if we have a match.
					u32 j;
					for (j = 0; j < other_size; ++j)
					{
						if (array[pos + j] != other[j])
							break;
					}

					// If we have a match, replace characters.
					if (j == other_size)
					{
						for (j = 0; j < replace_size; ++j)
							array[i + j] = replace[j];
						i += replace_size - 1;
						pos += other_size - 1;
						continue;
					}
				}

				// No match found, just copy characters.
				array[i - 1] = array[pos];
			}
			array[i] = 0;
			used = i;

			return *this;
		}

		// We are going to be adding characters, so the string size will increase.
		// Count the number of times toReplace exists in the string so we can allocate the new size.
		u32 find_count = 0;
		s32 pos = 0;
		while ((pos = find_raw(other, pos)) != -1)
		{
			++find_count;
			++pos;
		}

		// Re-allocate the string now, if needed.
		u32 len = delta * find_count;
		if (used + len >= allocated)
			reallocate(used + len);

		// Start replacing.
		pos = 0;
		while ((pos = find_raw(other, pos)) != -1)
		{
			uchar16_t* start = array + pos + other_size - 1;
			uchar16_t* ptr   = array + used;
			uchar16_t* end   = array + used + delta;

			// Shift characters to make room for the string.
			while (ptr != start)
			{
				*end = *ptr;
				--ptr;
				--end;
			}

			// Add the new string now.
			for (u32 i = 0; i < replace_size; ++i)
				array[pos + i] = replace[i];

			pos += replace_size;
			used += delta;
		}

		// Terminate the string and return ourself.
		array[used] = 0;
		return *this;
	}


	//! Removes characters from a ustring16..
	//! \param c The character to remove.
	//! \return A reference to our current string.
	ustring16<TAlloc>& remove(uchar32_t c)
	{
		u32 pos = 0;
		u32 found = 0;
		u32 len = (c > 0xFFFF ? 2 : 1);		// Remove characters equal to the size of c as a UTF-16 character.
		for (u32 i=0; i<=used; ++i)
		{
			uchar32_t uc32 = 0;
			if (!UTF16_IS_SURROGATE_HI(array[i]))
				uc32 |= array[i];
			else if (i + 1 <= used)
			{
				// Convert the surrogate pair into a single UTF-32 character.
				uc32 = unicode::toUTF32(array[i], array[i + 1]);
			}
			u32 len2 = (uc32 > 0xFFFF ? 2 : 1);

			if (uc32 == c)
			{
				found += len;
				continue;
			}

			array[pos++] = array[i];
			if (len2 == 2)
				array[pos++] = array[++i];
		}
		used -= found;
		array[used] = 0;
		return *this;
	}


	//! Removes a ustring16 from the ustring16.
	//! \param toRemove The string to remove.
	//! \return A reference to our current string.
	ustring16<TAlloc>& remove(const ustring16<TAlloc>& toRemove)
	{
		u32 size = toRemove.size_raw();
		if (size == 0) return *this;

		const uchar16_t* tra = toRemove.c_str();
		u32 pos = 0;
		u32 found = 0;
		for (u32 i=0; i<=used; ++i)
		{
			u32 j = 0;
			while (j < size)
			{
				if (array[i + j] != tra[j])
					break;
				++j;
			}
			if (j == size)
			{
				found += size;
				i += size - 1;
				continue;
			}

			array[pos++] = array[i];
		}
		used -= found;
		array[used] = 0;
		return *this;
	}


	//! Removes characters from the ustring16.
	//! \param characters The characters to remove.
	//! \return A reference to our current string.
	ustring16<TAlloc>& removeChars(const ustring16<TAlloc>& characters)
	{
		if (characters.size_raw() == 0)
			return *this;

		u32 pos = 0;
		u32 found = 0;
		const_iterator iter(characters);
		for (u32 i=0; i<=used; ++i)
		{
			uchar32_t uc32 = 0;
			if (!UTF16_IS_SURROGATE_HI(array[i]))
				uc32 |= array[i];
			else if (i + 1 <= used)
			{
				// Convert the surrogate pair into a single UTF-32 character.
				uc32 = unicode::toUTF32(array[i], array[i+1]);
			}
			u32 len2 = (uc32 > 0xFFFF ? 2 : 1);

			bool cont = false;
			iter.toStart();
			while (!iter.atEnd())
			{
				uchar32_t c = *iter;
				if (uc32 == c)
				{
					found += (c > 0xFFFF ? 2 : 1);		// Remove characters equal to the size of c as a UTF-16 character.
					++i;
					cont = true;
					break;
				}
				++iter;
			}
			if (cont) continue;

			array[pos++] = array[i];
			if (len2 == 2)
				array[pos++] = array[++i];
		}
		used -= found;
		array[used] = 0;
		return *this;
	}


	//! Trims the ustring16.
	//! Removes the specified characters (by default, Latin-1 whitespace) from the begining and the end of the ustring16.
	//! \param whitespace The characters that are to be considered as whitespace.
	//! \return A reference to our current string.
	ustring16<TAlloc>& trim(const ustring16<TAlloc>& whitespace = " \t\n\r")
	{
		core::array<uchar32_t> utf32white = whitespace.toUTF32();

		// find start and end of the substring without the specified characters
		const s32 begin = findFirstCharNotInList(utf32white.const_pointer(), whitespace.used + 1);
		if (begin == -1)
			return (*this="");

		const s32 end = findLastCharNotInList(utf32white.const_pointer(), whitespace.used + 1);

		return (*this = subString(begin, (end +1) - begin));
	}


	//! Erases a character from the ustring16.
	//! May be slow, because all elements following after the erased element have to be copied.
	//! \param index Index of element to be erased.
	//! \return A reference to our current string.
	ustring16<TAlloc>& erase(u32 index)
	{
		_IRR_DEBUG_BREAK_IF(index>used) // access violation

		iterator i(*this, index);

		uchar32_t t = *i;
		u32 len = (t > 0xFFFF ? 2 : 1);

		for (u32 j = static_cast<u32>(i.getPos()) + len; j <= used; ++j)
			array[j - len] = array[j];

		used -= len;
		array[used] = 0;

		return *this;
	}


	//! Validate the existing ustring16, checking for valid surrogate pairs and checking for proper termination.
	//! \return A reference to our current string.
	ustring16<TAlloc>& validate()
	{
		// Validate all unicode characters.
		for (u32 i=0; i<allocated; ++i)
		{
			// Terminate on existing null.
			if (array[i] == 0)
			{
				used = i;
				return *this;
			}
			if (UTF16_IS_SURROGATE(array[i]))
			{
				if (((i+1) >= allocated) || UTF16_IS_SURROGATE_LO(array[i]))
					array[i] = unicode::UTF_REPLACEMENT_CHARACTER;
				else if (UTF16_IS_SURROGATE_HI(array[i]) && !UTF16_IS_SURROGATE_LO(array[i+1]))
					array[i] = unicode::UTF_REPLACEMENT_CHARACTER;
				++i;
			}
			if (array[i] >= 0xFDD0 && array[i] <= 0xFDEF)
				array[i] = unicode::UTF_REPLACEMENT_CHARACTER;
		}

		// terminate
		used = 0;
		if (allocated > 0)
		{
			used = allocated - 1;
			array[used] = 0;
		}
		return *this;
	}


	//! Gets the last char of the ustring16, or 0.
	//! \return The last char of the ustring16, or 0.
	uchar32_t lastChar() const
	{
		if (used < 1)
			return 0;

		if (UTF16_IS_SURROGATE_LO(array[used-1]))
		{
			// Make sure we have a paired surrogate.
			if (used < 2)
				return 0;

			// Check for an invalid surrogate.
			if (!UTF16_IS_SURROGATE_HI(array[used-2]))
				return 0;

			// Convert the surrogate pair into a single UTF-32 character.
			return unicode::toUTF32(array[used-2], array[used-1]);
		}
		else
		{
			return array[used-1];
		}
	}


	//! Split the ustring16 into parts.
	/** This method will split a ustring16 at certain delimiter characters
	into the container passed in as reference. The type of the container
	has to be given as template parameter. It must provide a push_back and
	a size method.
	\param ret The result container
	\param c C-style ustring16 of delimiter characters
	\param count Number of delimiter characters
	\param ignoreEmptyTokens Flag to avoid empty substrings in the result
	container. If two delimiters occur without a character in between, an
	empty substring would be placed in the result. If this flag is set,
	only non-empty strings are stored.
	\param keepSeparators Flag which allows to add the separator to the
	result ustring16. If this flag is true, the concatenation of the
	substrings results in the original ustring16. Otherwise, only the
	characters between the delimiters are returned.
	\return The number of resulting substrings
	*/
	template<class container>
	u32 split(container& ret, const uchar32_t* const c, u32 count=1, bool ignoreEmptyTokens=true, bool keepSeparators=false) const
	{
		if (!c)
			return 0;

		const_iterator i(*this);
		const u32 oldSize=ret.size();
		u32 pos = 0;
		u32 lastpos = 0;
		u32 lastpospos = 0;
		bool lastWasSeparator = false;
		while (!i.atEnd())
		{
			uchar32_t ch = *i;
			bool foundSeparator = false;
			for (u32 j=0; j<count; ++j)
			{
				if (ch == c[j])
				{
					if ((!ignoreEmptyTokens || pos - lastpos != 0) &&
							!lastWasSeparator)
					ret.push_back(ustring16<TAlloc>(&array[lastpospos], pos - lastpos));
					foundSeparator = true;
					lastpos = (keepSeparators ? pos : pos + 1);
					lastpospos = (keepSeparators ? i.getPos() : i.getPos() + 1);
					break;
				}
			}
			lastWasSeparator = foundSeparator;
			++pos;
			++i;
		}
		u32 s = size() + 1;
		if (s > lastpos)
			ret.push_back(ustring16<TAlloc>(&array[lastpospos], s - lastpos));
		return ret.size()-oldSize;
	}


	//! Split the ustring16 into parts.
	/** This method will split a ustring16 at certain delimiter characters
	into the container passed in as reference. The type of the container
	has to be given as template parameter. It must provide a push_back and
	a size method.
	\param ret The result container
	\param c A unicode string of delimiter characters
	\param ignoreEmptyTokens Flag to avoid empty substrings in the result
	container. If two delimiters occur without a character in between, an
	empty substring would be placed in the result. If this flag is set,
	only non-empty strings are stored.
	\param keepSeparators Flag which allows to add the separator to the
	result ustring16. If this flag is true, the concatenation of the
	substrings results in the original ustring16. Otherwise, only the
	characters between the delimiters are returned.
	\return The number of resulting substrings
	*/
	template<class container>
	u32 split(container& ret, const ustring16<TAlloc>& c, bool ignoreEmptyTokens=true, bool keepSeparators=false) const
	{
		core::array<uchar32_t> v = c.toUTF32();
		return split(ret, v.pointer(), v.size(), ignoreEmptyTokens, keepSeparators);
	}


	//! Gets the size of the allocated memory buffer for the string.
	//! \return The size of the allocated memory buffer.
	u32 capacity() const
	{
		return allocated;
	}


	//! Returns the raw number of UTF-16 code points in the string which includes the individual surrogates.
	//! \return The raw number of UTF-16 code points, excluding the trialing NUL.
	u32 size_raw() const
	{
		return used;
	}


	//! Inserts a character into the string.
	//! \param c The character to insert.
	//! \param pos The position to insert the character.
	//! \return A reference to our current string.
	ustring16<TAlloc>& insert(uchar32_t c, u32 pos)
	{
		u8 len = (c > 0xFFFF ? 2 : 1);

		if (used + len >= allocated)
			reallocate(used + len);

		used += len;

		iterator iter(*this, pos);
		for (u32 i = used - 2; i > iter.getPos(); --i)
			array[i] = array[i - len];

		if (c > 0xFFFF)
		{
			// c will be multibyte, so split it up into a surrogate pair.
			uchar16_t x = static_cast<uchar16_t>(c);
			uchar16_t vh = UTF16_HI_SURROGATE | ((((c >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10);
			uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1));
			array[iter.getPos()] = vh;
			array[iter.getPos()+1] = vl;
		}
		else
		{
			array[iter.getPos()] = static_cast<uchar16_t>(c);
		}
		array[used] = 0;
		return *this;
	}


	//! Inserts a string into the string.
	//! \param c The string to insert.
	//! \param pos The position to insert the string.
	//! \return A reference to our current string.
	ustring16<TAlloc>& insert(const ustring16<TAlloc>& c, u32 pos)
	{
		u32 len = c.size_raw();
		if (len == 0) return *this;

		if (used + len >= allocated)
			reallocate(used + len);

		used += len;

		iterator iter(*this, pos);
		for (u32 i = used - 2; i > iter.getPos() + len; --i)
			array[i] = array[i - len];

		const uchar16_t* s = c.c_str();
		for (u32 i = 0; i < len; ++i)
		{
			array[pos++] = *s;
			++s;
		}

		array[used] = 0;
		return *this;
	}


	//! Inserts a character into the string.
	//! \param c The character to insert.
	//! \param pos The position to insert the character.
	//! \return A reference to our current string.
	ustring16<TAlloc>& insert_raw(uchar16_t c, u32 pos)
	{
		if (used + 1 >= allocated)
			reallocate(used + 1);

		++used;

		for (u32 i = used - 1; i > pos; --i)
			array[i] = array[i - 1];

		array[pos] = c;
		array[used] = 0;
		return *this;
	}


	//! Removes a character from string.
	//! \param pos Position of the character to remove.
	//! \return A reference to our current string.
	ustring16<TAlloc>& erase_raw(u32 pos)
	{
		for (u32 i=pos; i<=used; ++i)
		{
			array[i] = array[i + 1];
		}
		--used;
		array[used] = 0;
		return *this;
	}


	//! Replaces a character in the string.
	//! \param c The new character.
	//! \param pos The position of the character to replace.
	//! \return A reference to our current string.
	ustring16<TAlloc>& replace_raw(uchar16_t c, u32 pos)
	{
		array[pos] = c;
		return *this;
	}


	//! Returns an iterator to the beginning of the string.
	//! \return An iterator to the beginning of the string.
	iterator begin()
	{
		iterator i(*this, 0);
		return i;
	}


	//! Returns an iterator to the beginning of the string.
	//! \return An iterator to the beginning of the string.
	const_iterator begin() const
	{
		const_iterator i(*this, 0);
		return i;
	}


	//! Returns an iterator to the beginning of the string.
	//! \return An iterator to the beginning of the string.
	const_iterator cbegin() const
	{
		const_iterator i(*this, 0);
		return i;
	}


	//! Returns an iterator to the end of the string.
	//! \return An iterator to the end of the string.
	iterator end()
	{
		iterator i(*this, 0);
		i.toEnd();
		return i;
	}


	//! Returns an iterator to the end of the string.
	//! \return An iterator to the end of the string.
	const_iterator end() const
	{
		const_iterator i(*this, 0);
		i.toEnd();
		return i;
	}


	//! Returns an iterator to the end of the string.
	//! \return An iterator to the end of the string.
	const_iterator cend() const
	{
		const_iterator i(*this, 0);
		i.toEnd();
		return i;
	}


	//! Converts the string to a UTF-8 encoded string.
	//! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string.
	//! \return A string containing the UTF-8 encoded string.
	core::string<uchar8_t> toUTF8_s(const bool addBOM = false) const
	{
		core::string<uchar8_t> ret;
		ret.reserve(used * 4 + (addBOM ? unicode::BOM_UTF8_LEN : 0) + 1);
		const_iterator iter(*this, 0);

		// Add the byte order mark if the user wants it.
		if (addBOM)
		{
			ret.append(unicode::BOM_ENCODE_UTF8[0]);
			ret.append(unicode::BOM_ENCODE_UTF8[1]);
			ret.append(unicode::BOM_ENCODE_UTF8[2]);
		}

		while (!iter.atEnd())
		{
			uchar32_t c = *iter;
			if (c > 0xFFFF)
			{	// 4 bytes
				uchar8_t b1 = (0x1E << 3) | ((c >> 18) & 0x7);
				uchar8_t b2 = (0x2 << 6) | ((c >> 12) & 0x3F);
				uchar8_t b3 = (0x2 << 6) | ((c >> 6) & 0x3F);
				uchar8_t b4 = (0x2 << 6) | (c & 0x3F);
				ret.append(b1);
				ret.append(b2);
				ret.append(b3);
				ret.append(b4);
			}
			else if (c > 0x7FF)
			{	// 3 bytes
				uchar8_t b1 = (0xE << 4) | ((c >> 12) & 0xF);
				uchar8_t b2 = (0x2 << 6) | ((c >> 6) & 0x3F);
				uchar8_t b3 = (0x2 << 6) | (c & 0x3F);
				ret.append(b1);
				ret.append(b2);
				ret.append(b3);
			}
			else if (c > 0x7F)
			{	// 2 bytes
				uchar8_t b1 = (0x6 << 5) | ((c >> 6) & 0x1F);
				uchar8_t b2 = (0x2 << 6) | (c & 0x3F);
				ret.append(b1);
				ret.append(b2);
			}
			else
			{	// 1 byte
				ret.append(static_cast<uchar8_t>(c));
			}
			++iter;
		}
		return ret;
	}


	//! Converts the string to a UTF-8 encoded string array.
	//! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string.
	//! \return An array containing the UTF-8 encoded string.
	core::array<uchar8_t> toUTF8(const bool addBOM = false) const
	{
		core::array<uchar8_t> ret(used * 4 + (addBOM ? unicode::BOM_UTF8_LEN : 0) + 1);
		const_iterator iter(*this, 0);

		// Add the byte order mark if the user wants it.
		if (addBOM)
		{
			ret.push_back(unicode::BOM_ENCODE_UTF8[0]);
			ret.push_back(unicode::BOM_ENCODE_UTF8[1]);
			ret.push_back(unicode::BOM_ENCODE_UTF8[2]);
		}

		while (!iter.atEnd())
		{
			uchar32_t c = *iter;
			if (c > 0xFFFF)
			{	// 4 bytes
				uchar8_t b1 = (0x1E << 3) | ((c >> 18) & 0x7);
				uchar8_t b2 = (0x2 << 6) | ((c >> 12) & 0x3F);
				uchar8_t b3 = (0x2 << 6) | ((c >> 6) & 0x3F);
				uchar8_t b4 = (0x2 << 6) | (c & 0x3F);
				ret.push_back(b1);
				ret.push_back(b2);
				ret.push_back(b3);
				ret.push_back(b4);
			}
			else if (c > 0x7FF)
			{	// 3 bytes
				uchar8_t b1 = (0xE << 4) | ((c >> 12) & 0xF);
				uchar8_t b2 = (0x2 << 6) | ((c >> 6) & 0x3F);
				uchar8_t b3 = (0x2 << 6) | (c & 0x3F);
				ret.push_back(b1);
				ret.push_back(b2);
				ret.push_back(b3);
			}
			else if (c > 0x7F)
			{	// 2 bytes
				uchar8_t b1 = (0x6 << 5) | ((c >> 6) & 0x1F);
				uchar8_t b2 = (0x2 << 6) | (c & 0x3F);
				ret.push_back(b1);
				ret.push_back(b2);
			}
			else
			{	// 1 byte
				ret.push_back(static_cast<uchar8_t>(c));
			}
			++iter;
		}
		ret.push_back(0);
		return ret;
	}


#ifdef USTRING_CPP0X_NEWLITERALS	// C++0x
	//! Converts the string to a UTF-16 encoded string.
	//! \param endian The desired endianness of the string.
	//! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string.
	//! \return A string containing the UTF-16 encoded string.
	core::string<char16_t> toUTF16_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const
	{
		core::string<char16_t> ret;
		ret.reserve(used + (addBOM ? unicode::BOM_UTF16_LEN : 0) + 1);

		// Add the BOM if specified.
		if (addBOM)
		{
			if (endian == unicode::EUTFEE_NATIVE)
				ret[0] = unicode::BOM;
			else if (endian == unicode::EUTFEE_LITTLE)
			{
				uchar8_t* ptr8 = reinterpret_cast<uchar8_t*>(ret.c_str());
				*ptr8++ = unicode::BOM_ENCODE_UTF16_LE[0];
				*ptr8 = unicode::BOM_ENCODE_UTF16_LE[1];
			}
			else
			{
				uchar8_t* ptr8 = reinterpret_cast<uchar8_t*>(ret.c_str());
				*ptr8++ = unicode::BOM_ENCODE_UTF16_BE[0];
				*ptr8 = unicode::BOM_ENCODE_UTF16_BE[1];
			}
		}

		ret.append(array);
		if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian)
		{
			char16_t* ptr = ret.c_str();
			for (u32 i = 0; i < ret.size(); ++i)
				*ptr++ = unicode::swapEndian16(*ptr);
		}
		return ret;
	}
#endif


	//! Converts the string to a UTF-16 encoded string array.
	//! Unfortunately, no toUTF16_s() version exists due to limitations with Irrlicht's string class.
	//! \param endian The desired endianness of the string.
	//! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string.
	//! \return An array containing the UTF-16 encoded string.
	core::array<uchar16_t> toUTF16(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const
	{
		core::array<uchar16_t> ret(used + (addBOM ? unicode::BOM_UTF16_LEN : 0) + 1);
		uchar16_t* ptr = ret.pointer();

		// Add the BOM if specified.
		if (addBOM)
		{
			if (endian == unicode::EUTFEE_NATIVE)
				*ptr = unicode::BOM;
			else if (endian == unicode::EUTFEE_LITTLE)
			{
				uchar8_t* ptr8 = reinterpret_cast<uchar8_t*>(ptr);
				*ptr8++ = unicode::BOM_ENCODE_UTF16_LE[0];
				*ptr8 = unicode::BOM_ENCODE_UTF16_LE[1];
			}
			else
			{
				uchar8_t* ptr8 = reinterpret_cast<uchar8_t*>(ptr);
				*ptr8++ = unicode::BOM_ENCODE_UTF16_BE[0];
				*ptr8 = unicode::BOM_ENCODE_UTF16_BE[1];
			}
			++ptr;
		}

		memcpy((void*)ptr, (void*)array, used * sizeof(uchar16_t));
		if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian)
		{
			for (u32 i = 0; i <= used; ++i)
				ptr[i] = unicode::swapEndian16(ptr[i]);
		}
		ret.set_used(used + (addBOM ? unicode::BOM_UTF16_LEN : 0));
		ret.push_back(0);
		return ret;
	}


#ifdef USTRING_CPP0X_NEWLITERALS	// C++0x
	//! Converts the string to a UTF-32 encoded string.
	//! \param endian The desired endianness of the string.
	//! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string.
	//! \return A string containing the UTF-32 encoded string.
	core::string<char32_t> toUTF32_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const
	{
		core::string<char32_t> ret;
		ret.reserve(size() + 1 + (addBOM ? unicode::BOM_UTF32_LEN : 0));
		const_iterator iter(*this, 0);

		// Add the BOM if specified.
		if (addBOM)
		{
			if (endian == unicode::EUTFEE_NATIVE)
				ret.append(unicode::BOM);
			else
			{
				union
				{
					uchar32_t full;
					u8 chunk[4];
				} t;

				if (endian == unicode::EUTFEE_LITTLE)
				{
					t.chunk[0] = unicode::BOM_ENCODE_UTF32_LE[0];
					t.chunk[1] = unicode::BOM_ENCODE_UTF32_LE[1];
					t.chunk[2] = unicode::BOM_ENCODE_UTF32_LE[2];
					t.chunk[3] = unicode::BOM_ENCODE_UTF32_LE[3];
				}
				else
				{
					t.chunk[0] = unicode::BOM_ENCODE_UTF32_BE[0];
					t.chunk[1] = unicode::BOM_ENCODE_UTF32_BE[1];
					t.chunk[2] = unicode::BOM_ENCODE_UTF32_BE[2];
					t.chunk[3] = unicode::BOM_ENCODE_UTF32_BE[3];
				}
				ret.append(t.full);
			}
		}

		while (!iter.atEnd())
		{
			uchar32_t c = *iter;
			if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian)
				c = unicode::swapEndian32(c);
			ret.append(c);
			++iter;
		}
		return ret;
	}
#endif


	//! Converts the string to a UTF-32 encoded string array.
	//! Unfortunately, no toUTF32_s() version exists due to limitations with Irrlicht's string class.
	//! \param endian The desired endianness of the string.
	//! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string.
	//! \return An array containing the UTF-32 encoded string.
	core::array<uchar32_t> toUTF32(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const
	{
		core::array<uchar32_t> ret(size() + (addBOM ? unicode::BOM_UTF32_LEN : 0) + 1);
		const_iterator iter(*this, 0);

		// Add the BOM if specified.
		if (addBOM)
		{
			if (endian == unicode::EUTFEE_NATIVE)
				ret.push_back(unicode::BOM);
			else
			{
				union
				{
					uchar32_t full;
					u8 chunk[4];
				} t;

				if (endian == unicode::EUTFEE_LITTLE)
				{
					t.chunk[0] = unicode::BOM_ENCODE_UTF32_LE[0];
					t.chunk[1] = unicode::BOM_ENCODE_UTF32_LE[1];
					t.chunk[2] = unicode::BOM_ENCODE_UTF32_LE[2];
					t.chunk[3] = unicode::BOM_ENCODE_UTF32_LE[3];
				}
				else
				{
					t.chunk[0] = unicode::BOM_ENCODE_UTF32_BE[0];
					t.chunk[1] = unicode::BOM_ENCODE_UTF32_BE[1];
					t.chunk[2] = unicode::BOM_ENCODE_UTF32_BE[2];
					t.chunk[3] = unicode::BOM_ENCODE_UTF32_BE[3];
				}
				ret.push_back(t.full);
			}
		}
		ret.push_back(0);

		while (!iter.atEnd())
		{
			uchar32_t c = *iter;
			if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian)
				c = unicode::swapEndian32(c);
			ret.push_back(c);
			++iter;
		}
		return ret;
	}


	//! Converts the string to a wchar_t encoded string.
	/** The size of a wchar_t changes depending on the platform.  This function will store a
	correct UTF-8, -16, or -32 encoded string depending on the size of a wchar_t. **/
	//! \param endian The desired endianness of the string.
	//! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string.
	//! \return A string containing the wchar_t encoded string.
	core::string<wchar_t> toWCHAR_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const
	{
		if (sizeof(wchar_t) == 4)
		{
			core::array<uchar32_t> a(toUTF32(endian, addBOM));
			core::stringw ret(a.pointer());
			return ret;
		}
		else if (sizeof(wchar_t) == 2)
		{
			if (endian == unicode::EUTFEE_NATIVE && addBOM == false)
			{
				core::stringw ret(array);
				return ret;
			}
			else
			{
				core::array<uchar16_t> a(toUTF16(endian, addBOM));
				core::stringw ret(a.pointer());
				return ret;
			}
		}
		else if (sizeof(wchar_t) == 1)
		{
			core::array<uchar8_t> a(toUTF8(addBOM));
			core::stringw ret(a.pointer());
			return ret;
		}

		// Shouldn't happen.
		return core::stringw();
	}


	//! Converts the string to a wchar_t encoded string array.
	/** The size of a wchar_t changes depending on the platform.  This function will store a
	correct UTF-8, -16, or -32 encoded string depending on the size of a wchar_t. **/
	//! \param endian The desired endianness of the string.
	//! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string.
	//! \return An array containing the wchar_t encoded string.
	core::array<wchar_t> toWCHAR(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const
	{
		if (sizeof(wchar_t) == 4)
		{
			core::array<uchar32_t> a(toUTF32(endian, addBOM));
			core::array<wchar_t> ret(a.size());
			ret.set_used(a.size());
			memcpy((void*)ret.pointer(), (void*)a.pointer(), a.size() * sizeof(uchar32_t));
			return ret;
		}
		if (sizeof(wchar_t) == 2)
		{
			if (endian == unicode::EUTFEE_NATIVE && addBOM == false)
			{
				core::array<wchar_t> ret(used);
				ret.set_used(used);
				memcpy((void*)ret.pointer(), (void*)array, used * sizeof(uchar16_t));
				return ret;
			}
			else
			{
				core::array<uchar16_t> a(toUTF16(endian, addBOM));
				core::array<wchar_t> ret(a.size());
				ret.set_used(a.size());
				memcpy((void*)ret.pointer(), (void*)a.pointer(), a.size() * sizeof(uchar16_t));
				return ret;
			}
		}
		if (sizeof(wchar_t) == 1)
		{
			core::array<uchar8_t> a(toUTF8(addBOM));
			core::array<wchar_t> ret(a.size());
			ret.set_used(a.size());
			memcpy((void*)ret.pointer(), (void*)a.pointer(), a.size() * sizeof(uchar8_t));
			return ret;
		}

		// Shouldn't happen.
		return core::array<wchar_t>();
	}

	//! Converts the string to a properly encoded io::path string.
	//! \param endian The desired endianness of the string.
	//! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string.
	//! \return An io::path string containing the properly encoded string.
	io::path toPATH_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const
	{
#if defined(_IRR_WCHAR_FILESYSTEM)
		return toWCHAR_s(endian, addBOM);
#else
		return toUTF8_s(addBOM);
#endif
	}

	//! Loads an unknown stream of data.
	//! Will attempt to determine if the stream is unicode data.  Useful for loading from files.
	//! \param data The data stream to load from.
	//! \param data_size The length of the data string.
	//! \return A reference to our current string.
	ustring16<TAlloc>& loadDataStream(const char* data, size_t data_size)
	{
		// Clear our string.
		*this = "";
		if (!data)
			return *this;

		unicode::EUTF_ENCODE e = unicode::determineUnicodeBOM(data);
		switch (e)
		{
			default:
			case unicode::EUTFE_UTF8:
				append((uchar8_t*)data, data_size);
				break;

			case unicode::EUTFE_UTF16:
			case unicode::EUTFE_UTF16_BE:
			case unicode::EUTFE_UTF16_LE:
				append((uchar16_t*)data, data_size / 2);
				break;

			case unicode::EUTFE_UTF32:
			case unicode::EUTFE_UTF32_BE:
			case unicode::EUTFE_UTF32_LE:
				append((uchar32_t*)data, data_size / 4);
				break;
		}

		return *this;
	}

	//! Gets the encoding of the Unicode string this class contains.
	//! \return An enum describing the current encoding of this string.
	const unicode::EUTF_ENCODE getEncoding() const
	{
		return encoding;
	}

	//! Gets the endianness of the Unicode string this class contains.
	//! \return An enum describing the endianness of this string.
	const unicode::EUTF_ENDIAN getEndianness() const
	{
		if (encoding == unicode::EUTFE_UTF16_LE ||
			encoding == unicode::EUTFE_UTF32_LE)
			return unicode::EUTFEE_LITTLE;
		else return unicode::EUTFEE_BIG;
	}

private:

	//! Reallocate the string, making it bigger or smaller.
	//! \param new_size The new size of the string.
	void reallocate(u32 new_size)
	{
		uchar16_t* old_array = array;

		array = allocator.allocate(new_size + 1); //new u16[new_size];
		allocated = new_size + 1;
		if (old_array == 0) return;

		u32 amount = used < new_size ? used : new_size;
		for (u32 i=0; i<=amount; ++i)
			array[i] = old_array[i];

		if (allocated <= used)
			used = allocated - 1;

		array[used] = 0;

		allocator.deallocate(old_array); // delete [] old_array;
	}

	//--- member variables

	uchar16_t* array;
	unicode::EUTF_ENCODE encoding;
	u32 allocated;
	u32 used;
	TAlloc allocator;
	//irrAllocator<uchar16_t> allocator;
};

typedef ustring16<irrAllocator<uchar16_t> > ustring;


//! Appends two ustring16s.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const ustring16<TAlloc>& right)
{
	ustring16<TAlloc> ret(left);
	ret += right;
	return ret;
}


//! Appends a ustring16 and a null-terminated unicode string.
template <typename TAlloc, class B>
inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const B* const right)
{
	ustring16<TAlloc> ret(left);
	ret += right;
	return ret;
}


//! Appends a ustring16 and a null-terminated unicode string.
template <class B, typename TAlloc>
inline ustring16<TAlloc> operator+(const B* const left, const ustring16<TAlloc>& right)
{
	ustring16<TAlloc> ret(left);
	ret += right;
	return ret;
}


//! Appends a ustring16 and an Irrlicht string.
template <typename TAlloc, typename B, typename BAlloc>
inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const string<B, BAlloc>& right)
{
	ustring16<TAlloc> ret(left);
	ret += right;
	return ret;
}


//! Appends a ustring16 and an Irrlicht string.
template <typename TAlloc, typename B, typename BAlloc>
inline ustring16<TAlloc> operator+(const string<B, BAlloc>& left, const ustring16<TAlloc>& right)
{
	ustring16<TAlloc> ret(left);
	ret += right;
	return ret;
}


//! Appends a ustring16 and a std::basic_string.
template <typename TAlloc, typename B, typename A, typename BAlloc>
inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const std::basic_string<B, A, BAlloc>& right)
{
	ustring16<TAlloc> ret(left);
	ret += right;
	return ret;
}


//! Appends a ustring16 and a std::basic_string.
template <typename TAlloc, typename B, typename A, typename BAlloc>
inline ustring16<TAlloc> operator+(const std::basic_string<B, A, BAlloc>& left, const ustring16<TAlloc>& right)
{
	ustring16<TAlloc> ret(left);
	ret += right;
	return ret;
}


//! Appends a ustring16 and a char.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const char right)
{
	ustring16<TAlloc> ret(left);
	ret += right;
	return ret;
}


//! Appends a ustring16 and a char.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const char left, const ustring16<TAlloc>& right)
{
	ustring16<TAlloc> ret(left);
	ret += right;
	return ret;
}


#ifdef USTRING_CPP0X_NEWLITERALS
//! Appends a ustring16 and a uchar32_t.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const uchar32_t right)
{
	ustring16<TAlloc> ret(left);
	ret += right;
	return ret;
}


//! Appends a ustring16 and a uchar32_t.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const uchar32_t left, const ustring16<TAlloc>& right)
{
	ustring16<TAlloc> ret(left);
	ret += right;
	return ret;
}
#endif


//! Appends a ustring16 and a short.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const short right)
{
	ustring16<TAlloc> ret(left);
	ret += core::stringc(right);
	return ret;
}


//! Appends a ustring16 and a short.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const short left, const ustring16<TAlloc>& right)
{
	ustring16<TAlloc> ret((core::stringc(left)));
	ret += right;
	return ret;
}


//! Appends a ustring16 and an unsigned short.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const unsigned short right)
{
	ustring16<TAlloc> ret(left);
	ret += core::stringc(right);
	return ret;
}


//! Appends a ustring16 and an unsigned short.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const unsigned short left, const ustring16<TAlloc>& right)
{
	ustring16<TAlloc> ret((core::stringc(left)));
	ret += right;
	return ret;
}


//! Appends a ustring16 and an int.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const int right)
{
	ustring16<TAlloc> ret(left);
	ret += core::stringc(right);
	return ret;
}


//! Appends a ustring16 and an int.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const int left, const ustring16<TAlloc>& right)
{
	ustring16<TAlloc> ret((core::stringc(left)));
	ret += right;
	return ret;
}


//! Appends a ustring16 and an unsigned int.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const unsigned int right)
{
	ustring16<TAlloc> ret(left);
	ret += core::stringc(right);
	return ret;
}


//! Appends a ustring16 and an unsigned int.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const unsigned int left, const ustring16<TAlloc>& right)
{
	ustring16<TAlloc> ret((core::stringc(left)));
	ret += right;
	return ret;
}


//! Appends a ustring16 and a long.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const long right)
{
	ustring16<TAlloc> ret(left);
	ret += core::stringc(right);
	return ret;
}


//! Appends a ustring16 and a long.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const long left, const ustring16<TAlloc>& right)
{
	ustring16<TAlloc> ret((core::stringc(left)));
	ret += right;
	return ret;
}


//! Appends a ustring16 and an unsigned long.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const unsigned long right)
{
	ustring16<TAlloc> ret(left);
	ret += core::stringc(right);
	return ret;
}


//! Appends a ustring16 and an unsigned long.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const unsigned long left, const ustring16<TAlloc>& right)
{
	ustring16<TAlloc> ret((core::stringc(left)));
	ret += right;
	return ret;
}


//! Appends a ustring16 and a float.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const float right)
{
	ustring16<TAlloc> ret(left);
	ret += core::stringc(right);
	return ret;
}


//! Appends a ustring16 and a float.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const float left, const ustring16<TAlloc>& right)
{
	ustring16<TAlloc> ret((core::stringc(left)));
	ret += right;
	return ret;
}


//! Appends a ustring16 and a double.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const double right)
{
	ustring16<TAlloc> ret(left);
	ret += core::stringc(right);
	return ret;
}


//! Appends a ustring16 and a double.
template <typename TAlloc>
inline ustring16<TAlloc> operator+(const double left, const ustring16<TAlloc>& right)
{
	ustring16<TAlloc> ret((core::stringc(left)));
	ret += right;
	return ret;
}


#ifdef USTRING_CPP0X
//! Appends two ustring16s.
template <typename TAlloc>
inline ustring16<TAlloc>&& operator+(const ustring16<TAlloc>& left, ustring16<TAlloc>&& right)
{
	//std::cout << "MOVE operator+(&, &&)" << std::endl;
	right.insert(left, 0);
	return std::move(right);
}


//! Appends two ustring16s.
template <typename TAlloc>
inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, const ustring16<TAlloc>& right)
{
	//std::cout << "MOVE operator+(&&, &)" << std::endl;
	left.append(right);
	return std::move(left);
}


//! Appends two ustring16s.
template <typename TAlloc>
inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, ustring16<TAlloc>&& right)
{
	//std::cout << "MOVE operator+(&&, &&)" << std::endl;
	if ((right.size_raw() <= left.capacity() - left.size_raw()) ||
		(right.capacity() - right.size_raw() < left.size_raw()))
	{
		left.append(right);
		return std::move(left);
	}
	else
	{
		right.insert(left, 0);
		return std::move(right);
	}
}


//! Appends a ustring16 and a null-terminated unicode string.
template <typename TAlloc, class B>
inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, const B* const right)
{
	//std::cout << "MOVE operator+(&&, B*)" << std::endl;
	left.append(right);
	return std::move(left);
}


//! Appends a ustring16 and a null-terminated unicode string.
template <class B, typename TAlloc>
inline ustring16<TAlloc>&& operator+(const B* const left, ustring16<TAlloc>&& right)
{
	//std::cout << "MOVE operator+(B*, &&)" << std::endl;
	right.insert(left, 0);
	return std::move(right);