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
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
/*!
Contains the `DynTrait` type,and related traits/type aliases.
*/

use std::{
    fmt::{self,Write as fmtWrite},
    io,
    ops::DerefMut,
    marker::PhantomData,
    mem::ManuallyDrop,
    ptr,
    rc::Rc,
};

use serde::{de, ser, Deserialize, Deserializer};

#[allow(unused_imports)]
use core_extensions::{prelude::*, ResultLike};

use crate::{
    abi_stability::SharedStableAbi,
    pointer_trait::{
        StableDeref, TransmuteElement,
        GetPointerKind,PK_SmartPointer,PK_Reference,
    },
    marker_type::{ErasedObject,UnsafeIgnoredType}, 
    std_types::{RBox, RCow, RStr,RVec,RIoError},
};

#[allow(unused_imports)]
use crate::std_types::Tuple2;

use super::*;
use super::{
    c_functions::adapt_std_fmt,
    trait_objects::*,
    vtable::{GetVtable, VTable},
    traits::InterfaceFor,
};


#[cfg(all(test,not(feature="only_new_tests")))]
mod tests;

mod priv_ {
    use super::*;


    /**

DynTrait implements ffi-safe trait objects,for a selection of traits.

# Passing opaque values around with `DynTrait<_>`

One can pass non-StableAbi types around by using type erasure,using this type.

It generally looks like `DynTrait<'borrow,Pointer<()>,Interface>`,where:

- `'borrow` is the borrow that the type that was erased had.

- `Pointer` is some `pointer_trait::StableDeref` pointer type.

- `Interface` is an `InterfaceType`,which describes what traits are 
    required when constructing the `DynTrait<_>` and which ones it implements.

`trait InterfaceType` allows describing which traits are required 
when constructing a `DynTrait<_>`,and which ones it implements.

### Construction

To construct a `DynTrait<_>` one can use these associated functions:
    
- from_value:
    Can be constructed from the value directly.
    Requires a value that implements ImplType.
    
- from_ptr:
    Can be constructed from a pointer of a value.
    Requires a value that implements ImplType.
    
- from_any_value:
    Can be constructed from the value directly.Requires a `'static` value.
    
- from_any_ptr
    Can be constructed from a pointer of a value.Requires a `'static` value.

- from_borrowing_value:
    Can be constructed from the value directly.Cannot unerase the DynTrait afterwards.
    
- from_borrowing_ptr
    Can be constructed from a pointer of a value.Cannot unerase the DynTrait afterwards.

DynTrait uses the impls of the value in methods,
which means that the pointer itself does not have to implement those traits,

### Trait object

`DynTrait<'borrow,Pointer<()>,Interface>` 
can be used as a trait object for any combination of 
the traits listed bellow.

These are the traits:

- Send

- Sync

- Iterator

- DoubleEndedIterator

- std::fmt::Write

- std::io::Write

- std::io::Seek

- std::io::Read

- std::io::BufRead

- Clone 

- Display 

- Debug 

- Default: Can be called as an inherent method.

- Eq 

- PartialEq 

- Ord 

- PartialOrd 

- Hash 

- serde::Deserialize:
    first deserializes from a string,and then calls the objects' Deserialize impl.

- serde::Serialize:
    first calls the objects' Deserialize impl,then serializes that as a string.

### Deconstruction

`DynTrait<_>` can then be unwrapped into a concrete type,
within the same dynamic library/executable that constructed it,
using these (fallible) conversion methods:

- into_unerased:
    Unwraps into a pointer to `T`.
    Where `DynTrait<P<()>,Interface>`'s 
        Interface must equal `<T as ImplType>::Interface`

- as_unerased:
    Unwraps into a `&T`.
    Where `DynTrait<P<()>,Interface>`'s 
        Interface must equal `<T as ImplType>::Interface`

- as_unerased_mut:
    Unwraps into a `&mut T`.
    Where `DynTrait<P<()>,Interface>`'s 
        Interface must equal `<T as ImplType>::Interface`

- into_any_unerased:Unwraps into a pointer to `T`.Requires `T:'static`.

- as_any_unerased:Unwraps into a `&T`.Requires `T:'static`.

- as_any_unerased_mut:Unwraps into a `&mut T`.Requires `T:'static`.


`DynTrait` cannot be converted back if it was created 
using `DynTrait::from_borrowing_*`.

# Passing DynTrait between dynamic libraries

Passing DynTrait between dynamic libraries 
(as in between the dynamic libraries directly loaded by the same binary/dynamic library)
may cause the program to panic at runtime with an error message stating that 
the trait is not implemented for the specific interface.

This can only happen if you are passing DynTrait between dynamic libraries,
or if DynTrait was instantiated in the parent passed to a child,
a DynTrait instantiated in a child dynamic library passed to the parent
should not cause a panic,it would be a bug.

```text
        binary
  _________|___________
lib0      lib1      lib2
  |         |         |
lib00    lib10      lib20
```

In this diagram passing a DynTrait constructed in lib00 to anything other than 
the binary or lib0 will cause the panic to happen if:

- The InterfaceType requires extra traits in the version of the Interface
    that lib1 and lib2 know about (that the binary does not require).

- lib1 or lib2 attempt to call methods that require the traits that were added 
    to the InterfaceType,in versions of that interface that only they know about.






# Examples

### In the Readme

The primary example using `DynTrait<_>` is in the readme.

Readme is in 
[the repository for this crate](https://github.com/rodrimati1992/abi_stable_crates),
[crates.io](https://crates.io/crates/abi_stable),
[lib.rs](https://lib.rs/crates/abi_stable).

### Comparing DynTraits

This is only possible if the erased types don't contain borrows,
and they are not constructed using `DynTrait::from_borrowing_*` methods.

DynTraits wrapping different pointer types can be compared with each other,
it simply uses the values' implementation of PartialEq.

```
use abi_stable::{
    DynTrait,
    erased_types::interfaces::PartialEqInterface,
    std_types::RArc,
};

{
    let left:DynTrait<'static,&(),PartialEqInterface>=
        DynTrait::from_any_ptr(&100,PartialEqInterface);
    
    let mut n100=100;
    let right:DynTrait<'static,&mut (),PartialEqInterface>=
        DynTrait::from_any_ptr(&mut n100,PartialEqInterface);

    assert_eq!(left,right);
}
{
    let left=
        DynTrait::from_any_value(200,PartialEqInterface);

    let right=
        DynTrait::from_any_ptr(RArc::new(200),PartialEqInterface);

    assert_eq!(left,right);
}

```

### Writing to a DynTrait

This is an example of using the `write!()` macro with DynTrait.

```
use abi_stable::{
    DynTrait,
    erased_types::interfaces::FmtWriteInterface,
};

use std::fmt::Write;

let mut buffer=String::new();

let mut wrapped:DynTrait<'static,&mut (),FmtWriteInterface>=
    DynTrait::from_any_ptr(&mut buffer,FmtWriteInterface);

write!(wrapped,"Foo").unwrap();
write!(wrapped,"Bar").unwrap();
write!(wrapped,"Baz").unwrap();

drop(wrapped);

assert_eq!(&buffer[..],"FooBarBaz");


```


### Iteration

Using `DynTrait` as an `Iterator` and `DoubleEndedIterator`.

```
use abi_stable::{
    DynTrait,
    erased_types::interfaces::DEIteratorInterface,
};

let mut wrapped=DynTrait::from_any_value(0..=10,DEIteratorInterface::NEW);

assert_eq!(
    wrapped.by_ref().take(5).collect::<Vec<_>>(),
    vec![0,1,2,3,4]
);

assert_eq!(
    wrapped.rev().collect::<Vec<_>>(),
    vec![10,9,8,7,6,5]
);


```


# Making pointers compatible with DynTrait

To make pointers compatible with DynTrait,they must imlement the 
`abi_stable::pointer_trait::{GetPointerKind,StableDeref,TransmuteElement}` traits 
as shown in the example.

`GetPointerKind` should generally be implemented with `type Kind=PK_SmartPointer`.
The exception is in the case that it is a `#[repr(transparent)]`
wrapper around a `&` or a `&mut`,
in which case it should implement `GetPointerKind<Kind=PK_Reference>` 
or `GetPointerKind<Kind=PK_MutReference>` respectively.

### Example

This is an example of a newtype wrapping an `RBox<T>`.

```rust 
    
use abi_stable::DynTrait;

fn main(){
    let lines="line0\nline1\nline2";
    let mut iter=NewtypeBox::new(lines.lines());

    // The type annotation here is just to show the type,it's not necessary.
    let mut wrapper:DynTrait<'_,NewtypeBox<()>,IteratorInterface>=
        DynTrait::from_borrowing_ptr(iter,IteratorInterface);

    // You can clone the DynTrait! 
    let clone=wrapper.clone();

    assert_eq!( wrapper.next(), Some("line0") );
    assert_eq!( wrapper.next(), Some("line1") );
    assert_eq!( wrapper.next(), Some("line2") );
    assert_eq!( wrapper.next(), None );

    assert_eq!(
        clone.rev().collect::<Vec<_>>(),
        vec!["line2","line1","line0"],
    )

}


/////////////////////////////////////////

use std::ops::{Deref, DerefMut};

use abi_stable::{
    StableAbi,
    InterfaceType,
    impl_InterfaceType,
    std_types::RBox,
    erased_types::IteratorItem,
    pointer_trait::{
        PK_SmartPointer,GetPointerKind,StableDeref,TransmuteElement
    },
    type_level::bools::True,
};

#[repr(transparent)]
#[derive(Default,Clone,StableAbi)]
pub struct NewtypeBox<T>{
    box_:RBox<T>,
}

impl<T> NewtypeBox<T>{
    pub fn new(value:T)->Self{
        Self{
            box_:RBox::new(value)
        }
    }
}

impl<T> Deref for NewtypeBox<T>{
    type Target=T;

    fn deref(&self)->&T{
        &*self.box_
    }
}

impl<T> DerefMut for NewtypeBox<T>{
    fn deref_mut(&mut self)->&mut T{
        &mut *self.box_
    }
}

unsafe impl<T> GetPointerKind for NewtypeBox<T>{
    type Kind=PK_SmartPointer;
}

unsafe impl<T> StableDeref for NewtypeBox<T> {}

unsafe impl<T,O> TransmuteElement<O> for NewtypeBox<T>
where 
    // Using this to ensure that the pointer is safe to wrap,
    // while this is not necessary for `RBox<T>`,
    // it might be for some other pointer type.
    RBox<T>:TransmuteElement<O,Kind=Self::Kind>
{
    type TransmutedPtr = NewtypeBox<O>;
}

/////////////////////////////////////////

#[repr(C)]
#[derive(StableAbi)]
pub struct IteratorInterface;

impl_InterfaceType!{
    impl InterfaceType for IteratorInterface {
        type Iterator = True;
        type DoubleEndedIterator = True;
        type Clone = True;
        type Debug = True;
    }
}

impl<'a> IteratorItem<'a> for IteratorInterface{
    type Item=&'a str;
}

```

    
    */
    #[repr(C)]
    #[derive(StableAbi)]
    #[sabi(
        inside_abi_stable_crate,
        prefix_bound="I:InterfaceBound<'borr>",
        bound="<I as SharedStableAbi>::StaticEquivalent:InterfaceBound<'static>",
        bound="VTable<'borr,P,I>:SharedStableAbi",
        tag="<I as InterfaceBound<'borr>>::TAG",
    )]
    pub struct DynTrait<'borr,P,I> 
    where I:InterfaceBound<'borr>
    {
        pub(super) object: ManuallyDrop<P>,
        vtable: *const VTable<'borr,P,I>,
        _marker:PhantomData<extern fn()->Tuple2<I,RStr<'borr>>>,
        _marker2:UnsafeIgnoredType<Rc<()>>,

    }

    impl DynTrait<'static,&'static (),()> {
        /// Constructs the `DynTrait<_>` from a `T:ImplType`.
        ///
        /// Use this whenever possible instead of `from_any_value`,
        /// because it produces better error messages when unerasing the `DynTrait<_>`
        pub fn from_value<T>(object: T) -> DynTrait<'static,RBox<()>,T::Interface>
        where
            T: ImplType,
            T::Interface:InterfaceBound<'static>,
            T: GetVtable<'static,T,RBox<()>,RBox<T>,<T as ImplType>::Interface>,
        {
            let object = RBox::new(object);
            DynTrait::from_ptr(object)
        }

        /// Constructs the `DynTrait<_>` from a pointer to a `T:ImplType`.
        ///
        /// Use this whenever possible instead of `from_any_ptr`,
        /// because it produces better error messages when unerasing the `DynTrait<_>`
        pub fn from_ptr<P, T>(object: P) -> DynTrait<'static,P::TransmutedPtr,T::Interface>
        where
            T: ImplType,
            T::Interface:InterfaceBound<'static>,
            T: GetVtable<'static,T,P::TransmutedPtr,P,<T as ImplType>::Interface>,
            P: StableDeref<Target = T>+TransmuteElement<()>,
        {
            DynTrait {
                object: unsafe{
                    ManuallyDrop::new(object.transmute_element(<()>::T))
                },
                vtable: T::get_vtable(),
                _marker:PhantomData,
                _marker2:UnsafeIgnoredType::DEFAULT,
            }
        }

        /// Constructs the `DynTrait<_>` from a type that doesn't borrow anything.
        pub fn from_any_value<T,I>(object: T,interface:I) -> DynTrait<'static,RBox<()>,I>
        where
            T:'static,
            I:InterfaceBound<'static>,
            InterfaceFor<T,I,True> : GetVtable<'static,T,RBox<()>,RBox<T>,I>,
        {
            let object = RBox::new(object);
            DynTrait::from_any_ptr(object,interface)
        }

        /// Constructs the `DynTrait<_>` from a pointer to a 
        /// type that doesn't borrow anything.
        pub fn from_any_ptr<P, T,I>(
            object: P,
            _interface:I
        ) -> DynTrait<'static,P::TransmutedPtr,I>
        where
            I:InterfaceBound<'static>,
            T:'static,
            InterfaceFor<T,I,True>: GetVtable<'static,T,P::TransmutedPtr,P,I>,
            P: StableDeref<Target = T>+TransmuteElement<()>,
        {
            DynTrait {
                object: unsafe{
                    ManuallyDrop::new(object.transmute_element(<()>::T))
                },
                vtable: <InterfaceFor<T,I,True>>::get_vtable(),
                _marker:PhantomData,
                _marker2:UnsafeIgnoredType::DEFAULT,
            }
        }
        
        /// Constructs the `DynTrait<_>` from a value with a `'borr` borrow.
        ///
        /// Cannot unerase the DynTrait afterwards.
        pub fn from_borrowing_value<'borr,T,I>(
            object: T,
            interface:I,
        ) -> DynTrait<'borr,RBox<()>,I>
        where
            T:'borr,
            I:InterfaceBound<'borr>,
            InterfaceFor<T,I,False> : GetVtable<'borr,T,RBox<()>,RBox<T>,I>,
        {
            let object = RBox::new(object);
            DynTrait::from_borrowing_ptr(object,interface)
        }

        /// Constructs the `DynTrait<_>` from a pointer to the erased type
        /// with a `'borr` borrow.
        ///
        /// Cannot unerase the DynTrait afterwards.
        pub fn from_borrowing_ptr<'borr,P, T,I>(
            object: P,
            _interface:I
        ) -> DynTrait<'borr,P::TransmutedPtr,I>
        where
            T:'borr,
            I:InterfaceBound<'borr>,
            InterfaceFor<T,I,False>: GetVtable<'borr,T,P::TransmutedPtr,P,I>,
            P: StableDeref<Target = T>+TransmuteElement<()>,
        {
            DynTrait {
                object: unsafe{
                    ManuallyDrop::new(object.transmute_element(<()>::T))
                },
                vtable: <InterfaceFor<T,I,False>>::get_vtable(),
                _marker:PhantomData,
                _marker2:UnsafeIgnoredType::DEFAULT,
            }
        }
    }


    impl<P,I> DynTrait<'static,P,I> 
    where 
        I: InterfaceBound<'static>
    {
        /// Allows checking whether 2 `DynTrait<_>`s have a value of the same type.
        ///
        /// Notes:
        ///
        /// - Types from different dynamic libraries/executables are 
        /// never considered equal.
        ///
        /// - `DynTrait`s constructed using `DynTrait::from_borrowing_*`
        /// are never considered to wrap the same type.
        pub fn is_same_type<Other,I2>(&self,other:&DynTrait<'static,Other,I2>)->bool
        where I2:InterfaceBound<'static>
        {
            self.vtable_address()==other.vtable_address()||
            self.vtable().type_info().is_compatible(other.vtable().type_info())
        }
    }

    impl<'borr,P,I> DynTrait<'borr,P,I> 
    where 
        I: InterfaceBound<'borr>
    {
        pub(super) fn vtable<'a>(&self) -> &'a VTable<'borr,P,I>{
            unsafe {
                &*(((self.vtable as usize)&PTR_MASK) as *const VTable<'borr,P,I>)
            }
        }

        pub(super)fn vtable_address(&self) -> usize {
            (self.vtable as usize)&PTR_MASK
        }

        pub(super)fn vtable_ptr_flags(&self) -> usize {
            (self.vtable as usize)&PTR_FLAGS
        }

        pub(super) fn as_abi(&self) -> &ErasedObject
        where
            P: Deref,
        {
            self.object()
        }

        #[allow(dead_code)]
        pub(super) fn as_abi_mut(&mut self) -> &mut ErasedObject
        where
            P: DerefMut,
        {
            self.object_mut()
        }

        /// Returns the address of the wrapped object.
        ///
        /// This will not change between calls for the same `DynTrait<_>`.
        pub fn object_address(&self) -> usize
        where
            P: Deref,
        {
            self.object() as *const ErasedObject as usize
        }

        pub(super) fn object(&self) -> &ErasedObject
        where
            P: Deref,
        {
            unsafe { self.object_as() }
        }
        pub(super) fn object_mut(&mut self) -> &mut ErasedObject
        where
            P: DerefMut,
        {
            unsafe { self.object_as_mut() }
        }

        unsafe fn object_as<T>(&self) -> &T
        where
            P: Deref,
        {
            &*((&**self.object) as *const P::Target as *const T)
        }
        unsafe fn object_as_mut<T>(&mut self) -> &mut T
        where
            P: DerefMut,
        {
            &mut *((&mut **self.object) as *mut P::Target as *mut T)
        }
    }


    macro_rules! try_unerase {
        (
            $this:ident,$res:expr
        ) => (
            if let Err(e)=$res {
                return Err( e.map(move|_| $this ) );
            }
        )
    }


    impl<'borr,P,I> DynTrait<'borr,P,I> 
    where 
        I: InterfaceBound<'borr>
    {
        /// The uid in the vtable has to be the same as the one for T,
        /// otherwise it was not created from that T in the library that declared the opaque type.
        pub(super) fn check_same_destructor_opaque<A,T>(&self) -> Result<(), UneraseError<()>>
        where
            P: TransmuteElement<T>,
            A: GetVtable<'borr,T,P,P::TransmutedPtr,I>,
        {
            let t_vtable:&VTable<'borr,P,I> = A::get_vtable();
            if self.vtable_address() == t_vtable as *const _ as usize
                || self.vtable().type_info().is_compatible(t_vtable.type_info())
            {
                Ok(())
            } else {
                Err(UneraseError {
                    dyn_trait:(),
                    expected_vtable_address: t_vtable as *const _ as usize,
                    expected_type_info:t_vtable.type_info(),
                    found_vtable_address: self.vtable as usize,
                    found_type_info:self.vtable().type_info(),
                })
            }
        }

        /// Unwraps the `DynTrait<_>` into a pointer of 
        /// the concrete type that it was constructed with.
        ///
        /// T is required to implement ImplType.
        ///
        /// # Errors
        ///
        /// This will return an error in any of these conditions:
        ///
        /// - It is called in a dynamic library/binary outside
        /// the one from which this `DynTrait<_>` was constructed.
        ///
        /// - The DynTrait was constructed using a `from_borrowing_*` method
        ///
        /// - `T` is not the concrete type this `DynTrait<_>` was constructed with.
        ///
        pub fn into_unerased<T>(self) -> Result<P::TransmutedPtr, UneraseError<Self>>
        where
            P: TransmuteElement<T>,
            P::Target:Sized,
            T: ImplType + GetVtable<'borr,T,P,P::TransmutedPtr,I>,
        {
            try_unerase!(self,self.check_same_destructor_opaque::<T,T>());
            unsafe { 
                let this=ManuallyDrop::new(self);
                Ok(ptr::read(&*this.object).transmute_element(T::T)) 
            }
        }

        /// Unwraps the `DynTrait<_>` into a reference of 
        /// the concrete type that it was constructed with.
        ///
        /// T is required to implement ImplType.
        ///
        /// # Errors
        ///
        /// This will return an error in any of these conditions:
        ///
        /// - It is called in a dynamic library/binary outside
        /// the one from which this `DynTrait<_>` was constructed.
        ///
        /// - The DynTrait was constructed using a `from_borrowing_*` method
        ///
        /// - `T` is not the concrete type this `DynTrait<_>` was constructed with.
        ///
        pub fn as_unerased<T>(&self) -> Result<&T, UneraseError<&Self>>
        where
            P: Deref + TransmuteElement<T>,
            T: ImplType + GetVtable<'borr,T,P,P::TransmutedPtr,I>,
        {
            try_unerase!(self,self.check_same_destructor_opaque::<T,T>());
            unsafe { Ok(self.object_as()) }
        }

        /// Unwraps the `DynTrait<_>` into a mutable reference of 
        /// the concrete type that it was constructed with.
        ///
        /// T is required to implement ImplType.
        ///
        /// # Errors
        ///
        /// This will return an error in any of these conditions:
        ///
        /// - It is called in a dynamic library/binary outside
        /// the one from which this `DynTrait<_>` was constructed.
        ///
        /// - The DynTrait was constructed using a `from_borrowing_*` method
        ///
        /// - `T` is not the concrete type this `DynTrait<_>` was constructed with.
        ///
        pub fn as_unerased_mut<T>(&mut self) -> Result<&mut T, UneraseError<&mut Self>>
        where
            P: DerefMut + TransmuteElement<T>,
            T: ImplType + GetVtable<'borr,T,P,P::TransmutedPtr,I>,
        {
            try_unerase!(self,self.check_same_destructor_opaque::<T,T>());
            unsafe { Ok(self.object_as_mut()) }
        }


        /// Unwraps the `DynTrait<_>` into a pointer of 
        /// the concrete type that it was constructed with.
        ///
        /// T is required to not borrow anything.
        ///
        /// # Errors
        ///
        /// This will return an error in any of these conditions:
        ///
        /// - It is called in a dynamic library/binary outside
        /// the one from which this `DynTrait<_>` was constructed.
        ///
        /// - The DynTrait was constructed using a `from_borrowing_*` method
        ///
        /// - `T` is not the concrete type this `DynTrait<_>` was constructed with.
        ///
        pub fn into_any_unerased<T>(self) -> Result<P::TransmutedPtr, UneraseError<Self>>
        where
            T:'static,
            P: TransmuteElement<T>,
            P::Target:Sized,
            Self:DynTraitBound<'borr>,
            InterfaceFor<T,I,True>: GetVtable<'borr,T,P,P::TransmutedPtr,I>,
        {
            try_unerase!(self,self.check_same_destructor_opaque::<InterfaceFor<T,I,True>,T>());
            unsafe {
                unsafe { 
                    let this=ManuallyDrop::new(self);
                    Ok(ptr::read(&*this.object).transmute_element(T::T)) 
                }
            }
        }

        /// Unwraps the `DynTrait<_>` into a reference of 
        /// the concrete type that it was constructed with.
        ///
        /// T is required to not borrow anything.
        ///
        /// # Errors
        ///
        /// This will return an error in any of these conditions:
        ///
        /// - It is called in a dynamic library/binary outside
        /// the one from which this `DynTrait<_>` was constructed.
        ///
        /// - The DynTrait was constructed using a `from_borrowing_*` method
        ///
        /// - `T` is not the concrete type this `DynTrait<_>` was constructed with.
        ///
        pub fn as_any_unerased<T>(&self) -> Result<&T, UneraseError<&Self>>
        where
            T:'static,
            P: Deref + TransmuteElement<T>,
            Self:DynTraitBound<'borr>,
            InterfaceFor<T,I,True>: GetVtable<'borr,T,P,P::TransmutedPtr,I>,
        {
            try_unerase!(self,self.check_same_destructor_opaque::<InterfaceFor<T,I,True>,T>());
            unsafe { Ok(self.object_as()) }
        }

        /// Unwraps the `DynTrait<_>` into a mutable reference of 
        /// the concrete type that it was constructed with.
        ///
        /// T is required to not borrow anything.
        ///
        /// # Errors
        ///
        /// This will return an error in any of these conditions:
        ///
        /// - It is called in a dynamic library/binary outside
        /// the one from which this `DynTrait<_>` was constructed.
        ///
        /// - The DynTrait was constructed using a `from_borrowing_*` method
        ///
        /// - `T` is not the concrete type this `DynTrait<_>` was constructed with.
        ///
        pub fn as_any_unerased_mut<T>(&mut self) -> Result<&mut T, UneraseError<&mut Self>>
        where
            P: DerefMut + TransmuteElement<T>,
            Self:DynTraitBound<'borr>,
            InterfaceFor<T,I,True>: GetVtable<'borr,T,P,P::TransmutedPtr,I>,
        {
            try_unerase!(self,self.check_same_destructor_opaque::<InterfaceFor<T,I,True>,T>());
            unsafe { Ok(self.object_as_mut()) }
        }

    }


    mod private_struct {
        pub struct PrivStruct;
    }
    use self::private_struct::PrivStruct;

    
    /// This is used to make sure that reborrowing does not change 
    /// the Send-ness or Sync-ness of the pointer.
    pub trait ReborrowBounds<SendNess,SyncNess>{}

    // If it's reborrowing,it must have either both Sync+Send or neither.
    impl ReborrowBounds<False,False> for PrivStruct {}
    impl ReborrowBounds<True ,True > for PrivStruct {}

    
    impl<'borr,P,I> DynTrait<'borr,P,I> 
    where 
        I:InterfaceBound<'borr>
    {
        /// Creates a shared reborrow of this DynTrait.
        ///
        /// The reborrowed DynTrait cannot use these methods:
        /// 
        /// - DynTrait::default
        /// 
        pub fn reborrow<'re>(&'re self)->DynTrait<'borr,&'re (),I> 
        where
            P:Deref<Target=()>,
            PrivStruct:ReborrowBounds<I::Send,I::Sync>,
        {
            // Reborrowing will break if I add extra functions that operate on `P`.
            DynTrait {
                object: ManuallyDrop::new(&**self.object),
                vtable: ((self.vtable as usize) | PTR_FLAG_IS_BORROWED)as *const _,
                _marker:PhantomData,
                _marker2:UnsafeIgnoredType::DEFAULT,
            }
        }

        /// Creates a mutable reborrow of this DynTrait.
        ///
        /// The reborrowed DynTrait cannot use these methods:
        /// 
        /// - DynTrait::default
        /// 
        /// - DynTrait::clone
        /// 
        pub fn reborrow_mut<'re>(&'re mut self)->DynTrait<'borr,&'re mut (),I> 
        where
            P:DerefMut<Target=()>,
            PrivStruct:ReborrowBounds<I::Send,I::Sync>,
        {
            // Reborrowing will break if I add extra functions that operate on `P`.
            DynTrait {
                object: ManuallyDrop::new(&mut **self.object),
                vtable: ((self.vtable as usize) | PTR_FLAG_IS_BORROWED)as *const _,
                _marker:PhantomData,
                _marker2:UnsafeIgnoredType::DEFAULT,
            }
        }
    }


    impl<'borr,P,I> DynTrait<'borr,P,I> 
    where 
        I:InterfaceBound<'borr>+'borr
    {
        /// Constructs a DynTrait<P,I> with a `P`,using the same vtable.
        /// `P` must come from a function in the vtable,
        /// or come from a copy of `P:Copy+GetPointerKind<Kind=PK_Reference>`,
        /// to ensure that it is compatible with the functions in it.
        pub(super) fn from_new_ptr(&self, object: P) -> Self {
            Self {
                object:ManuallyDrop::new(object),
                vtable: self.vtable,
                _marker:PhantomData,
                _marker2:UnsafeIgnoredType::DEFAULT,
            }
        }

/**
Constructs a `DynTrait<P,I>` with the default value for `P`.

# Reborrowing

This cannot be called with a reborrowed DynTrait:

```compile_fail
# use abi_stable::{
#     DynTrait,
#     erased_types::interfaces::DefaultInterface,
# };
let object=DynTrait::from_any_value((),DefaultInterface);
let borrow=object.reborrow();
let _=borrow.default();

```

```compile_fail
# use abi_stable::{
#     DynTrait,
#     erased_types::interfaces::DefaultInterface,
# };
let object=DynTrait::from_any_value((),DefaultInterface);
let borrow=object.reborrow_mut();
let _=borrow.default();

```
 */
        pub fn default(&self) -> Self
        where
            P: Deref + GetPointerKind<Kind=PK_SmartPointer>,
            I: InterfaceType<Default = True>,
        {
            let new = self.vtable().default_ptr()();
            self.from_new_ptr(new)
        }

        /// It serializes a `DynTrait<_>` into a string by using 
        /// `<ConcreteType as SerializeImplType>::serialize_impl`.
        pub fn serialized<'a>(&'a self) -> Result<RCow<'a, str>, RBoxError>
        where
            P: Deref,
            I: InterfaceType<Serialize = True>,
        {
            self.vtable().serialize()(self.as_abi()).into_result()
        }

        /// Deserializes a string into a `DynTrait<_>`,by using 
        /// `<I as DeserializeOwnedInterface>::deserialize_impl`.
        pub fn deserialize_owned_from_str(s: &str) -> Result<Self, RBoxError>
        where
            P: 'borr+Deref,
            I: DeserializeOwnedInterface<'borr,Deserialize = True, Deserialized = Self>,
        {
            s.piped(RStr::from).piped(I::deserialize_impl)
        }

        /// Deserializes a `&'borr str` into a `DynTrait<'borr,_>`,by using 
        /// `<I as DeserializeBorrowedInterface<'borr>>::deserialize_impl`.
        pub fn deserialize_borrowing_from_str(s: &'borr str) -> Result<Self, RBoxError>
        where
            P: 'borr+Deref,
            I: DeserializeBorrowedInterface<'borr,Deserialize = True, Deserialized = Self>,
        {
            s.piped(RStr::from).piped(I::deserialize_impl)
        }
    }

    impl<'borr,P,I> Drop for DynTrait<'borr,P,I>
    where I:InterfaceBound<'borr>
    {
        fn drop(&mut self){
            unsafe{
                let vtable=self.vtable();

                if (self.vtable_ptr_flags()&PTR_FLAG_IS_BORROWED)==PTR_FLAG_IS_BORROWED {
                    // Do nothing
                }else{
                    vtable.drop_ptr()(&mut *self.object);
                }
            }
        }
    }

}


const PTR_FLAGS:usize=0b1111;
const PTR_MASK:usize=!PTR_FLAGS;
const PTR_FLAG_IS_BORROWED:usize=0b_0001;


pub use self::priv_::DynTrait;

//////////////////////



mod clone_impl{
    pub trait CloneImpl<PtrKind>{
        fn clone_impl(&self) -> Self;
    }
}
use self::clone_impl::CloneImpl;


/// This impl is for smart pointers.
impl<'borr,P, I> CloneImpl<PK_SmartPointer> for DynTrait<'borr,P,I>
where
    P: Deref,
    I: InterfaceBound<'borr,Clone = True>+'borr,
{
    fn clone_impl(&self) -> Self {
        let vtable = self.vtable();
        let new = vtable.clone_ptr()(&*self.object);
        self.from_new_ptr(new)
    }
}

/// This impl is for references.
impl<'borr,P, I> CloneImpl<PK_Reference> for DynTrait<'borr,P,I>
where
    P: Deref+Copy,
    I: InterfaceBound<'borr,Clone = True>+'borr,
{
    fn clone_impl(&self) -> Self {
        self.from_new_ptr(*self.object)
    }
}


/**
Clone is implemented for references and smart pointers,
using `GetPointerKind` to decide whether `P` is a smart pointer or a reference.

DynTrait does not implement Clone if P==`&mut ()` :

```compile_fail
# use abi_stable::{
#     DynTrait,
#     erased_types::interfaces::CloneInterface,
# };

let object=DynTrait::from_any_value((),());
let borrow=object.reborrow_mut();
let _=borrow.clone();

```

*/
impl<'borr,P, I> Clone for DynTrait<'borr,P,I>
where
    P: Deref+GetPointerKind,
    I: InterfaceBound<'borr>,
    Self:CloneImpl<<P as GetPointerKind>::Kind>,
{
    fn clone(&self) -> Self {
        self.clone_impl()
    }
}

//////////////////////


impl<'borr,P, I> Display for DynTrait<'borr,P,I>
where
    P: Deref,
    I: InterfaceBound<'borr,Display = True>,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        adapt_std_fmt::<ErasedObject>(self.object(), self.vtable().display(), f)
    }
}

impl<'borr,P, I> Debug for DynTrait<'borr,P,I>
where
    P: Deref,
    I: InterfaceBound<'borr,Debug = True>,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        adapt_std_fmt::<ErasedObject>(self.object(), self.vtable().debug(), f)
    }
}

/**
First it serializes a `DynTrait<_>` into a string by using 
<ConcreteType as SerializeImplType>::serialize_impl,
then it serializes the string.

*/
/// ,then it .
impl<'borr,P, I> Serialize for DynTrait<'borr,P,I>
where
    P: Deref,
    I: InterfaceBound<'borr,Serialize = True>,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.vtable().serialize()(self.as_abi())
            .into_result()
            .map_err(ser::Error::custom)?
            .serialize(serializer)
    }
}

/// First it Deserializes a string,then it deserializes into a 
/// `DynTrait<_>`,by using `<I as DeserializeOwnedInterface>::deserialize_impl`.
impl<'de,'borr:'de, P, I> Deserialize<'de> for DynTrait<'borr,P,I>
where
    P: Deref+'borr,
    I: InterfaceBound<'borr>+'borr,
    I: DeserializeOwnedInterface<'borr,Deserialize = True, Deserialized = Self>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        I::deserialize_impl(RStr::from(&*s)).map_err(de::Error::custom)
    }
}

impl<P, I> Eq for DynTrait<'static,P,I>
where
    Self: PartialEq,
    P: Deref,
    I: InterfaceBound<'static,Eq = True>,
{
}

impl<P, P2, I> PartialEq<DynTrait<'static,P2,I>> for DynTrait<'static,P,I>
where
    P: Deref,
    P2: Deref,
    I: InterfaceBound<'static,PartialEq = True>,
{
    fn eq(&self, other: &DynTrait<'static,P2,I>) -> bool {
        // unsafe: must check that the vtable is the same,otherwise return a sensible value.
        if !self.is_same_type(other) {
            return false;
        }

        self.vtable().partial_eq()(self.as_abi(), other.as_abi())
    }
}

impl<P, I> Ord for DynTrait<'static,P,I>
where
    P: Deref,
    I: InterfaceBound<'static,Ord = True>,
    Self: PartialOrd + Eq,
{
    fn cmp(&self, other: &Self) -> Ordering {
        // unsafe: must check that the vtable is the same,otherwise return a sensible value.
        if !self.is_same_type(other) {
            return self.vtable_address().cmp(&other.vtable_address());
        }

        self.vtable().cmp()(self.as_abi(), other.as_abi()).into()
    }
}

impl<P, P2, I> PartialOrd<DynTrait<'static,P2,I>> for DynTrait<'static,P,I>
where
    P: Deref,
    P2: Deref,
    I: InterfaceBound<'static,PartialOrd = True>,
    Self: PartialEq<DynTrait<'static,P2,I>>,
{
    fn partial_cmp(&self, other: &DynTrait<'static,P2,I>) -> Option<Ordering> {
        // unsafe: must check that the vtable is the same,otherwise return a sensible value.
        if !self.is_same_type(other) {
            return Some(self.vtable_address().cmp(&other.vtable_address()));
        }

        self.vtable().partial_cmp()(self.as_abi(), other.as_abi())
            .map(IntoReprRust::into_rust)
            .into()
    }
}

impl<'borr,P, I> Hash for DynTrait<'borr,P,I>
where
    P: Deref,
    I: InterfaceBound<'borr,Hash = True>,
{
    fn hash<H>(&self, state: &mut H)
    where
        H: Hasher,
    {
        self.vtable().hash()(self.as_abi(), HasherObject::new(state))
    }
}


//////////////////////////////////////////////////////////////////


impl<'borr,P, I,Item> Iterator for DynTrait<'borr,P,I>
where
    P: DerefMut,
    I: InterfaceBound<'borr,Iterator = True,IteratorItem=Item>,
{
    type Item=Item;

    fn next(&mut self)->Option<Item>{
        let vtable=self.vtable();
        (vtable.iter().next)(self.as_abi_mut()).into_rust()
    }

    fn nth(&mut self,nth:usize)->Option<Item>{
        let vtable=self.vtable();
        (vtable.iter().nth)(self.as_abi_mut(),nth).into_rust()
    }

    fn size_hint(&self)->(usize,Option<usize>){
        let vtable=self.vtable();
        let tuple=(vtable.iter().size_hint)(self.as_abi()).into_rust();
        (tuple.0,tuple.1.into_rust())
    }

    fn count(mut self)->usize{
        let vtable=self.vtable();
        (vtable.iter().count)(self.as_abi_mut())
    }

    fn last(mut self)->Option<Item>{
        let vtable=self.vtable();
        (vtable.iter().last)(self.as_abi_mut()).into_rust()
    }
}


impl<'borr,P, I,Item> DynTrait<'borr,P,I>
where
    P: DerefMut,
    I: InterfaceBound<'borr,Iterator = True,IteratorItem=Item>,
{
/**
Eagerly skips n elements from the iterator.

This method is faster than using `Iterator::skip`.

# Example

```
# use abi_stable::{
#     DynTrait,
#     erased_types::interfaces::IteratorInterface,
#     std_types::RVec,
#     traits::IntoReprC,
# };

let mut iter=0..20;
let mut wrapped=DynTrait::from_any_ptr(&mut iter,IteratorInterface::NEW);

assert_eq!(wrapped.next(),Some(0));

wrapped.skip_eager(2);

assert_eq!(wrapped.next(),Some(3));
assert_eq!(wrapped.next(),Some(4));
assert_eq!(wrapped.next(),Some(5));

wrapped.skip_eager(2);

assert_eq!(wrapped.next(),Some(8));
assert_eq!(wrapped.next(),Some(9));

wrapped.skip_eager(9);

assert_eq!(wrapped.next(),Some(19));
assert_eq!(wrapped.next(),None    );



```


*/
    pub fn skip_eager(&mut self, n: usize){
        let vtable=self.vtable();
        (vtable.iter().skip_eager)(self.as_abi_mut(),n);
    }


/**
Extends the `RVec<Item>` with the `self` Iterator.

Extends `buffer` with as many elements of the iterator as `taking` specifies:

- RNone: Yields all elements.Use this with care,since Iterators can be infinite.

- RSome(n): Yields n elements.

### Example

```
# use abi_stable::{
#     DynTrait,
#     erased_types::interfaces::IteratorInterface,
#     std_types::{RVec,RSome},
#     traits::IntoReprC,
# };

let mut wrapped=DynTrait::from_any_value(0.. ,IteratorInterface::NEW);

let mut buffer=vec![ 101,102,103 ].into_c();
wrapped.extending_rvec(&mut buffer,RSome(5));
assert_eq!(
    &buffer[..],
    &*vec![101,102,103,0,1,2,3,4]
);

assert_eq!( wrapped.next(),Some(5));
assert_eq!( wrapped.next(),Some(6));
assert_eq!( wrapped.next(),Some(7));

```
*/
    pub fn extending_rvec(&mut self,buffer:&mut RVec<Item>,taking:ROption<usize>){
        let vtable=self.vtable();
        (vtable.iter().extending_rvec)(self.as_abi_mut(),buffer,taking);
    }
}


//////////////////////////////////////////////////////////////////


impl<'borr,P, I,Item> DoubleEndedIterator for DynTrait<'borr,P,I>
where
    Self:Iterator<Item=Item>,
    P: DerefMut,
    I: InterfaceBound<'borr,DoubleEndedIterator = True,IteratorItem=Item>,
{

    fn next_back(&mut self)->Option<Item>{
        let vtable=self.vtable();
        (vtable.back_iter().next_back)(self.as_abi_mut()).into_rust()
    }
}


impl<'borr,P, I,Item> DynTrait<'borr,P,I>
where
    Self:Iterator<Item=Item>,
    P: DerefMut,
    I: InterfaceBound<'borr,DoubleEndedIterator = True,IteratorItem=Item>,
{
    pub fn nth_back_(&mut self,nth:usize)->Option<Item>{
        let vtable=self.vtable();
        (vtable.back_iter().nth_back)(self.as_abi_mut(),nth).into_rust()
    }

/**
Extends the `RVec<Item>` with the back of the `self` DoubleEndedIterator.

Extends `buffer` with as many elements of the iterator as `taking` specifies:

- RNone: Yields all elements.Use this with care,since Iterators can be infinite.

- RSome(n): Yields n elements.

### Example

```
# use abi_stable::{
#     DynTrait,
#     erased_types::interfaces::DEIteratorInterface,
#     std_types::{RVec,RNone},
#     traits::IntoReprC,
# };

let mut wrapped=DynTrait::from_any_value(0..=3 ,DEIteratorInterface::NEW);

let mut buffer=vec![ 101,102,103 ].into_c();
wrapped.extending_rvec_back(&mut buffer,RNone);
assert_eq!(
    &buffer[..],
    &*vec![101,102,103,3,2,1,0]
)

```

*/
    pub fn extending_rvec_back(&mut self,buffer:&mut RVec<Item>,taking:ROption<usize>){
        let vtable=self.vtable();
        (vtable.back_iter().extending_rvec_back)(self.as_abi_mut(),buffer,taking);
    }
}


//////////////////////////////////////////////////////////////////


impl<'borr,P,I> fmtWrite for DynTrait<'borr,P,I>
where
    P: DerefMut,
    I: InterfaceBound<'borr,FmtWrite = True>,
{
    fn write_str(&mut self, s: &str) -> Result<(), fmt::Error>{
        let vtable = self.vtable();
        match vtable.fmt_write_str()(self.as_abi_mut(),s.into()) {
            ROk(_)=>Ok(()),
            RErr(_)=>Err(fmt::Error),
        }
    }
}



//////////////////////////////////////////////////////////////////


#[inline]
fn to_io_result<T,U>(res:RResult<T,RIoError>)->io::Result<U>
where
    T:Into<U>
{
    match res {
        ROk(v)=>Ok(v.into()),
        RErr(e)=>Err(e.into()),
    }
}


/////////////


impl<'borr,P,I> io::Write for DynTrait<'borr,P,I>
where
    P: DerefMut,
    I: InterfaceBound<'borr,IoWrite = True>,
{
    fn write(&mut self, buf: &[u8]) -> io::Result<usize>{
        let vtable = self.vtable().io_write();

        to_io_result((vtable.write)(self.as_abi_mut(),buf.into()))
    }
    fn flush(&mut self) -> io::Result<()>{
        let vtable = self.vtable().io_write();

        to_io_result((vtable.flush)(self.as_abi_mut()))
    }
    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
        let vtable = self.vtable().io_write();

        to_io_result((vtable.write_all)(self.as_abi_mut(),buf.into()))
    }
}


/////////////


impl<'borr,P,I> io::Read for DynTrait<'borr,P,I>
where
    P: DerefMut,
    I: InterfaceBound<'borr,IoRead = True>,
{
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>{
        let vtable = self.vtable().io_read();

        to_io_result((vtable.read)(self.as_abi_mut(),buf.into()))
    }

    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
        let vtable = self.vtable().io_read();

        to_io_result((vtable.read_exact)(self.as_abi_mut(),buf.into()))
    }

}


/////////////


impl<'borr,P,I> io::BufRead for DynTrait<'borr,P,I>
where
    P: DerefMut,
    I: InterfaceBound<'borr,IoRead = True,IoBufRead = True>,
{
    fn fill_buf(&mut self) -> io::Result<&[u8]>{
        let vtable = self.vtable().io_bufread();

        to_io_result((vtable.fill_buf)(self.as_abi_mut()))
    }

    fn consume(&mut self, ammount:usize ){
        let vtable = self.vtable().io_bufread();

        (vtable.consume)(self.as_abi_mut(),ammount)
    }

}

/////////////


impl<'borr,P,I> io::Seek for DynTrait<'borr,P,I>
where
    P: DerefMut,
    I: InterfaceBound<'borr,IoSeek = True>,
{
    fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64>{
        let vtable = self.vtable();

        to_io_result(vtable.io_seek()(self.as_abi_mut(),pos.into()))
    }
}


//////////////////////////////////////////////////////////////////

unsafe impl<'borr,P,I> Send for DynTrait<'borr,P,I>
where
    P: Send,
    I: InterfaceBound<'borr,Send = True>,
{}


unsafe impl<'borr,P,I> Sync for DynTrait<'borr,P,I>
where
    P: Sync,
    I: InterfaceBound<'borr,Sync = True>,
{}


//////////////////////////////////////////////////////////////////

mod sealed {
    use super::*;
    pub trait Sealed {}
    impl<'borr,P,I> Sealed for DynTrait<'borr,P,I> 
    where I:InterfaceBound<'borr>
    {}
}
use self::sealed::Sealed;

/// For accessing the Interface of a `DynTrait<Pointer<()>,Interface>`.
pub trait DynTraitBound<'borr>: Sealed {
    type Interface: InterfaceType;
}

impl<'borr,P, I> DynTraitBound<'borr> for DynTrait<'borr,P,I>
where
    P: Deref,
    I: InterfaceBound<'borr>,
{
    type Interface = I;
}


/// For accessing the `Interface` in a `DynTrait<Pointer<()>,Interface>`.
pub type GetVWInterface<'borr,This>=
    <This as DynTraitBound<'borr>>::Interface;


//////////////////////////////////////////////////////////////////

/// Error for `DynTrait<_>` being unerased into the wrong type
/// with one of the `*unerased*` methods.
#[derive(Copy, Clone)]
pub struct UneraseError<T> {
    dyn_trait:T,
    expected_vtable_address: usize,
    expected_type_info:&'static TypeInfo,
    found_vtable_address: usize,
    found_type_info:&'static TypeInfo,
}


impl<T> UneraseError<T>{
    fn map<F,U>(self,f:F)->UneraseError<U>
    where F:FnOnce(T)->U
    {
        UneraseError{
            dyn_trait              :f(self.dyn_trait),
            expected_vtable_address:self.expected_vtable_address,
            expected_type_info     :self.expected_type_info,
            found_vtable_address   :self.found_vtable_address,
            found_type_info        :self.found_type_info,
        }
    }

    /// Extracts the DynTrait,to handle the failure to unerase it.
    #[must_use]
    pub fn into_inner(self)->T{
        self.dyn_trait
    }
}


impl<D> fmt::Debug for UneraseError<D>{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("UneraseError")
            .field("dyn_trait",&"<not shown>")
            .field("expected_vtable_address",&self.expected_vtable_address)
            .field("expected_type_info",&self.expected_type_info)
            .field("found_vtable_address",&self.found_vtable_address)
            .field("found_type_info",&self.found_type_info)
            .finish()
    }
}

impl<D> fmt::Display for UneraseError<D>{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

impl<D> ::std::error::Error for UneraseError<D> {}

//////////////////////////////////////////////////////////////////