mirror of
https://github.com/pezkuwichain/serde.git
synced 2026-04-23 04:48:01 +00:00
Compare commits
1182 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 964a2dd4d1 | |||
| 8a21bbc720 | |||
| 4dba260ad7 | |||
| 1d3044fa28 | |||
| d1f0112bfb | |||
| 3f25cd9a7e | |||
| 45a36f1219 | |||
| 529a1cfedb | |||
| 219abd2e00 | |||
| 4bd10528a0 | |||
| b82bba2d0a | |||
| 17c175a1a6 | |||
| 763ab9c2a1 | |||
| 30b8036efa | |||
| 89bb16da6b | |||
| d00a895902 | |||
| 393b19ee8a | |||
| e68888d475 | |||
| d1306a78ec | |||
| ce230adf12 | |||
| 066c9a15cf | |||
| 6277079152 | |||
| d60fd84b7e | |||
| 02e6c04e9f | |||
| 9f04b9d6e7 | |||
| d298da0b4f | |||
| ff21d557c7 | |||
| faaa494579 | |||
| 661cdf4e00 | |||
| a55d812441 | |||
| b7ca574bb3 | |||
| d960571439 | |||
| 1ccc58e2aa | |||
| 34b39083bc | |||
| 48f4deac55 | |||
| 9a0f05d00d | |||
| b47e1a6dc3 | |||
| 39c7797633 | |||
| 368784949e | |||
| 74cf80989d | |||
| f0b4735781 | |||
| 297f373548 | |||
| 81f28da8e1 | |||
| d4bb687032 | |||
| f9bc5037f5 | |||
| 8624ca6f1d | |||
| a9b5cc4830 | |||
| c31f76321c | |||
| f2402dcf52 | |||
| 361402ac4d | |||
| c52e131a03 | |||
| c0a06bdc96 | |||
| dd13fd3a34 | |||
| 91f628727b | |||
| 571a2e4e2d | |||
| 7edcf6ec3b | |||
| e4f7d8513c | |||
| 09c69da909 | |||
| 7ee175f448 | |||
| 70ab3cdd61 | |||
| 8fb554e593 | |||
| 7a2bfdc1dd | |||
| 9046e9d7a1 | |||
| 87040b4bc4 | |||
| 68aab2424f | |||
| 9b9b697eb1 | |||
| db449c4bf2 | |||
| 948aa47687 | |||
| 3e1e42ef9b | |||
| dbdfe4f306 | |||
| e0d6b9d010 | |||
| a5b8e806f8 | |||
| d7dadd83b6 | |||
| 7612fd8e82 | |||
| 4c77af53e5 | |||
| 5d9c1aeb06 | |||
| 59e48997dd | |||
| ffcd97834f | |||
| e0c049dbf2 | |||
| 8cb6607e82 | |||
| 1ffb0570b6 | |||
| 2c1dd60575 | |||
| 24f849da2d | |||
| a5024a4238 | |||
| b105423e5e | |||
| 42c1bc2907 | |||
| c334c1c7b5 | |||
| 92668d7061 | |||
| b9d865d8e7 | |||
| fc4e370ba9 | |||
| a982d27536 | |||
| dc87826298 | |||
| a09a8a039a | |||
| ea702755a2 | |||
| d161911c63 | |||
| e27553d3df | |||
| 48eaf988bc | |||
| 73a364d4fd | |||
| 6dfdcb6ba1 | |||
| 089c7eb1d7 | |||
| 1e05fc2145 | |||
| 977612d8dd | |||
| 5855078703 | |||
| 3c88a93fb2 | |||
| 530c29466e | |||
| ea99e8b686 | |||
| 2a148112d4 | |||
| a4126e4c5a | |||
| d1325862f7 | |||
| 1f65ce75ec | |||
| 9536e52aa6 | |||
| be0c755731 | |||
| 42bc63bed8 | |||
| e41b940a3d | |||
| 88149fc0c3 | |||
| 5ecfb3b388 | |||
| 13a9f929de | |||
| e40fbe0767 | |||
| 0a10116bf5 | |||
| b1fbbfd3ce | |||
| 984ebcead0 | |||
| aa88f01cdc | |||
| 13794c1b48 | |||
| b5e64abba1 | |||
| 503ce310f5 | |||
| b26f291d93 | |||
| bc6bc9e3f0 | |||
| 3a52364f3e | |||
| 4d1627fc96 | |||
| 7c04bf36d9 | |||
| 4b06030666 | |||
| a5a04306f2 | |||
| f9885c4826 | |||
| 04f25eb122 | |||
| 2fea5f3e1c | |||
| 905b2c3cf3 | |||
| d5b428a087 | |||
| b3b8056d93 | |||
| 137cf9bab8 | |||
| 7372f152bd | |||
| a43da15b74 | |||
| 212cbbd8bf | |||
| 738aa31733 | |||
| 787ecc6a82 | |||
| 9fc8a86bcc | |||
| 800442a75e | |||
| 88debb3fb8 | |||
| 88a4ed9cd7 | |||
| bdba6fc5b0 | |||
| dec116311e | |||
| 8c49e6d6a5 | |||
| 7cc24a43fb | |||
| c008c6d3a8 | |||
| c9f5d08ed1 | |||
| fff6c9cb66 | |||
| cb5e7c6264 | |||
| 4ef1128546 | |||
| 227bea1d0b | |||
| 766ede965e | |||
| eb5a49e380 | |||
| 2df529cac5 | |||
| 4b66463011 | |||
| b907cfef85 | |||
| 506c8cc087 | |||
| 3951ef91c0 | |||
| b0d20afdfb | |||
| 5e6ee523d2 | |||
| a07b6bd9e7 | |||
| 8dd06eed2f | |||
| 5b668ed87a | |||
| abe305dbfe | |||
| 2d1a60c056 | |||
| 5edfdba940 | |||
| 756bff534f | |||
| 110d36fa14 | |||
| 8c576fe9fb | |||
| b860d3cb1f | |||
| dced4416a7 | |||
| ca47eb929c | |||
| b01c23b5ee | |||
| 3aaf29c846 | |||
| d2eea87001 | |||
| 8242c64152 | |||
| 9e45bd8c87 | |||
| 405b534254 | |||
| d34be74dfd | |||
| c475df8320 | |||
| 2b8a620807 | |||
| 1cd6aee562 | |||
| 90d4d7b37b | |||
| 1f8b803607 | |||
| 516cc8b04e | |||
| 0676477cd7 | |||
| 4193122472 | |||
| eb6fb1d40e | |||
| bf873a7b3f | |||
| fbd4a17467 | |||
| ad34c14c8c | |||
| e461a23798 | |||
| 894a21bc1f | |||
| 1ecf3730ee | |||
| 7a0e8f73b4 | |||
| b6e8b58cb2 | |||
| a3f556959f | |||
| 9338c4f1b9 | |||
| 28d67f4172 | |||
| 2401ae61a8 | |||
| 57d3fce0c6 | |||
| a020cceed8 | |||
| 49e985eb90 | |||
| 63def96c66 | |||
| 2fea8c9c28 | |||
| b7ea213926 | |||
| 871fb5adee | |||
| 2c984980a0 | |||
| 36f07912b8 | |||
| 7222cf7514 | |||
| 08c59a2e0e | |||
| 4a0bf4de65 | |||
| 95ffca9bbe | |||
| 5e47c87ba0 | |||
| c6d5d9be14 | |||
| d63d09f4db | |||
| de6d00c306 | |||
| 5bda95ba81 | |||
| 36641e7b81 | |||
| 6eca34c45c | |||
| 7efa0153b0 | |||
| 8dba87661b | |||
| 17fb4cb503 | |||
| 5bd0386b8e | |||
| 8b484c9703 | |||
| a16f07858b | |||
| 133d117bf4 | |||
| e7f3a80867 | |||
| f8c3d225a3 | |||
| 6d40d9e8ec | |||
| c91fca19e1 | |||
| f13a805530 | |||
| 54802983b8 | |||
| f430d9d1c8 | |||
| c9612a2f57 | |||
| 7ffea5a716 | |||
| c8c9f7d96c | |||
| f75d286b90 | |||
| 9acb17ab54 | |||
| f15ff1868e | |||
| 86f0d0382f | |||
| 8595b25763 | |||
| 49aca521f1 | |||
| 4c38bd0180 | |||
| 02c4ff7b7e | |||
| a8d1c0253a | |||
| bb5370b746 | |||
| 536e78a146 | |||
| 21c9446890 | |||
| 1b42f3f594 | |||
| cafa02d9b4 | |||
| a9b6cbb8b3 | |||
| 1d719b542c | |||
| 532b950971 | |||
| f93b4e91e6 | |||
| 94e2ccc94e | |||
| cbe6b4c97c | |||
| a46a4e27dd | |||
| 4919a3184d | |||
| 0b19608d85 | |||
| 99bddddd8e | |||
| 85c95040b3 | |||
| 339c0f5493 | |||
| b4d5c26f4e | |||
| f4e1ffa2cb | |||
| ef5d09e144 | |||
| e547a06639 | |||
| c61b20cceb | |||
| 42987a5b24 | |||
| 3f28a93240 | |||
| 9970084550 | |||
| 3920993370 | |||
| 22690cedc2 | |||
| b27039d34d | |||
| 1b6fd5a362 | |||
| 8b7b886036 | |||
| 2a2c098eeb | |||
| f68f32d3ee | |||
| 6ccb6c9130 | |||
| 49d24a1377 | |||
| b0eee50947 | |||
| 554b81d636 | |||
| 9fe16767c5 | |||
| 3a3777a2fb | |||
| effa298871 | |||
| 9a86e6818f | |||
| 7d09b1475c | |||
| 7e441e5110 | |||
| 40b874214a | |||
| 0c18c151e2 | |||
| 4ad6c4fd56 | |||
| 8ee8c07090 | |||
| 8e77960e3a | |||
| 819d47fea2 | |||
| 8e865f62c4 | |||
| 6cbf0d32da | |||
| 20afa85087 | |||
| da6d967776 | |||
| f47a50e996 | |||
| 1eca7766ba | |||
| 51f95575ec | |||
| 429de89276 | |||
| a69b82c7c5 | |||
| 55e5f19437 | |||
| c34baa1e5f | |||
| 7cc36a9cd3 | |||
| d343017f47 | |||
| 2212bfbf2c | |||
| e85ca8411e | |||
| 1ff2053262 | |||
| bf779ea343 | |||
| 8fe66c7f2a | |||
| e03dedabe4 | |||
| 08bc2d2e76 | |||
| 35be61d85f | |||
| 3692edfd08 | |||
| 5a258ade27 | |||
| f3052c392e | |||
| d1ce4d62c9 | |||
| 869ebd9e4e | |||
| 14446af537 | |||
| 248d937f9a | |||
| ffa2f80186 | |||
| ac1128a647 | |||
| 88d845c4d1 | |||
| 87a402a751 | |||
| cdb0e6c899 | |||
| 54cee86fd3 | |||
| 178edd1abc | |||
| 4bb9279074 | |||
| 3c45e5c7a5 | |||
| d36f28971c | |||
| d914fdf67b | |||
| 7014c105b4 | |||
| f3d566af09 | |||
| 278e8eb720 | |||
| e9b04de9a5 | |||
| 2a2891d54b | |||
| 85f1bf0259 | |||
| 123e040189 | |||
| 6f0f273d9c | |||
| fb7ba225d1 | |||
| d690ffda8d | |||
| 18a775277f | |||
| fbb250766d | |||
| 71116b860a | |||
| ce3f134145 | |||
| 80507d650c | |||
| 0ae61a3dd1 | |||
| 5fb73073bd | |||
| 63d484d50c | |||
| f3f29f81bc | |||
| 621588b258 | |||
| 7aba920dec | |||
| a732b9bad3 | |||
| 6723da67b3 | |||
| 2d99a50c27 | |||
| 01f6115d73 | |||
| a4eb9d5788 | |||
| 6f77ea58fd | |||
| 2cb55e8cb9 | |||
| 671f5ebd07 | |||
| 2bc1d62e50 | |||
| 1796536962 | |||
| dba1377d1f | |||
| ce66b230e3 | |||
| affc81b1d6 | |||
| c3ec05f410 | |||
| 332d59f362 | |||
| d98172f330 | |||
| e0c9bd4b87 | |||
| 33d26c6d38 | |||
| 0557a7feac | |||
| d46db730ff | |||
| 07b1acc9f5 | |||
| 85864e6ccb | |||
| 1f31bb2db9 | |||
| 6b5bd24edd | |||
| 8c2359f9c3 | |||
| f59ec44a0b | |||
| b7446db511 | |||
| 8bd7acc9fc | |||
| d120539310 | |||
| 82098f4e49 | |||
| 1c55f58093 | |||
| df3c3cb555 | |||
| c539563687 | |||
| 69de46f9e0 | |||
| d5102a7afd | |||
| c4b5a42615 | |||
| d0502b93ef | |||
| b289edd4a4 | |||
| 3a687e5369 | |||
| 8c30ec9698 | |||
| e40b9e9814 | |||
| 22d0bdae8a | |||
| 84fa3fba58 | |||
| 85001608e0 | |||
| 09fe2dbba5 | |||
| b6ed82dd7d | |||
| 5bbeedadf2 | |||
| d786de6696 | |||
| 5d24d6cfb4 | |||
| c8c22c036f | |||
| b7f30d7f82 | |||
| 4bf5a15d7e | |||
| f394f25956 | |||
| 9d96f95ddd | |||
| f12f640590 | |||
| d02e959b3f | |||
| ea833d3427 | |||
| 78e74886be | |||
| 061a1d8a8c | |||
| de9fd3b04e | |||
| e36f33589c | |||
| a892a13473 | |||
| 556d5bdc27 | |||
| c6acec29e5 | |||
| dce02c624b | |||
| 77e56613a5 | |||
| 3b7fa47b2e | |||
| f5fd7f5950 | |||
| fb6fc4e19f | |||
| 85772726ee | |||
| f05ba9fdf2 | |||
| 2e829ae4e6 | |||
| 25a5dd1579 | |||
| 1831b471f9 | |||
| 49ff56aa15 | |||
| 89549e2567 | |||
| 124bacd871 | |||
| 4280dd466d | |||
| 65eb116a85 | |||
| e15940f355 | |||
| 68440952ab | |||
| d751b4c39a | |||
| d10a69b243 | |||
| 1a1b6fbf85 | |||
| 93968455f3 | |||
| 4722571a4d | |||
| 36a7bf6244 | |||
| 89f0ad99a6 | |||
| 05ad8662e2 | |||
| 15c09a8d2c | |||
| 80a27cbb4a | |||
| 13e1a129dd | |||
| 334a6e788a | |||
| fa51083a12 | |||
| aaca4f06c6 | |||
| cc8a5a79ab | |||
| 4f79829849 | |||
| 6c18896cf5 | |||
| ac738632ef | |||
| 8d06f36d71 | |||
| e404de85b2 | |||
| 6fe01bc8e3 | |||
| 855f3d99bb | |||
| 9d015a2942 | |||
| 42c41922ce | |||
| 984181c558 | |||
| ed603d4580 | |||
| 70c83768b7 | |||
| 7220029055 | |||
| 35676305da | |||
| fbad194042 | |||
| 2e4cc0b443 | |||
| 9217517532 | |||
| 0feeb7a341 | |||
| 2901344722 | |||
| 54c80ad677 | |||
| 16ba32dbe1 | |||
| 60938913b2 | |||
| 26528fbbb4 | |||
| 6adcaa55e5 | |||
| fb575225bc | |||
| ee4e7413b0 | |||
| a6f8bd5aac | |||
| 3766633f4a | |||
| 99038b044e | |||
| 4ec0a7e672 | |||
| a41dae45a5 | |||
| cb9e1cfb54 | |||
| 54ce7f2e90 | |||
| ddbd139793 | |||
| a070de28e2 | |||
| 57aeb26728 | |||
| a592828808 | |||
| 67d86dcc4f | |||
| 15764cb955 | |||
| 97bc1e08e7 | |||
| 7ffb74f5bb | |||
| f25e6d3ea9 | |||
| 431cbe48b7 | |||
| 5405ab319d | |||
| 0f9a930c4f | |||
| 1a449bb3d0 | |||
| c0e8164792 | |||
| a3a7e4085f | |||
| 149c87d7c2 | |||
| 5deba439c3 | |||
| d450de1482 | |||
| 47c7387279 | |||
| dc8d209f29 | |||
| 831802adc8 | |||
| 2d5a26dfc0 | |||
| c6b6e2a5d9 | |||
| d1be5ef187 | |||
| f531be1524 | |||
| 10b1508d4a | |||
| 041d5c0842 | |||
| 7d09053bb8 | |||
| 8e87926bc2 | |||
| d6a462b862 | |||
| cfc2f9adc0 | |||
| 00f94290a6 | |||
| 093201abfb | |||
| 6d64104375 | |||
| fb0e62951f | |||
| 6ab508a93c | |||
| 9f38c2ab59 | |||
| 021ce5be88 | |||
| f1f8b4622b | |||
| 1fb2172a25 | |||
| 5941f1d071 | |||
| 8d6cc4dfa5 | |||
| 18e077eda9 | |||
| c9e2e518ba | |||
| 51042bde50 | |||
| 5c6a0e12e9 | |||
| d4e1ef659a | |||
| f5f35677f0 | |||
| 90d9c77186 | |||
| 882d130e19 | |||
| 5f84e601b6 | |||
| 0bf6a17428 | |||
| db8881d845 | |||
| 3403352749 | |||
| ac69524258 | |||
| 28589620f6 | |||
| 8e4da7f36b | |||
| 4c4a27f53c | |||
| b838651ac9 | |||
| 5cd8212a61 | |||
| c5f606f10f | |||
| c21bea8b30 | |||
| 22a26a33f4 | |||
| 8a09f05644 | |||
| 5923a0cd2f | |||
| 1576b5a8a0 | |||
| 2c4dbf5a84 | |||
| 021f4f2d70 | |||
| decc571988 | |||
| 322d7a90db | |||
| dd3f653103 | |||
| 46a1860601 | |||
| 84a573c926 | |||
| 7dfa8f43f4 | |||
| 7375b4e847 | |||
| 48da62ed07 | |||
| 9834af7ed9 | |||
| 6b404d8529 | |||
| 3119cc8857 | |||
| bb059b97c0 | |||
| b7188f7022 | |||
| a64fe99d1b | |||
| c716c4e261 | |||
| 3d2e3beafe | |||
| 1917e54a6e | |||
| 898b346d48 | |||
| e90adb20ef | |||
| a52e7f5554 | |||
| 7afb8b52ae | |||
| cb4694387e | |||
| 58fa302007 | |||
| bf33daf124 | |||
| 4b472be56e | |||
| bdffaf3ea1 | |||
| f197c3ce96 | |||
| 01dfad6705 | |||
| 2e06786262 | |||
| 578f34ecaf | |||
| 2c8767cb46 | |||
| 45c51d3198 | |||
| bd40830905 | |||
| 4e6cd2d63f | |||
| 2256a04926 | |||
| 660ea7bd7b | |||
| 7052833512 | |||
| 5c2cf5778f | |||
| b5c0406afe | |||
| 96cd910c92 | |||
| e0bd57d63c | |||
| 7c784f592e | |||
| 2c69ccdca4 | |||
| 66eddd4d9b | |||
| 1485f0a448 | |||
| 379c9e7148 | |||
| 6c2af4da7a | |||
| 2ff7d003ee | |||
| ea182e2561 | |||
| 938f42faf6 | |||
| cc115ca43a | |||
| f1b4072444 | |||
| 16d3e96b77 | |||
| 7d2423e856 | |||
| 9865ec23c7 | |||
| 76a321db5c | |||
| 004dcaec3b | |||
| 74eb2f52b8 | |||
| 9b7317fbb1 | |||
| 41142d41ee | |||
| fd328c2f2a | |||
| 3ad276944a | |||
| bb20796e9d | |||
| 709ac64dfc | |||
| a9a4b2d8e2 | |||
| 7374ac499d | |||
| 6596f77e91 | |||
| eeb4efc19c | |||
| 76b70455ec | |||
| f43c8a6267 | |||
| ae806af644 | |||
| 7aa0b6ce27 | |||
| efdbf5795f | |||
| 55355b6680 | |||
| f8a91e5176 | |||
| aa0cd9b3dc | |||
| 1f82cd6e3d | |||
| 3caac4e6f3 | |||
| f4414bfc14 | |||
| 8378267b9b | |||
| 9c0140968d | |||
| 5716e8c508 | |||
| 0e9d45da60 | |||
| 6e7a75c859 | |||
| 0ff91e4451 | |||
| 305fab7c16 | |||
| a959073a81 | |||
| 2f0fc6e6f1 | |||
| 7bd87feb62 | |||
| bff2301ac3 | |||
| fd3c15fb68 | |||
| 808b06940e | |||
| 8cce6ecf15 | |||
| ef97f87b96 | |||
| 93a7568ff6 | |||
| 0439bb9d02 | |||
| 886670134a | |||
| 65e36647f5 | |||
| 51fdb0e4ef | |||
| a4de662adb | |||
| ff02b0c741 | |||
| 6b3958d5fc | |||
| 84b289dd7b | |||
| dbba537b66 | |||
| bc2324fba7 | |||
| 9082b75e75 | |||
| 4b9f751d74 | |||
| 451700d3d2 | |||
| 1c5d83889c | |||
| f659fa8919 | |||
| 87393b61bb | |||
| a84b6aaedd | |||
| ac98a25291 | |||
| 48dd47b2b7 | |||
| 4af850431c | |||
| 95c5e8681e | |||
| c7c5b50f35 | |||
| a8509a1d03 | |||
| d9b6feef19 | |||
| b526404707 | |||
| 9785646246 | |||
| 332b51f58a | |||
| fb18a5cc56 | |||
| b1cab411d6 | |||
| b01fc032fd | |||
| f771eea6e6 | |||
| 6b127cb8d0 | |||
| d0a63b451c | |||
| 8296ff4bad | |||
| eaff73a541 | |||
| 19ec8bbdb9 | |||
| 4d4b85318f | |||
| 708a310ab0 | |||
| ec75f22396 | |||
| 6ea632e98b | |||
| 4117b1c054 | |||
| 761284932b | |||
| c244535f9b | |||
| 577c7657dc | |||
| f05875e49a | |||
| 56400ac0ff | |||
| a18d8fbc09 | |||
| a0eb235f0a | |||
| c6cd8a09c0 | |||
| 3e94bf2d13 | |||
| f4c8ad6c3a | |||
| 57433e1eaa | |||
| 118476b98b | |||
| 6caf8a0074 | |||
| 96483ee54f | |||
| 6a9216f26a | |||
| 4bba342e42 | |||
| 2987b0d10a | |||
| d6a50b8977 | |||
| 76b3dead9b | |||
| d24b2c86f2 | |||
| b6965ecde8 | |||
| b3d5de3b92 | |||
| 49b0bfd257 | |||
| 1132c0b0e1 | |||
| 4cb5ee0678 | |||
| b257084f3a | |||
| c03587f0bf | |||
| 96526dfd66 | |||
| 740865b637 | |||
| 4d10eef55d | |||
| 7adf624dee | |||
| 78cf29d1d1 | |||
| 3f3cffe317 | |||
| 4e7b0ac089 | |||
| 0c35ce0a4f | |||
| dbd05ae9cc | |||
| c268eb2258 | |||
| 40f8e6b061 | |||
| 001cb7ab01 | |||
| de89f95f31 | |||
| 9812a4c9c6 | |||
| 8ea6c66cf7 | |||
| 17bf789708 | |||
| f6a66a5537 | |||
| 1236889664 | |||
| fd5ab8c5c8 | |||
| 39fa78e2ec | |||
| e18416ac7f | |||
| b63cc13f3a | |||
| 74b230c183 | |||
| 561a373d19 | |||
| 064241f03c | |||
| 32163cd53b | |||
| 3a5aa00262 | |||
| c3f15fd7f8 | |||
| 9985d2ebfc | |||
| 46f88037db | |||
| 7a3e3a61f4 | |||
| 517c2f79b7 | |||
| 4de59494e6 | |||
| 3cde6fa333 | |||
| 0224e212f9 | |||
| 5ad784f6c6 | |||
| b842164fd8 | |||
| 365e5129af | |||
| d0ee5b0b4b | |||
| 5d4f9ce72b | |||
| 807224d231 | |||
| 0bd380ee23 | |||
| a926cb62f0 | |||
| 8c8fcdbc54 | |||
| da7bb8e109 | |||
| f8b3990571 | |||
| 9dffbcfedb | |||
| 50c73edd6a | |||
| 1b1f95f372 | |||
| 9b349d08cc | |||
| 718822449f | |||
| 43624e8e7f | |||
| b0bc8e3594 | |||
| f1b20577d3 | |||
| 9ae47a261e | |||
| 4507eaec5b | |||
| b3212f4c2b | |||
| 6d25fc9dbb | |||
| 589187874a | |||
| 1b6ae02e8a | |||
| 7ace67e997 | |||
| c072025982 | |||
| a5d0703e44 | |||
| 0a32cea26e | |||
| b2acda333b | |||
| da4e37d3f5 | |||
| 17d825bdd9 | |||
| e0254fc312 | |||
| 3f9cbc157a | |||
| a51f930101 | |||
| d1e39db61e | |||
| 77edd8e544 | |||
| 8087b7cec6 | |||
| 42b8b6153e | |||
| 8df841f048 | |||
| bfa2b69193 | |||
| 939e1540d4 | |||
| 835eb94275 | |||
| 79cc333dca | |||
| 1ced6db73e | |||
| fbcf905c9f | |||
| 979a4bcd88 | |||
| 2aefa5bb1d | |||
| 4c92b877d6 | |||
| 342ea25290 | |||
| 8d8f17982a | |||
| bba21f99fe | |||
| 8c57f433ff | |||
| bfac1a581c | |||
| 59285f627b | |||
| dd3233ac85 | |||
| 9b57f60c2a | |||
| 8038832a79 | |||
| 4ce0dfc91d | |||
| 3aba2b79b8 | |||
| 072ff149f5 | |||
| 14802e9666 | |||
| e1a44293c0 | |||
| 8f08baf43a | |||
| 188425ffe5 | |||
| daf015799b | |||
| b3b3b7d565 | |||
| 566af5df9d | |||
| 1a8a11e924 | |||
| 25bebe76b6 | |||
| e5beef4004 | |||
| b858cd9e18 | |||
| f3f098e7f5 | |||
| 09822c99cc | |||
| 966b104d48 | |||
| 59e0d5e081 | |||
| c687ee60ff | |||
| 2c0a4e7669 | |||
| 1ba6ff41f6 | |||
| af6fbba9b8 | |||
| a577574cfe | |||
| f474c57881 | |||
| 7521db7b0b | |||
| 4bdabea639 | |||
| 27c933a865 | |||
| 51912e6197 | |||
| 56c42a907f | |||
| e96a213720 | |||
| bf31feebc4 | |||
| 55de7bd99b | |||
| cc67c97224 | |||
| bd87485251 | |||
| 7ef2205f80 | |||
| 72de877ec3 | |||
| f872b3fb4b | |||
| ddc33ee747 | |||
| 612e384b03 | |||
| 1c88856fc8 | |||
| 0b5e91d430 | |||
| 534e6d1f4c | |||
| 7ad31a01dd | |||
| e0429cdd96 | |||
| 7413bbb7bf | |||
| 00cd2900e7 | |||
| 05a238fac4 | |||
| 0a65153634 | |||
| 310db21d64 | |||
| fc19895237 | |||
| 72af0896e8 | |||
| c4392ff256 | |||
| c68ab508c0 | |||
| 76cca814f0 | |||
| 22b69fc5c9 | |||
| a1bd0c1667 | |||
| 48ea75fddc | |||
| 4b49f716b9 | |||
| 55f5f397d7 | |||
| 4be4f60f21 | |||
| 9a8037bbf2 | |||
| c7f1af90b2 | |||
| 902d3a0aa5 | |||
| c14eb28223 | |||
| 2722a04e52 | |||
| 5dbcd7957a | |||
| 7511eeae7b | |||
| 5f4a7e54bc | |||
| b7e3058078 | |||
| f3358cc377 | |||
| fa3460e0a7 | |||
| 42069ca669 | |||
| acc7141b64 | |||
| 3e1b950b14 | |||
| b50b702d1c | |||
| caddd11c15 | |||
| 5711e3d860 | |||
| 8b1058b8ec | |||
| 092ba6dae2 | |||
| cab653e7c7 | |||
| 8d999a8edd | |||
| 7b773ac088 | |||
| 4f6b27eec1 | |||
| fe20852b2c | |||
| fc58ea7487 | |||
| c61cea0eb1 | |||
| 764b25bd07 | |||
| a66cd25787 | |||
| 0e8d94750b | |||
| 3c915189f4 | |||
| c5541cddeb | |||
| 63561609a6 | |||
| 5dc356ddb0 | |||
| dc36fd38d6 | |||
| 26873bf3d5 | |||
| ff53323790 | |||
| fd3869d380 | |||
| 1d538bc59d | |||
| 784cfcd49e | |||
| a142d319e7 | |||
| da3bf3c20a | |||
| 1672306fa1 | |||
| 7fc780ba1b | |||
| 7fb2bd50bf | |||
| 2aeb51ad51 | |||
| 0482b756e8 | |||
| 1d9c707a76 | |||
| 199ed417bd | |||
| 199a02cb68 | |||
| b6371f045f | |||
| fd84aec485 | |||
| ed6777e59f | |||
| 22024a2b71 | |||
| 8eff38b6f6 | |||
| fa562d449d | |||
| c9d55362d6 | |||
| 23031d057f | |||
| 882d394352 | |||
| fbdede68a4 | |||
| e88ef4715c | |||
| 94f3dd25d8 | |||
| 2c58a9c11d | |||
| 97528b59cf | |||
| 6715fb6652 | |||
| fefc010deb | |||
| 6cbb72decf | |||
| 7e25ed863c | |||
| 5a56394814 | |||
| de1059f648 | |||
| 97f08086dd | |||
| 0348a3914d | |||
| 5dc245d2ce | |||
| 71cc95248c | |||
| 2cb7d66767 | |||
| 49fa208242 | |||
| d2fef27721 | |||
| 351b7039a8 | |||
| 7585ce9ed4 | |||
| 578a0178b5 | |||
| 6c9cebdcc3 | |||
| 35e2022e9a | |||
| 0058e3a8d4 | |||
| abf28ee167 | |||
| 5f1cb9b96c | |||
| 8f8fc6f3ff | |||
| 24787195a1 | |||
| 5885111863 | |||
| b1cb5379de | |||
| 447d08bd91 | |||
| b0512a4479 | |||
| 8663435a05 | |||
| 327990bc5f | |||
| 57753c9044 | |||
| e35603eb85 | |||
| 8fa40fe7e1 | |||
| d4c20829f6 | |||
| dbe2beacb0 | |||
| b9a938a01c | |||
| 4dd7345568 | |||
| b3cf9375d4 | |||
| 1751155a3a | |||
| 5dae700aec | |||
| affa9382be | |||
| 10f23dddfe | |||
| d30cf07254 | |||
| 31491b822f | |||
| 4c19cfead5 | |||
| b2754c2c3b | |||
| f56976db1d | |||
| 77b8a8baa0 | |||
| 0b9190cce3 | |||
| 2a40c5dd24 | |||
| 60ab494226 | |||
| ac758ed3c8 | |||
| 236d40d73e | |||
| 92029a05c6 | |||
| c7b9997dd1 | |||
| 48309bfdd0 | |||
| f76d1ab10d | |||
| 45f552f006 | |||
| 4d42cfea53 | |||
| 7109e2d379 | |||
| ff214643ce | |||
| 04918a52eb | |||
| 5dd71600f7 | |||
| ea9ed22e3e | |||
| 1611daf802 | |||
| e24f52d3ae | |||
| bcc9e15b05 | |||
| af835a2699 | |||
| 5f2d306f9b | |||
| 36fb49b522 | |||
| ed5b4d7319 | |||
| b09c0fc653 | |||
| ab3e40ca45 | |||
| 8f67e9c048 | |||
| 7dc1a64f03 | |||
| ac3a3e922f | |||
| 4e50c56542 | |||
| 26b1ed79c0 | |||
| 2e8ef0f768 | |||
| c993414b92 | |||
| ed6ef4e149 | |||
| 859cdcc815 | |||
| 745a95b607 | |||
| 81d617bd93 | |||
| 3396388222 | |||
| ff8c3b3d51 | |||
| 3d0efd123f | |||
| 8ca1b9ac3c | |||
| 2c24be90d2 | |||
| 482f92af61 | |||
| 24ac61f9f2 | |||
| 426394cd7b | |||
| 7c3e95a7c7 | |||
| 9dd5f9dc7a | |||
| e6776ffc37 | |||
| adae2bd3c5 | |||
| 14ca260c26 | |||
| 64588f0cb6 | |||
| 50cac7f985 | |||
| 5fe85128c2 | |||
| bc236bde34 | |||
| 15794a5ed6 | |||
| 62058962de | |||
| 7d52366403 | |||
| ee45eb8340 | |||
| 801f37b305 | |||
| bdec0b3e63 | |||
| 5c631f3e58 | |||
| 5fd9daa865 | |||
| 0485702a68 | |||
| 875610044f | |||
| ec483fc07d | |||
| 53e6e29571 | |||
| c5eed99c6a | |||
| fe5176113b | |||
| 0f7c67efa7 | |||
| cd0ee64892 | |||
| ec3af2cb6a | |||
| 960b68937d | |||
| a1e101b513 | |||
| c30311153c | |||
| a935ebe8b9 | |||
| 83ee86122b | |||
| af752ddcb5 | |||
| 9550063275 | |||
| c117a680cf | |||
| 206e19edb4 | |||
| f0c87fbd4c | |||
| c3fe6c9c67 | |||
| e5df4b6653 | |||
| 12cf2f0b0b | |||
| 8d4de2b3db | |||
| e509adcac5 | |||
| eb9c860cb4 | |||
| cf38b8dae5 | |||
| 75af81234f | |||
| 7cc319acca | |||
| 3b44792ff3 | |||
| 678bad241e | |||
| 5b1225cc87 | |||
| 1748831152 | |||
| ed1b476a22 | |||
| 79c59ebae1 | |||
| fd6462f8d1 | |||
| c37f67b0a1 | |||
| 195f7380b5 | |||
| becb8c48e8 | |||
| aa16ecf4d3 | |||
| ddda360fec | |||
| cca72f2dbc | |||
| 5013b37c09 | |||
| c90dc9f48f | |||
| 67e8ca354c | |||
| 9a4ba047c4 | |||
| 7622255d6f | |||
| 8ba1e7aceb | |||
| 5f6838130d | |||
| e0eff942b1 | |||
| 1da47c0870 | |||
| d36879f5ee | |||
| f363cb435a | |||
| d8506e9a6d | |||
| 87503d11e9 | |||
| d0b49d9b89 | |||
| b30965ede4 | |||
| ace6d9e442 | |||
| e150553d58 | |||
| ed569bd3f6 | |||
| d00c1ad6d0 | |||
| 2cd49060fa | |||
| 54a970e694 | |||
| d57f02884f | |||
| dcf7037792 | |||
| 55eb390778 | |||
| 99b9524201 | |||
| 45bd239202 | |||
| 54009e0991 | |||
| bfe7a04c4d | |||
| 3167da72d8 | |||
| 0d725a63b0 | |||
| ee0cd4aba9 | |||
| 1b1c605102 | |||
| 44edfa5974 | |||
| aa8d13456a | |||
| 4beb86ab7e | |||
| c369010d3d | |||
| 1618faed63 | |||
| 9059b734aa | |||
| 89f463111e | |||
| 2962287703 | |||
| aa3c55fd98 | |||
| 17c295680e | |||
| 09de237033 | |||
| d17846eff1 | |||
| 5378d22708 | |||
| c8b2ad01b5 | |||
| e778c7e25c | |||
| f0d0dd2982 | |||
| 3e63d34c00 | |||
| 8821421357 | |||
| eb4af09456 | |||
| 78137ee3a4 | |||
| b40d8f7bac | |||
| a6ba251ef9 | |||
| c6cc2340c8 | |||
| a212ef11a9 | |||
| 7bd4c6963b | |||
| f21cbb71e2 | |||
| f4f8194f46 | |||
| 90e02206fe | |||
| 9fc9d1b33a | |||
| b9f5d22630 | |||
| cbafc83af4 | |||
| b628446768 | |||
| aacc14ad7b | |||
| 35eb234c41 | |||
| 989c8ff809 | |||
| 49c2585a20 | |||
| 9972478066 | |||
| 00287bd055 | |||
| 11f47bd51f | |||
| 5e98a83717 | |||
| ec8b7c9b89 | |||
| 008ce75ae5 | |||
| 5c62b7ed06 | |||
| 99f4efd313 | |||
| 87ff636c10 | |||
| d2bd361d9c | |||
| 5a32d420cd | |||
| a3b2f00c92 | |||
| 13fcf1ad5b | |||
| 8cb2ff6e2e | |||
| c917941ec3 | |||
| f699d29fb3 | |||
| 6723097a3f | |||
| 80e27344f1 | |||
| f244e0f522 | |||
| 61317f5935 | |||
| 9ca1e2a8f7 | |||
| aedd5f57cf | |||
| dc87288f48 | |||
| 5dd53e7ea3 | |||
| 9e454a243a | |||
| 3f62b6d2bf | |||
| fbd6d1974a | |||
| 5d22be26d8 |
+3
-2
@@ -1,2 +1,3 @@
|
||||
/target/
|
||||
/Cargo.lock
|
||||
Cargo.lock
|
||||
target
|
||||
*.sw[po]
|
||||
|
||||
+12
-8
@@ -1,13 +1,17 @@
|
||||
sudo: false
|
||||
language: rust
|
||||
cache: cargo
|
||||
|
||||
# run builds for all the trains (and more)
|
||||
rust:
|
||||
- 1.13.0
|
||||
- stable
|
||||
- beta
|
||||
- nightly
|
||||
|
||||
script:
|
||||
- cargo build --verbose
|
||||
- cargo test --verbose
|
||||
- cargo bench --verbose
|
||||
- cd serde2
|
||||
- cargo build --verbose
|
||||
- cargo test --verbose
|
||||
- cargo bench --verbose
|
||||
matrix:
|
||||
include:
|
||||
- rust: nightly
|
||||
env: CLIPPY=true
|
||||
|
||||
script: ./travis.sh
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
# Contributing to Serde
|
||||
|
||||
Serde welcomes contribution from everyone. Here are the guidelines if you are
|
||||
thinking of helping us:
|
||||
|
||||
## Contributions
|
||||
|
||||
Contributions to Serde or its dependencies should be made in the form of GitHub
|
||||
pull requests. Each pull request will be reviewed by a core contributor
|
||||
(someone with permission to land patches) and either landed in the main tree or
|
||||
given feedback for changes that would be required. All contributions should
|
||||
follow this format, even those from core contributors.
|
||||
|
||||
Should you wish to work on an issue, please claim it first by commenting on
|
||||
the GitHub issue that you want to work on it. This is to prevent duplicated
|
||||
efforts from contributors on the same issue.
|
||||
|
||||
## Pull Request Checklist
|
||||
|
||||
- Branch from the master branch and, if needed, rebase to the current master
|
||||
branch before submitting your pull request. If it doesn't merge cleanly with
|
||||
master you may be asked to rebase your changes.
|
||||
|
||||
- Commits should be as small as possible, while ensuring that each commit is
|
||||
correct independently (i.e., each commit should compile and pass tests).
|
||||
|
||||
- If your patch is not getting reviewed or you need a specific person to review
|
||||
it, you can @-reply a reviewer asking for a review in the pull request or a
|
||||
comment, or you can ask for a review in `#serde` on `irc.mozilla.org`.
|
||||
|
||||
- Add tests relevant to the fixed bug or new feature.
|
||||
|
||||
## Conduct
|
||||
|
||||
In all Serde-related forums, we follow the [Rust Code of
|
||||
Conduct](https://www.rust-lang.org/conduct.html). For escalation or moderation
|
||||
issues, please contact Erick (erick.tryzelaar@gmail.com) instead of the Rust
|
||||
moderation team.
|
||||
|
||||
## Communication
|
||||
|
||||
Beyond opening tickets on the
|
||||
[serde-rs/serde](https://github.com/serde-rs/serde) project, Serde contributors
|
||||
frequent the `#serde` channel on
|
||||
[`irc.mozilla.org`](https://wiki.mozilla.org/IRC).
|
||||
+9
-16
@@ -1,16 +1,9 @@
|
||||
[package]
|
||||
name = "serde"
|
||||
version = "0.2.0"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "A quasi-quoting macro system"
|
||||
repository = "https://github.com/erickt/rust-quasi"
|
||||
|
||||
[lib]
|
||||
name = "serde"
|
||||
|
||||
[dependencies]
|
||||
rustc-serialize = "*"
|
||||
|
||||
[dev-dependencies]
|
||||
serde_macros = "0.2.0"
|
||||
[workspace]
|
||||
members = [
|
||||
"serde",
|
||||
"serde_codegen_internals",
|
||||
"serde_derive",
|
||||
"serde_test",
|
||||
"test_suite",
|
||||
"test_suite/no_std",
|
||||
]
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
See LICENSE-APACHE and LICENSE-MIT.
|
||||
|
||||
----
|
||||
|
||||
bench_log is derived from https://github.com/cloudflare/goser, which has the
|
||||
following license:
|
||||
|
||||
Copyright (c) 2013, CloudFlare, Inc.
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of the author nor the
|
||||
names of its contributors may be used to endorse or promote products
|
||||
derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
|
||||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
@@ -1,34 +1,71 @@
|
||||
Experimental Rust Serialization Library.
|
||||
# Serde   [](https://travis-ci.org/serde-rs/serde) [](https://crates.io/crates/serde)
|
||||
|
||||
[](https://travis-ci.org/erickt/rust-serde)
|
||||
|
||||
This is an experiment to modernize rust's `libserialize` library. It is designed to implement https://github.com/rust-lang/rfcs/pull/22. `rust-serde` is an attempt to address a major shortcoming in `libserialize`. For normal structures, when you say you want to deserialize into:
|
||||
|
||||
```rust
|
||||
struct Foo {
|
||||
x: int,
|
||||
y: int,
|
||||
}
|
||||
```
|
||||
|
||||
`libserialize`'s deserializer essentially asks for:
|
||||
|
||||
* Is the next value a struct named "Foo"? If not, error.
|
||||
* Is the next field named "x"? If not, error.
|
||||
* Is the next value an "int"? If not, error.
|
||||
* Is the next field named "y"? If not, error.
|
||||
* Is the next value an "int"? If not, error.
|
||||
* Is the struct finished? If not, error.
|
||||
|
||||
While this works for user defined structures, it cannot support deserializing into a value like `json::Json`, which is an enum that can represent every JSON value. In order to support that, it needs to be able to do some lookahead:
|
||||
|
||||
* What is the next value type?
|
||||
* If a struct, parse a struct.
|
||||
* If an integer, parse an integer.
|
||||
* ...
|
||||
|
||||
More formally, `libserialize` implements a LL(0) grammar, whereas `json::Json` requires a LL(1) grammar. `rust-serde` provides this by implementing a serializer and deserializer that produces a tagged token stream of values. This enables a `Deserializable` for `json::Json` to look at the next token before deciding on how to parse the value.
|
||||
**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.**
|
||||
|
||||
---
|
||||
|
||||
There is now also a new library variation called `serde2`. This removes the need for tagged values and replaces them with a `Visitor` pattern. This pattern is very similar to the `Iterator` pattern, but it threads some custom state through visiting each type. This gets many of the benefits of the `serde` library without needing to always pay for tagging the variants.
|
||||
You may be looking for:
|
||||
|
||||
- [An overview of Serde](https://serde.rs/)
|
||||
- [Data formats supported by Serde](https://serde.rs/#data-formats)
|
||||
- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/codegen.html)
|
||||
- [Examples](https://serde.rs/examples.html)
|
||||
- [API documentation](https://docs.serde.rs/serde/)
|
||||
- [Release notes](https://github.com/serde-rs/serde/releases)
|
||||
|
||||
## Serde in action
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
extern crate serde_json;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
struct Point {
|
||||
x: i32,
|
||||
y: i32,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let point = Point { x: 1, y: 2 };
|
||||
|
||||
// Convert the Point to a JSON string.
|
||||
let serialized = serde_json::to_string(&point).unwrap();
|
||||
|
||||
// Prints serialized = {"x":1,"y":2}
|
||||
println!("serialized = {}", serialized);
|
||||
|
||||
// Convert the JSON string back to a Point.
|
||||
let deserialized: Point = serde_json::from_str(&serialized).unwrap();
|
||||
|
||||
// Prints deserialized = Point { x: 1, y: 2 }
|
||||
println!("deserialized = {:?}", deserialized);
|
||||
}
|
||||
```
|
||||
|
||||
## Getting help
|
||||
|
||||
Serde developers live in the #serde channel on
|
||||
[`irc.mozilla.org`](https://wiki.mozilla.org/IRC). The #rust channel is also a
|
||||
good resource with generally faster response time but less specific knowledge
|
||||
about Serde. If IRC is not your thing or you don't get a good response, we are
|
||||
happy to respond to [GitHub issues](https://github.com/serde-rs/serde/issues/new)
|
||||
as well.
|
||||
|
||||
## License
|
||||
|
||||
Serde is licensed under either of
|
||||
|
||||
* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
|
||||
http://www.apache.org/licenses/LICENSE-2.0)
|
||||
* MIT license ([LICENSE-MIT](LICENSE-MIT) or
|
||||
http://opensource.org/licenses/MIT)
|
||||
|
||||
at your option.
|
||||
|
||||
### Contribution
|
||||
|
||||
Unless you explicitly state otherwise, any contribution intentionally submitted
|
||||
for inclusion in Serde by you, as defined in the Apache-2.0 license, shall be
|
||||
dual licensed as above, without any additional terms or conditions.
|
||||
|
||||
@@ -1,417 +0,0 @@
|
||||
#![feature(custom_derive, plugin, test)]
|
||||
#![plugin(serde_macros)]
|
||||
|
||||
extern crate serde;
|
||||
extern crate "rustc-serialize" as rustc_serialize;
|
||||
extern crate test;
|
||||
|
||||
use test::Bencher;
|
||||
|
||||
use rustc_serialize::{Decoder, Decodable};
|
||||
|
||||
use serde::de::{Deserializer, Deserialize};
|
||||
|
||||
use Animal::{Dog, Frog};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(Clone, PartialEq, Debug, RustcDecodable)]
|
||||
#[derive_deserialize]
|
||||
enum Animal {
|
||||
Dog,
|
||||
Frog(String, isize)
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
EndOfStreamError,
|
||||
SyntaxError,
|
||||
}
|
||||
|
||||
impl serde::de::Error for Error {
|
||||
fn syntax_error() -> Error { Error::SyntaxError }
|
||||
|
||||
fn end_of_stream_error() -> Error { Error::EndOfStreamError }
|
||||
|
||||
fn missing_field_error(_: &'static str) -> Error { Error::SyntaxError }
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
mod decoder {
|
||||
use rustc_serialize::Decoder;
|
||||
|
||||
use super::{Animal, Error};
|
||||
use super::Animal::{Dog, Frog};
|
||||
use self::State::{AnimalState, IsizeState, StringState};
|
||||
|
||||
enum State {
|
||||
AnimalState(Animal),
|
||||
IsizeState(isize),
|
||||
StringState(String),
|
||||
}
|
||||
|
||||
pub struct AnimalDecoder {
|
||||
stack: Vec<State>,
|
||||
|
||||
}
|
||||
|
||||
impl AnimalDecoder {
|
||||
#[inline]
|
||||
pub fn new(animal: Animal) -> AnimalDecoder {
|
||||
AnimalDecoder {
|
||||
stack: vec!(AnimalState(animal)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Decoder for AnimalDecoder {
|
||||
type Error = Error;
|
||||
|
||||
fn error(&mut self, _: &str) -> Error { Error::SyntaxError }
|
||||
|
||||
// Primitive types:
|
||||
fn read_nil(&mut self) -> Result<(), Error> { Err(Error::SyntaxError) }
|
||||
fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::SyntaxError) }
|
||||
fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::SyntaxError) }
|
||||
fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::SyntaxError) }
|
||||
fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::SyntaxError) }
|
||||
fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::SyntaxError) }
|
||||
#[inline]
|
||||
fn read_isize(&mut self) -> Result<isize, Error> {
|
||||
match self.stack.pop() {
|
||||
Some(IsizeState(x)) => Ok(x),
|
||||
_ => Err(Error::SyntaxError),
|
||||
}
|
||||
}
|
||||
fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::SyntaxError) }
|
||||
fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::SyntaxError) }
|
||||
fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::SyntaxError) }
|
||||
fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::SyntaxError) }
|
||||
fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::SyntaxError) }
|
||||
fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::SyntaxError) }
|
||||
fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::SyntaxError) }
|
||||
fn read_char(&mut self) -> Result<char, Error> { Err(Error::SyntaxError) }
|
||||
#[inline]
|
||||
fn read_str(&mut self) -> Result<String, Error> {
|
||||
match self.stack.pop() {
|
||||
Some(StringState(x)) => Ok(x),
|
||||
_ => Err(Error::SyntaxError),
|
||||
}
|
||||
}
|
||||
|
||||
// Compound types:
|
||||
#[inline]
|
||||
fn read_enum<T, F>(&mut self, name: &str, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
match self.stack.pop() {
|
||||
Some(AnimalState(animal)) => {
|
||||
self.stack.push(AnimalState(animal));
|
||||
if name == "Animal" {
|
||||
f(self)
|
||||
} else {
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
}
|
||||
_ => Err(Error::SyntaxError)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_enum_variant<T, F>(&mut self, names: &[&str], f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
let name = match self.stack.pop() {
|
||||
Some(AnimalState(Dog)) => "Dog",
|
||||
Some(AnimalState(Frog(x0, x1))) => {
|
||||
self.stack.push(IsizeState(x1));
|
||||
self.stack.push(StringState(x0));
|
||||
"Frog"
|
||||
}
|
||||
_ => { return Err(Error::SyntaxError); }
|
||||
};
|
||||
|
||||
let idx = match names.iter().position(|n| *n == name) {
|
||||
Some(idx) => idx,
|
||||
None => { return Err(Error::SyntaxError); }
|
||||
};
|
||||
|
||||
f(self, idx)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
f(self)
|
||||
}
|
||||
|
||||
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
// Specialized types:
|
||||
fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder, bool) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_seq<T, F>(&mut self, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
f(self, 3)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
f(self)
|
||||
}
|
||||
|
||||
fn read_map<T, F>(&mut self, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_map_elt_key<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_map_elt_val<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
mod deserializer {
|
||||
use super::{Animal, Error};
|
||||
|
||||
use serde::de;
|
||||
|
||||
enum State {
|
||||
AnimalState(Animal),
|
||||
IsizeState(isize),
|
||||
StringState(String),
|
||||
UnitState,
|
||||
}
|
||||
|
||||
pub struct AnimalDeserializer {
|
||||
stack: Vec<State>,
|
||||
}
|
||||
|
||||
impl AnimalDeserializer {
|
||||
#[inline]
|
||||
pub fn new(animal: Animal) -> AnimalDeserializer {
|
||||
AnimalDeserializer {
|
||||
stack: vec!(State::AnimalState(animal)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl de::Deserializer for AnimalDeserializer {
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn visit<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
match self.stack.pop() {
|
||||
Some(State::AnimalState(Animal::Dog)) => {
|
||||
self.stack.push(State::UnitState);
|
||||
visitor.visit_enum("Animal", "Dog", DogVisitor {
|
||||
de: self,
|
||||
})
|
||||
}
|
||||
Some(State::AnimalState(Animal::Frog(x0, x1))) => {
|
||||
self.stack.push(State::IsizeState(x1));
|
||||
self.stack.push(State::StringState(x0));
|
||||
visitor.visit_enum("Animal", "Frog", FrogVisitor {
|
||||
de: self,
|
||||
state: 0,
|
||||
})
|
||||
}
|
||||
Some(State::IsizeState(value)) => {
|
||||
visitor.visit_isize(value)
|
||||
}
|
||||
Some(State::StringState(value)) => {
|
||||
visitor.visit_string(value)
|
||||
}
|
||||
Some(State::UnitState) => {
|
||||
visitor.visit_unit()
|
||||
}
|
||||
None => {
|
||||
Err(Error::EndOfStreamError)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct DogVisitor<'a> {
|
||||
de: &'a mut AnimalDeserializer,
|
||||
}
|
||||
|
||||
impl<'a> de::EnumVisitor for DogVisitor<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_unit(&mut self) -> Result<(), Error> {
|
||||
de::Deserialize::deserialize(self.de)
|
||||
}
|
||||
}
|
||||
|
||||
struct FrogVisitor<'a> {
|
||||
de: &'a mut AnimalDeserializer,
|
||||
state: usize,
|
||||
}
|
||||
|
||||
impl<'a> de::EnumVisitor for FrogVisitor<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_seq<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::EnumSeqVisitor,
|
||||
{
|
||||
visitor.visit(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> de::SeqVisitor for FrogVisitor<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit<T>(&mut self) -> Result<Option<T>, Error>
|
||||
where T: de::Deserialize,
|
||||
{
|
||||
match self.state {
|
||||
0 => {
|
||||
self.state += 1;
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
|
||||
}
|
||||
1 => {
|
||||
self.state += 1;
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
|
||||
}
|
||||
_ => {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
if self.state == 2 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = 2 - self.state;
|
||||
(len, Some(len))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_dog(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let animal = Dog;
|
||||
|
||||
let mut d = decoder::AnimalDecoder::new(animal.clone());
|
||||
let value: Animal = Decodable::decode(&mut d).unwrap();
|
||||
|
||||
assert_eq!(value, animal);
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_frog(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let animal = Frog("Henry".to_string(), 349);
|
||||
|
||||
let mut d = decoder::AnimalDecoder::new(animal.clone());
|
||||
let value: Animal = Decodable::decode(&mut d).unwrap();
|
||||
|
||||
assert_eq!(value, animal);
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_dog(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let animal = Dog;
|
||||
|
||||
let mut d = deserializer::AnimalDeserializer::new(animal.clone());
|
||||
let value: Animal = Deserialize::deserialize(&mut d).unwrap();
|
||||
|
||||
assert_eq!(value, animal);
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_frog(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let animal = Frog("Henry".to_string(), 349);
|
||||
|
||||
let mut d = deserializer::AnimalDeserializer::new(animal.clone());
|
||||
let value: Animal = Deserialize::deserialize(&mut d).unwrap();
|
||||
|
||||
assert_eq!(value, animal);
|
||||
})
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,462 +0,0 @@
|
||||
#![feature(custom_derive, core, plugin, test)]
|
||||
#![plugin(serde_macros)]
|
||||
|
||||
extern crate serde;
|
||||
extern crate "rustc-serialize" as rustc_serialize;
|
||||
extern crate test;
|
||||
|
||||
use std::fmt::Debug;
|
||||
use std::collections::HashMap;
|
||||
use test::Bencher;
|
||||
|
||||
use rustc_serialize::{Decoder, Decodable};
|
||||
|
||||
use serde::de::{Deserializer, Deserialize};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
pub enum Error {
|
||||
EndOfStream,
|
||||
SyntaxError,
|
||||
MissingField,
|
||||
}
|
||||
|
||||
impl serde::de::Error for Error {
|
||||
fn syntax_error() -> Error { Error::SyntaxError }
|
||||
|
||||
fn end_of_stream_error() -> Error { Error::EndOfStream }
|
||||
|
||||
fn missing_field_error(_: &'static str) -> Error {
|
||||
Error::MissingField
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
mod decoder {
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::IntoIter;
|
||||
use rustc_serialize;
|
||||
|
||||
use super::Error;
|
||||
use self::Value::{StringValue, IsizeValue};
|
||||
|
||||
enum Value {
|
||||
StringValue(String),
|
||||
IsizeValue(isize),
|
||||
}
|
||||
|
||||
pub struct IsizeDecoder {
|
||||
len: usize,
|
||||
iter: IntoIter<String, isize>,
|
||||
stack: Vec<Value>,
|
||||
}
|
||||
|
||||
impl IsizeDecoder {
|
||||
#[inline]
|
||||
pub fn new(values: HashMap<String, isize>) -> IsizeDecoder {
|
||||
IsizeDecoder {
|
||||
len: values.len(),
|
||||
iter: values.into_iter(),
|
||||
stack: vec!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl rustc_serialize::Decoder for IsizeDecoder {
|
||||
type Error = Error;
|
||||
|
||||
fn error(&mut self, _msg: &str) -> Error {
|
||||
Error::SyntaxError
|
||||
}
|
||||
|
||||
// Primitive types:
|
||||
fn read_nil(&mut self) -> Result<(), Error> { Err(Error::SyntaxError) }
|
||||
fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::SyntaxError) }
|
||||
fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::SyntaxError) }
|
||||
fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::SyntaxError) }
|
||||
fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::SyntaxError) }
|
||||
fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::SyntaxError) }
|
||||
#[inline]
|
||||
fn read_isize(&mut self) -> Result<isize, Error> {
|
||||
match self.stack.pop() {
|
||||
Some(IsizeValue(x)) => Ok(x),
|
||||
Some(_) => Err(Error::SyntaxError),
|
||||
None => Err(Error::EndOfStream),
|
||||
}
|
||||
}
|
||||
fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::SyntaxError) }
|
||||
fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::SyntaxError) }
|
||||
fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::SyntaxError) }
|
||||
fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::SyntaxError) }
|
||||
fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::SyntaxError) }
|
||||
fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::SyntaxError) }
|
||||
fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::SyntaxError) }
|
||||
fn read_char(&mut self) -> Result<char, Error> { Err(Error::SyntaxError) }
|
||||
#[inline]
|
||||
fn read_str(&mut self) -> Result<String, Error> {
|
||||
match self.stack.pop() {
|
||||
Some(StringValue(x)) => Ok(x),
|
||||
Some(_) => Err(Error::SyntaxError),
|
||||
None => Err(Error::EndOfStream),
|
||||
}
|
||||
}
|
||||
|
||||
// Compound types:
|
||||
fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
// Specialized types:
|
||||
fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder, bool) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_seq<T, F>(&mut self, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_seq_elt<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_map<T, F>(&mut self, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
let len = self.len;
|
||||
f(self, len)
|
||||
}
|
||||
#[inline]
|
||||
fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
match self.iter.next() {
|
||||
Some((key, value)) => {
|
||||
self.stack.push(IsizeValue(value));
|
||||
self.stack.push(StringValue(key));
|
||||
f(self)
|
||||
}
|
||||
None => {
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
f(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
mod deserializer {
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map;
|
||||
|
||||
use super::Error;
|
||||
|
||||
use serde::de;
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
enum State {
|
||||
StartState,
|
||||
KeyState(String),
|
||||
ValueState(isize),
|
||||
}
|
||||
|
||||
pub struct IsizeDeserializer {
|
||||
stack: Vec<State>,
|
||||
iter: hash_map::IntoIter<String, isize>,
|
||||
}
|
||||
|
||||
impl IsizeDeserializer {
|
||||
#[inline]
|
||||
pub fn new(values: HashMap<String, isize>) -> IsizeDeserializer {
|
||||
IsizeDeserializer {
|
||||
stack: vec!(State::StartState),
|
||||
iter: values.into_iter(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl de::Deserializer for IsizeDeserializer {
|
||||
type Error = Error;
|
||||
|
||||
fn visit<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
match self.stack.pop() {
|
||||
Some(State::StartState) => {
|
||||
visitor.visit_map(self)
|
||||
}
|
||||
Some(State::KeyState(key)) => {
|
||||
visitor.visit_string(key)
|
||||
}
|
||||
Some(State::ValueState(value)) => {
|
||||
visitor.visit_isize(value)
|
||||
}
|
||||
None => {
|
||||
Err(Error::EndOfStream)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl de::MapVisitor for IsizeDeserializer {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
|
||||
where K: de::Deserialize,
|
||||
{
|
||||
match self.iter.next() {
|
||||
Some((key, value)) => {
|
||||
self.stack.push(State::ValueState(value));
|
||||
self.stack.push(State::KeyState(key));
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self))))
|
||||
}
|
||||
None => {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_value<V>(&mut self) -> Result<V, Error>
|
||||
where V: de::Deserialize,
|
||||
{
|
||||
de::Deserialize::deserialize(self)
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
match self.iter.next() {
|
||||
Some(_) => Err(Error::SyntaxError),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
self.iter.size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
impl Iterator for IsizeDeserializer {
|
||||
type Item = Result<de::Token, Error>;
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Result<de::Token, Error>> {
|
||||
match self.stack.pop() {
|
||||
Some(StartState) => {
|
||||
self.stack.push(KeyOrEndState);
|
||||
Some(Ok(de::Token::MapStart(self.len)))
|
||||
}
|
||||
Some(KeyOrEndState) => {
|
||||
match self.iter.next() {
|
||||
Some((key, value)) => {
|
||||
self.stack.push(ValueState(value));
|
||||
Some(Ok(de::Token::String(key)))
|
||||
}
|
||||
None => {
|
||||
self.stack.push(EndState);
|
||||
Some(Ok(de::Token::End))
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(ValueState(x)) => {
|
||||
self.stack.push(KeyOrEndState);
|
||||
Some(Ok(de::Token::Isize(x)))
|
||||
}
|
||||
Some(EndState) => {
|
||||
None
|
||||
}
|
||||
None => {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl de::Deserializer<Error> for IsizeDeserializer {
|
||||
#[inline]
|
||||
fn end_of_stream_error(&mut self) -> Error {
|
||||
EndOfStream
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn syntax_error(&mut self, _token: de::Token, _expected: &[de::TokenKind]) -> Error {
|
||||
SyntaxError
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn unexpected_name_error(&mut self, _token: de::Token) -> Error {
|
||||
SyntaxError
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn conversion_error(&mut self, _token: de::Token) -> Error {
|
||||
SyntaxError
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn missing_field<
|
||||
T: de::Deserialize<IsizeDeserializer, Error>
|
||||
>(&mut self, _field: &'static str) -> Result<T, Error> {
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
fn run_decoder<
|
||||
D: Decoder<Error=Error>,
|
||||
T: Clone + PartialEq + Debug + Decodable
|
||||
>(mut d: D, value: T) {
|
||||
let v = Decodable::decode(&mut d);
|
||||
|
||||
assert_eq!(Ok(value), v);
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_000(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let m: HashMap<String, isize> = HashMap::new();
|
||||
run_decoder(decoder::IsizeDecoder::new(m.clone()), m)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_003(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let mut m: HashMap<String, isize> = HashMap::new();
|
||||
for i in range(0, 3) {
|
||||
m.insert(i.to_string(), i);
|
||||
}
|
||||
run_decoder(decoder::IsizeDecoder::new(m.clone()), m)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_100(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let mut m: HashMap<String, isize> = HashMap::new();
|
||||
for i in range(0, 100) {
|
||||
m.insert(i.to_string(), i);
|
||||
}
|
||||
run_decoder(decoder::IsizeDecoder::new(m.clone()), m)
|
||||
})
|
||||
}
|
||||
|
||||
fn run_deserializer<
|
||||
D: Deserializer<Error=E>,
|
||||
E: Debug,
|
||||
T: Clone + PartialEq + Debug + Deserialize
|
||||
>(mut d: D, value: T) {
|
||||
let v: T = Deserialize::deserialize(&mut d).unwrap();
|
||||
|
||||
assert_eq!(value, v);
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_000(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let m: HashMap<String, isize> = HashMap::new();
|
||||
run_deserializer(deserializer::IsizeDeserializer::new(m.clone()), m)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_003(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let mut m: HashMap<String, isize> = HashMap::new();
|
||||
for i in range(0, 3) {
|
||||
m.insert(i.to_string(), i);
|
||||
}
|
||||
run_deserializer(deserializer::IsizeDeserializer::new(m.clone()), m)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_100(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let mut m: HashMap<String, isize> = HashMap::new();
|
||||
for i in range(0, 100) {
|
||||
m.insert(i.to_string(), i);
|
||||
}
|
||||
run_deserializer(deserializer::IsizeDeserializer::new(m.clone()), m)
|
||||
})
|
||||
}
|
||||
@@ -1,726 +0,0 @@
|
||||
#![feature(custom_derive, plugin, test)]
|
||||
#![plugin(serde_macros)]
|
||||
|
||||
extern crate serde;
|
||||
extern crate "rustc-serialize" as rustc_serialize;
|
||||
extern crate test;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use test::Bencher;
|
||||
|
||||
use rustc_serialize::{Decoder, Decodable};
|
||||
|
||||
use serde::de::{Deserializer, Deserialize};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(Clone, PartialEq, Debug, RustcDecodable)]
|
||||
#[derive_deserialize]
|
||||
struct Inner {
|
||||
a: (),
|
||||
b: usize,
|
||||
c: HashMap<String, Option<char>>,
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(Clone, PartialEq, Debug, RustcDecodable)]
|
||||
#[derive_deserialize]
|
||||
struct Outer {
|
||||
inner: Vec<Inner>,
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
EndOfStream,
|
||||
SyntaxError,
|
||||
UnexpectedName,
|
||||
ConversionError,
|
||||
MissingField,
|
||||
OtherError,
|
||||
}
|
||||
|
||||
impl serde::de::Error for Error {
|
||||
fn syntax_error() -> Error { Error::SyntaxError }
|
||||
|
||||
fn end_of_stream_error() -> Error { Error::EndOfStream }
|
||||
|
||||
fn missing_field_error(_: &'static str) -> Error {
|
||||
Error::MissingField
|
||||
}
|
||||
}
|
||||
|
||||
mod decoder {
|
||||
use std::collections::HashMap;
|
||||
use rustc_serialize::Decoder;
|
||||
|
||||
use super::{Outer, Inner, Error};
|
||||
|
||||
use self::State::{
|
||||
OuterState,
|
||||
InnerState,
|
||||
NullState,
|
||||
UsizeState,
|
||||
CharState,
|
||||
StringState,
|
||||
FieldState,
|
||||
VecState,
|
||||
MapState,
|
||||
OptionState,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
enum State {
|
||||
OuterState(Outer),
|
||||
InnerState(Inner),
|
||||
NullState,
|
||||
UsizeState(usize),
|
||||
CharState(char),
|
||||
StringState(String),
|
||||
FieldState(&'static str),
|
||||
VecState(Vec<Inner>),
|
||||
MapState(HashMap<String, Option<char>>),
|
||||
OptionState(bool),
|
||||
}
|
||||
|
||||
pub struct OuterDecoder {
|
||||
stack: Vec<State>,
|
||||
|
||||
}
|
||||
|
||||
impl OuterDecoder {
|
||||
#[inline]
|
||||
pub fn new(animal: Outer) -> OuterDecoder {
|
||||
OuterDecoder {
|
||||
stack: vec!(OuterState(animal)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Decoder for OuterDecoder {
|
||||
type Error = Error;
|
||||
|
||||
fn error(&mut self, _msg: &str) -> Error {
|
||||
Error::OtherError
|
||||
}
|
||||
|
||||
// Primitive types:
|
||||
#[inline]
|
||||
fn read_nil(&mut self) -> Result<(), Error> {
|
||||
match self.stack.pop() {
|
||||
Some(NullState) => Ok(()),
|
||||
_ => Err(Error::SyntaxError),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn read_usize(&mut self) -> Result<usize, Error> {
|
||||
match self.stack.pop() {
|
||||
Some(UsizeState(value)) => Ok(value),
|
||||
_ => Err(Error::SyntaxError),
|
||||
}
|
||||
}
|
||||
fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::SyntaxError) }
|
||||
fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::SyntaxError) }
|
||||
fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::SyntaxError) }
|
||||
fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::SyntaxError) }
|
||||
fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::SyntaxError) }
|
||||
fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::SyntaxError) }
|
||||
fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::SyntaxError) }
|
||||
fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::SyntaxError) }
|
||||
fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::SyntaxError) }
|
||||
fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::SyntaxError) }
|
||||
fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::SyntaxError) }
|
||||
fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::SyntaxError) }
|
||||
#[inline]
|
||||
fn read_char(&mut self) -> Result<char, Error> {
|
||||
match self.stack.pop() {
|
||||
Some(CharState(c)) => Ok(c),
|
||||
_ => Err(Error::SyntaxError),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn read_str(&mut self) -> Result<String, Error> {
|
||||
match self.stack.pop() {
|
||||
Some(StringState(value)) => Ok(value),
|
||||
_ => Err(Error::SyntaxError),
|
||||
}
|
||||
}
|
||||
|
||||
// Compound types:
|
||||
fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_struct<T, F>(&mut self, s_name: &str, _len: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
match self.stack.pop() {
|
||||
Some(OuterState(Outer { inner })) => {
|
||||
if s_name == "Outer" {
|
||||
self.stack.push(VecState(inner));
|
||||
self.stack.push(FieldState("inner"));
|
||||
f(self)
|
||||
} else {
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
}
|
||||
Some(InnerState(Inner { a: (), b, c })) => {
|
||||
if s_name == "Inner" {
|
||||
self.stack.push(MapState(c));
|
||||
self.stack.push(FieldState("c"));
|
||||
|
||||
self.stack.push(UsizeState(b));
|
||||
self.stack.push(FieldState("b"));
|
||||
|
||||
self.stack.push(NullState);
|
||||
self.stack.push(FieldState("a"));
|
||||
f(self)
|
||||
} else {
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
}
|
||||
_ => Err(Error::SyntaxError),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn read_struct_field<T, F>(&mut self, f_name: &str, _f_idx: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
match self.stack.pop() {
|
||||
Some(FieldState(name)) => {
|
||||
if f_name == name {
|
||||
f(self)
|
||||
} else {
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
}
|
||||
_ => Err(Error::SyntaxError)
|
||||
}
|
||||
}
|
||||
|
||||
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
// Specialized types:
|
||||
#[inline]
|
||||
fn read_option<T, F>(&mut self, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder, bool) -> Result<T, Error>,
|
||||
{
|
||||
match self.stack.pop() {
|
||||
Some(OptionState(b)) => f(self, b),
|
||||
_ => Err(Error::SyntaxError),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_seq<T, F>(&mut self, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
match self.stack.pop() {
|
||||
Some(VecState(value)) => {
|
||||
let len = value.len();
|
||||
for inner in value.into_iter().rev() {
|
||||
self.stack.push(InnerState(inner));
|
||||
}
|
||||
f(self, len)
|
||||
}
|
||||
_ => Err(Error::SyntaxError)
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
f(self)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_map<T, F>(&mut self, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
match self.stack.pop() {
|
||||
Some(MapState(map)) => {
|
||||
let len = map.len();
|
||||
for (key, value) in map {
|
||||
match value {
|
||||
Some(c) => {
|
||||
self.stack.push(CharState(c));
|
||||
self.stack.push(OptionState(true));
|
||||
}
|
||||
None => {
|
||||
self.stack.push(OptionState(false));
|
||||
}
|
||||
}
|
||||
self.stack.push(StringState(key));
|
||||
}
|
||||
f(self, len)
|
||||
}
|
||||
_ => Err(Error::SyntaxError),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
f(self)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
f(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
mod deserializer {
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map;
|
||||
use std::vec;
|
||||
use super::{Outer, Inner};
|
||||
use super::Error;
|
||||
use serde::de;
|
||||
|
||||
#[derive(Debug)]
|
||||
enum State {
|
||||
OuterState(Outer),
|
||||
InnerState(Inner),
|
||||
StrState(&'static str),
|
||||
NullState,
|
||||
UsizeState(usize),
|
||||
CharState(char),
|
||||
StringState(String),
|
||||
OptionState(bool),
|
||||
VecState(Vec<Inner>),
|
||||
MapState(HashMap<String, Option<char>>),
|
||||
}
|
||||
|
||||
pub struct OuterDeserializer {
|
||||
stack: Vec<State>,
|
||||
}
|
||||
|
||||
impl OuterDeserializer {
|
||||
#[inline]
|
||||
pub fn new(outer: Outer) -> OuterDeserializer {
|
||||
OuterDeserializer {
|
||||
stack: vec!(State::OuterState(outer)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl de::Deserializer for OuterDeserializer {
|
||||
type Error = Error;
|
||||
|
||||
fn visit<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
match self.stack.pop() {
|
||||
Some(State::OuterState(Outer { inner })) => {
|
||||
self.stack.push(State::VecState(inner));
|
||||
self.stack.push(State::StrState("inner"));
|
||||
|
||||
visitor.visit_named_map("Outer", OuterMapVisitor {
|
||||
de: self,
|
||||
state: 0,
|
||||
})
|
||||
}
|
||||
Some(State::InnerState(Inner { a: (), b, c })) => {
|
||||
self.stack.push(State::MapState(c));
|
||||
self.stack.push(State::StrState("c"));
|
||||
|
||||
self.stack.push(State::UsizeState(b));
|
||||
self.stack.push(State::StrState("b"));
|
||||
|
||||
self.stack.push(State::NullState);
|
||||
self.stack.push(State::StrState("a"));
|
||||
|
||||
visitor.visit_named_map("Inner", InnerMapVisitor {
|
||||
de: self,
|
||||
state: 0,
|
||||
})
|
||||
}
|
||||
Some(State::VecState(value)) => {
|
||||
visitor.visit_seq(OuterSeqVisitor {
|
||||
de: self,
|
||||
iter: value.into_iter(),
|
||||
})
|
||||
}
|
||||
Some(State::MapState(value)) => {
|
||||
visitor.visit_map(MapVisitor {
|
||||
de: self,
|
||||
iter: value.into_iter(),
|
||||
})
|
||||
}
|
||||
Some(State::NullState) => {
|
||||
visitor.visit_unit()
|
||||
}
|
||||
Some(State::UsizeState(x)) => {
|
||||
visitor.visit_usize(x)
|
||||
}
|
||||
Some(State::CharState(x)) => {
|
||||
visitor.visit_char(x)
|
||||
}
|
||||
Some(State::StrState(x)) => {
|
||||
visitor.visit_str(x)
|
||||
}
|
||||
Some(State::StringState(x)) => {
|
||||
visitor.visit_string(x)
|
||||
}
|
||||
Some(State::OptionState(false)) => {
|
||||
visitor.visit_none()
|
||||
}
|
||||
Some(State::OptionState(true)) => {
|
||||
visitor.visit_some(self)
|
||||
}
|
||||
None => Err(Error::EndOfStream),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct OuterMapVisitor<'a> {
|
||||
de: &'a mut OuterDeserializer,
|
||||
state: usize,
|
||||
}
|
||||
|
||||
impl<'a> de::MapVisitor for OuterMapVisitor<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
|
||||
where K: de::Deserialize,
|
||||
{
|
||||
match self.state {
|
||||
0 => {
|
||||
self.state += 1;
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
|
||||
}
|
||||
_ => {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_value<V>(&mut self) -> Result<V, Error>
|
||||
where V: de::Deserialize,
|
||||
{
|
||||
de::Deserialize::deserialize(self.de)
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
if self.state == 1 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = 1 - self.state;
|
||||
(len, Some(len))
|
||||
}
|
||||
}
|
||||
|
||||
struct OuterSeqVisitor<'a> {
|
||||
de: &'a mut OuterDeserializer,
|
||||
iter: vec::IntoIter<Inner>,
|
||||
}
|
||||
|
||||
impl<'a> de::SeqVisitor for OuterSeqVisitor<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit<T>(&mut self) -> Result<Option<T>, Error>
|
||||
where T: de::Deserialize,
|
||||
{
|
||||
match self.iter.next() {
|
||||
Some(value) => {
|
||||
self.de.stack.push(State::InnerState(value));
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
|
||||
}
|
||||
None => {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
match self.iter.next() {
|
||||
Some(_) => Err(Error::SyntaxError),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
self.iter.size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
struct InnerMapVisitor<'a> {
|
||||
de: &'a mut OuterDeserializer,
|
||||
state: usize,
|
||||
}
|
||||
|
||||
impl<'a> de::MapVisitor for InnerMapVisitor<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
|
||||
where K: de::Deserialize,
|
||||
{
|
||||
match self.state {
|
||||
0 ... 2 => {
|
||||
self.state += 1;
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
|
||||
}
|
||||
_ => {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_value<V>(&mut self) -> Result<V, Error>
|
||||
where V: de::Deserialize,
|
||||
{
|
||||
de::Deserialize::deserialize(self.de)
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
if self.state == 1 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = 1 - self.state;
|
||||
(len, Some(len))
|
||||
}
|
||||
}
|
||||
|
||||
struct MapVisitor<'a> {
|
||||
de: &'a mut OuterDeserializer,
|
||||
iter: hash_map::IntoIter<String, Option<char>>,
|
||||
}
|
||||
|
||||
impl<'a> de::MapVisitor for MapVisitor<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
|
||||
where K: de::Deserialize,
|
||||
{
|
||||
match self.iter.next() {
|
||||
Some((key, Some(value))) => {
|
||||
self.de.stack.push(State::CharState(value));
|
||||
self.de.stack.push(State::OptionState(true));
|
||||
self.de.stack.push(State::StringState(key));
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
|
||||
}
|
||||
Some((key, None)) => {
|
||||
self.de.stack.push(State::OptionState(false));
|
||||
self.de.stack.push(State::StringState(key));
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
|
||||
}
|
||||
None => {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_value<V>(&mut self) -> Result<V, Error>
|
||||
where V: de::Deserialize,
|
||||
{
|
||||
de::Deserialize::deserialize(self.de)
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
match self.iter.next() {
|
||||
Some(_) => Err(Error::SyntaxError),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
self.iter.size_hint()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_0_0(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let mut map = HashMap::new();
|
||||
map.insert("abc".to_string(), Some('c'));
|
||||
|
||||
let outer = Outer {
|
||||
inner: vec!(),
|
||||
};
|
||||
|
||||
let mut d = decoder::OuterDecoder::new(outer.clone());
|
||||
let value: Outer = Decodable::decode(&mut d).unwrap();
|
||||
|
||||
assert_eq!(value, outer);
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_1_0(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let map = HashMap::new();
|
||||
|
||||
let outer = Outer {
|
||||
inner: vec!(
|
||||
Inner {
|
||||
a: (),
|
||||
b: 5,
|
||||
c: map,
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
let mut d = decoder::OuterDecoder::new(outer.clone());
|
||||
let value: Outer = Decodable::decode(&mut d).unwrap();
|
||||
|
||||
assert_eq!(value, outer);
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_1_5(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let mut map = HashMap::new();
|
||||
map.insert("1".to_string(), Some('a'));
|
||||
map.insert("2".to_string(), None);
|
||||
map.insert("3".to_string(), Some('b'));
|
||||
map.insert("4".to_string(), None);
|
||||
map.insert("5".to_string(), Some('c'));
|
||||
|
||||
let outer = Outer {
|
||||
inner: vec!(
|
||||
Inner {
|
||||
a: (),
|
||||
b: 5,
|
||||
c: map,
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
let mut d = decoder::OuterDecoder::new(outer.clone());
|
||||
let value: Outer = Decodable::decode(&mut d).unwrap();
|
||||
|
||||
assert_eq!(value, outer);
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_0_0(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let outer = Outer {
|
||||
inner: vec!(),
|
||||
};
|
||||
|
||||
let mut d = deserializer::OuterDeserializer::new(outer.clone());
|
||||
let value: Outer = Deserialize::deserialize(&mut d).unwrap();
|
||||
|
||||
assert_eq!(value, outer);
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_1_0(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let map = HashMap::new();
|
||||
|
||||
let outer = Outer {
|
||||
inner: vec!(
|
||||
Inner {
|
||||
a: (),
|
||||
b: 5,
|
||||
c: map,
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
let mut d = deserializer::OuterDeserializer::new(outer.clone());
|
||||
let value: Outer = Deserialize::deserialize(&mut d).unwrap();
|
||||
|
||||
assert_eq!(value, outer);
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_1_5(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let mut map = HashMap::new();
|
||||
map.insert("1".to_string(), Some('a'));
|
||||
map.insert("2".to_string(), None);
|
||||
map.insert("3".to_string(), Some('b'));
|
||||
map.insert("4".to_string(), None);
|
||||
map.insert("5".to_string(), Some('c'));
|
||||
|
||||
let outer = Outer {
|
||||
inner: vec!(
|
||||
Inner {
|
||||
a: (),
|
||||
b: 5,
|
||||
c: map,
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
let mut d = deserializer::OuterDeserializer::new(outer.clone());
|
||||
let value: Outer = Deserialize::deserialize(&mut d).unwrap();
|
||||
|
||||
assert_eq!(value, outer);
|
||||
})
|
||||
}
|
||||
@@ -1,615 +0,0 @@
|
||||
#![feature(core, plugin, test)]
|
||||
#![plugin(serde_macros)]
|
||||
|
||||
extern crate serde;
|
||||
extern crate "rustc-serialize" as rustc_serialize;
|
||||
extern crate test;
|
||||
|
||||
use std::fmt::Debug;
|
||||
use test::Bencher;
|
||||
|
||||
use rustc_serialize::{Decoder, Decodable};
|
||||
|
||||
use serde::de::{Deserializer, Deserialize};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
pub enum Error {
|
||||
EndOfStreamError,
|
||||
SyntaxError,
|
||||
}
|
||||
|
||||
impl serde::de::Error for Error {
|
||||
fn syntax_error() -> Error { Error::SyntaxError }
|
||||
|
||||
fn end_of_stream_error() -> Error { Error::EndOfStreamError }
|
||||
|
||||
fn missing_field_error(_: &'static str) -> Error { Error::SyntaxError }
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
mod decoder {
|
||||
use std::vec;
|
||||
use rustc_serialize;
|
||||
|
||||
use super::Error;
|
||||
|
||||
pub struct UsizeDecoder {
|
||||
len: usize,
|
||||
iter: vec::IntoIter<usize>,
|
||||
}
|
||||
|
||||
impl UsizeDecoder {
|
||||
#[inline]
|
||||
pub fn new(values: Vec<usize>) -> UsizeDecoder {
|
||||
UsizeDecoder {
|
||||
len: values.len(),
|
||||
iter: values.into_iter(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl rustc_serialize::Decoder for UsizeDecoder {
|
||||
type Error = Error;
|
||||
|
||||
fn error(&mut self, _: &str) -> Error { Error::SyntaxError }
|
||||
|
||||
// Primitive types:
|
||||
fn read_nil(&mut self) -> Result<(), Error> { Err(Error::SyntaxError) }
|
||||
#[inline]
|
||||
fn read_usize(&mut self) -> Result<usize, Error> {
|
||||
match self.iter.next() {
|
||||
Some(value) => Ok(value),
|
||||
None => Err(Error::EndOfStreamError),
|
||||
}
|
||||
}
|
||||
fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::SyntaxError) }
|
||||
fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::SyntaxError) }
|
||||
fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::SyntaxError) }
|
||||
fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::SyntaxError) }
|
||||
fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::SyntaxError) }
|
||||
fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::SyntaxError) }
|
||||
fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::SyntaxError) }
|
||||
fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::SyntaxError) }
|
||||
fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::SyntaxError) }
|
||||
fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::SyntaxError) }
|
||||
fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::SyntaxError) }
|
||||
fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::SyntaxError) }
|
||||
fn read_char(&mut self) -> Result<char, Error> { Err(Error::SyntaxError) }
|
||||
fn read_str(&mut self) -> Result<String, Error> { Err(Error::SyntaxError) }
|
||||
|
||||
// Compound types:
|
||||
fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
// Specialized types:
|
||||
fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder, bool) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_seq<T, F>(&mut self, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
let len = self.len;
|
||||
f(self, len)
|
||||
}
|
||||
#[inline]
|
||||
fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
f(self)
|
||||
}
|
||||
|
||||
fn read_map<T, F>(&mut self, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_map_elt_key<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_map_elt_val<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub struct U8Decoder {
|
||||
len: usize,
|
||||
iter: vec::IntoIter<u8>,
|
||||
}
|
||||
|
||||
impl U8Decoder {
|
||||
#[inline]
|
||||
pub fn new(values: Vec<u8>) -> U8Decoder {
|
||||
U8Decoder {
|
||||
len: values.len(),
|
||||
iter: values.into_iter(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl rustc_serialize::Decoder for U8Decoder {
|
||||
type Error = Error;
|
||||
|
||||
fn error(&mut self, _: &str) -> Error { Error::SyntaxError }
|
||||
|
||||
// Primitive types:
|
||||
fn read_nil(&mut self) -> Result<(), Error> { Err(Error::SyntaxError) }
|
||||
fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::SyntaxError) }
|
||||
fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::SyntaxError) }
|
||||
fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::SyntaxError) }
|
||||
fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::SyntaxError) }
|
||||
#[inline]
|
||||
fn read_u8(&mut self) -> Result<u8, Error> {
|
||||
match self.iter.next() {
|
||||
Some(value) => Ok(value),
|
||||
None => Err(Error::EndOfStreamError),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::SyntaxError) }
|
||||
fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::SyntaxError) }
|
||||
fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::SyntaxError) }
|
||||
fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::SyntaxError) }
|
||||
fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::SyntaxError) }
|
||||
fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::SyntaxError) }
|
||||
fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::SyntaxError) }
|
||||
fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::SyntaxError) }
|
||||
fn read_char(&mut self) -> Result<char, Error> { Err(Error::SyntaxError) }
|
||||
fn read_str(&mut self) -> Result<String, Error> { Err(Error::SyntaxError) }
|
||||
|
||||
// Compound types:
|
||||
fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
// Specialized types:
|
||||
fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder, bool) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_seq<T, F>(&mut self, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
let len = self.len;
|
||||
f(self, len)
|
||||
}
|
||||
#[inline]
|
||||
fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
f(self)
|
||||
}
|
||||
|
||||
fn read_map<T, F>(&mut self, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_map_elt_key<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn read_map_elt_val<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
mod deserializer {
|
||||
//use std::num;
|
||||
use std::vec;
|
||||
|
||||
use super::Error;
|
||||
|
||||
use serde::de;
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
enum State {
|
||||
StartState,
|
||||
SepOrEndState,
|
||||
EndState,
|
||||
}
|
||||
|
||||
pub struct Deserializer<A> {
|
||||
state: State,
|
||||
iter: vec::IntoIter<A>,
|
||||
len: usize,
|
||||
value: Option<A>,
|
||||
}
|
||||
|
||||
impl<A> Deserializer<A> {
|
||||
#[inline]
|
||||
pub fn new(values: Vec<A>) -> Deserializer<A> {
|
||||
let len = values.len();
|
||||
Deserializer {
|
||||
state: State::StartState,
|
||||
iter: values.into_iter(),
|
||||
len: len,
|
||||
value: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl de::Deserializer for Deserializer<usize> {
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn visit<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
match self.state {
|
||||
State::StartState => {
|
||||
self.state = State::SepOrEndState;
|
||||
visitor.visit_seq(self)
|
||||
}
|
||||
State::SepOrEndState => {
|
||||
visitor.visit_usize(self.value.take().unwrap())
|
||||
}
|
||||
State::EndState => {
|
||||
Err(Error::EndOfStreamError)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl de::SeqVisitor for Deserializer<usize> {
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn visit<T>(&mut self) -> Result<Option<T>, Error>
|
||||
where T: de::Deserialize,
|
||||
{
|
||||
match self.iter.next() {
|
||||
Some(value) => {
|
||||
self.len -= 1;
|
||||
self.value = Some(value);
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self))))
|
||||
}
|
||||
None => {
|
||||
self.state = State::EndState;
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
match self.iter.next() {
|
||||
Some(_) => Err(Error::SyntaxError),
|
||||
None => {
|
||||
self.state = State::EndState;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(self.len, Some(self.len))
|
||||
}
|
||||
}
|
||||
|
||||
impl de::Deserializer for Deserializer<u8> {
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn visit<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
match self.state {
|
||||
State::StartState => {
|
||||
self.state = State::SepOrEndState;
|
||||
visitor.visit_seq(self)
|
||||
}
|
||||
State::SepOrEndState => {
|
||||
visitor.visit_u8(self.value.take().unwrap())
|
||||
}
|
||||
State::EndState => {
|
||||
Err(Error::EndOfStreamError)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl de::SeqVisitor for Deserializer<u8> {
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn visit<T>(&mut self) -> Result<Option<T>, Error>
|
||||
where T: de::Deserialize,
|
||||
{
|
||||
match self.iter.next() {
|
||||
Some(value) => {
|
||||
self.len -= 1;
|
||||
self.value = Some(value);
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self))))
|
||||
}
|
||||
None => {
|
||||
self.state = State::EndState;
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
match self.iter.next() {
|
||||
Some(_) => Err(Error::SyntaxError),
|
||||
None => {
|
||||
self.state = State::EndState;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(self.len, Some(self.len))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
fn run_decoder<
|
||||
D: Decoder<Error=Error>,
|
||||
T: Clone + PartialEq + Debug + Decodable
|
||||
>(mut d: D, value: T) {
|
||||
let v = Decodable::decode(&mut d);
|
||||
|
||||
assert_eq!(Ok(value), v);
|
||||
}
|
||||
|
||||
fn run_deserializer<
|
||||
D: Deserializer<Error=E>,
|
||||
E: Debug,
|
||||
T: Clone + PartialEq + Debug + Deserialize
|
||||
>(mut d: D, value: T) {
|
||||
let v: T = Deserialize::deserialize(&mut d).unwrap();
|
||||
|
||||
assert_eq!(value, v);
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_usize_000(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<usize> = vec!();
|
||||
run_decoder(decoder::UsizeDecoder::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_usize_003(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<usize> = vec!(1, 2, 3);
|
||||
run_decoder(decoder::UsizeDecoder::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_usize_100(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<usize> = range(0, 100).collect();
|
||||
run_decoder(decoder::UsizeDecoder::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_u8_000(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<u8> = vec!();
|
||||
run_decoder(decoder::U8Decoder::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_u8_003(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<u8> = vec!(1, 2, 3);
|
||||
run_decoder(decoder::U8Decoder::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_u8_100(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<u8> = range(0u8, 100).collect();
|
||||
run_decoder(decoder::U8Decoder::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_usize_000(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<usize> = vec!();
|
||||
run_deserializer(deserializer::Deserializer::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_usize_003(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<usize> = vec!(1, 2, 3);
|
||||
run_deserializer(deserializer::Deserializer::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_usize_100(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<usize> = range(0, 100).collect();
|
||||
run_deserializer(deserializer::Deserializer::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_u8_000(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<u8> = vec!();
|
||||
run_deserializer(deserializer::Deserializer::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_u8_003(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<u8> = vec!(1, 2, 3);
|
||||
run_deserializer(deserializer::Deserializer::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_u8_100(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<u8> = range(0u8, 100).collect();
|
||||
run_deserializer(deserializer::Deserializer::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
[package]
|
||||
name = "serde"
|
||||
version = "0.9.7"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "A generic serialization/deserialization framework"
|
||||
homepage = "https://serde.rs"
|
||||
repository = "https://github.com/serde-rs/serde"
|
||||
documentation = "https://docs.serde.rs/serde/"
|
||||
readme = "../README.md"
|
||||
keywords = ["serde", "serialization", "no_std"]
|
||||
categories = ["encoding"]
|
||||
include = ["Cargo.toml", "src/**/*.rs"]
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "serde-rs/serde" }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
|
||||
std = []
|
||||
unstable = []
|
||||
alloc = ["unstable"]
|
||||
collections = ["alloc"]
|
||||
unstable-testing = ["unstable", "std"]
|
||||
|
||||
# to get serde_derive picked up by play.integer32.com
|
||||
playground = ["serde_derive"]
|
||||
|
||||
[dependencies]
|
||||
serde_derive = { version = "0.9", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_derive = "0.9"
|
||||
@@ -0,0 +1,310 @@
|
||||
//! Wrapper types to enable optimized handling of `&[u8]` and `Vec<u8>`.
|
||||
//!
|
||||
//! Without specialization, Rust forces us to treat `&[u8]` just like any other
|
||||
//! slice and `Vec<u8>` just like any other vector. In reality this particular
|
||||
//! slice and vector can often be serialized and deserialized in a more
|
||||
//! efficient, compact representation in many formats.
|
||||
//!
|
||||
//! When working with such a format, you can opt into specialized handling of
|
||||
//! `&[u8]` by wrapping it in `bytes::Bytes` and `Vec<u8>` by wrapping it in
|
||||
//! `bytes::ByteBuf`.
|
||||
//!
|
||||
//! Rust support for specialization is being tracked in
|
||||
//! [rust-lang/rust#31844][specialization]. Once it lands in the stable compiler
|
||||
//! we will be deprecating these wrapper types in favor of optimizing `&[u8]`
|
||||
//! and `Vec<u8>` out of the box.
|
||||
//!
|
||||
//! [specialization]: https://github.com/rust-lang/rust/issues/31844
|
||||
|
||||
use core::{ops, fmt, char, iter, slice};
|
||||
use core::fmt::Write;
|
||||
|
||||
use ser;
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
pub use self::bytebuf::ByteBuf;
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[doc(hidden)] // does anybody need this?
|
||||
pub use self::bytebuf::ByteBufVisitor;
|
||||
|
||||
#[cfg(feature = "collections")]
|
||||
use collections::Vec;
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// Wraps a `&[u8]` in order to serialize in an efficient way. Does not support
|
||||
/// deserialization.
|
||||
///
|
||||
/// ```rust
|
||||
/// # #[macro_use] extern crate serde_derive;
|
||||
/// # extern crate serde;
|
||||
/// # use std::net::IpAddr;
|
||||
/// #
|
||||
/// use serde::bytes::Bytes;
|
||||
///
|
||||
/// # #[allow(dead_code)]
|
||||
/// #[derive(Serialize)]
|
||||
/// struct Packet<'a> {
|
||||
/// destination: IpAddr,
|
||||
/// payload: Bytes<'a>,
|
||||
/// }
|
||||
/// #
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
#[derive(Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
|
||||
pub struct Bytes<'a> {
|
||||
bytes: &'a [u8],
|
||||
}
|
||||
|
||||
impl<'a> Bytes<'a> {
|
||||
/// Wrap an existing `&[u8]`.
|
||||
pub fn new(bytes: &'a [u8]) -> Self {
|
||||
Bytes {
|
||||
bytes: bytes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> fmt::Debug for Bytes<'a> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
try!(f.write_str("b\""));
|
||||
for c in escape_bytestring(self.bytes) {
|
||||
try!(f.write_char(c));
|
||||
}
|
||||
f.write_char('"')
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<&'a [u8]> for Bytes<'a> {
|
||||
fn from(bytes: &'a [u8]) -> Self {
|
||||
Bytes::new(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<'a> From<&'a Vec<u8>> for Bytes<'a> {
|
||||
fn from(bytes: &'a Vec<u8>) -> Self {
|
||||
Bytes::new(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Into<&'a [u8]> for Bytes<'a> {
|
||||
fn into(self) -> &'a [u8] {
|
||||
self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ops::Deref for Bytes<'a> {
|
||||
type Target = [u8];
|
||||
|
||||
fn deref(&self) -> &[u8] { self.bytes }
|
||||
}
|
||||
|
||||
impl<'a> ser::Serialize for Bytes<'a> {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: ser::Serializer
|
||||
{
|
||||
serializer.serialize_bytes(self.bytes)
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
mod bytebuf {
|
||||
use core::ops;
|
||||
use core::fmt;
|
||||
use core::fmt::Write;
|
||||
|
||||
use ser;
|
||||
use de;
|
||||
|
||||
#[cfg(feature = "collections")]
|
||||
use collections::{String, Vec};
|
||||
|
||||
/// Wraps a `Vec<u8>` in order to serialize and deserialize in an efficient
|
||||
/// way.
|
||||
///
|
||||
/// ```rust
|
||||
/// # #[macro_use] extern crate serde_derive;
|
||||
/// # extern crate serde;
|
||||
/// # use std::net::IpAddr;
|
||||
/// #
|
||||
/// use serde::bytes::ByteBuf;
|
||||
///
|
||||
/// # #[allow(dead_code)]
|
||||
/// #[derive(Serialize, Deserialize)]
|
||||
/// struct Packet {
|
||||
/// destination: IpAddr,
|
||||
/// payload: ByteBuf,
|
||||
/// }
|
||||
/// #
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
#[derive(Clone, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
|
||||
pub struct ByteBuf {
|
||||
bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
impl ByteBuf {
|
||||
/// Construct a new, empty `ByteBuf`.
|
||||
pub fn new() -> Self {
|
||||
ByteBuf::from(Vec::new())
|
||||
}
|
||||
|
||||
/// Construct a new, empty `ByteBuf` with the specified capacity.
|
||||
pub fn with_capacity(cap: usize) -> Self {
|
||||
ByteBuf::from(Vec::with_capacity(cap))
|
||||
}
|
||||
|
||||
/// Wrap existing bytes in a `ByteBuf`.
|
||||
pub fn from<T: Into<Vec<u8>>>(bytes: T) -> Self {
|
||||
ByteBuf {
|
||||
bytes: bytes.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ByteBuf {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
try!(f.write_str("b\""));
|
||||
for c in super::escape_bytestring(self.bytes.as_ref()) {
|
||||
try!(f.write_char(c));
|
||||
}
|
||||
f.write_char('"')
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<Vec<u8>> for ByteBuf {
|
||||
fn into(self) -> Vec<u8> {
|
||||
self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Vec<u8>> for ByteBuf {
|
||||
fn from(bytes: Vec<u8>) -> Self {
|
||||
ByteBuf::from(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<Vec<u8>> for ByteBuf {
|
||||
fn as_ref(&self) -> &Vec<u8> {
|
||||
&self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<[u8]> for ByteBuf {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
&self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
impl AsMut<Vec<u8>> for ByteBuf {
|
||||
fn as_mut(&mut self) -> &mut Vec<u8> {
|
||||
&mut self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
impl AsMut<[u8]> for ByteBuf {
|
||||
fn as_mut(&mut self) -> &mut [u8] {
|
||||
&mut self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
impl ops::Deref for ByteBuf {
|
||||
type Target = [u8];
|
||||
|
||||
fn deref(&self) -> &[u8] { &self.bytes[..] }
|
||||
}
|
||||
|
||||
impl ops::DerefMut for ByteBuf {
|
||||
fn deref_mut(&mut self) -> &mut [u8] { &mut self.bytes[..] }
|
||||
}
|
||||
|
||||
impl ser::Serialize for ByteBuf {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: ser::Serializer
|
||||
{
|
||||
serializer.serialize_bytes(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// This type implements the `serde::de::Visitor` trait for a `ByteBuf`.
|
||||
pub struct ByteBufVisitor;
|
||||
|
||||
impl de::Visitor for ByteBufVisitor {
|
||||
type Value = ByteBuf;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
formatter.write_str("byte array")
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_unit<E>(self) -> Result<ByteBuf, E>
|
||||
where E: de::Error,
|
||||
{
|
||||
Ok(ByteBuf::new())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_seq<V>(self, mut visitor: V) -> Result<ByteBuf, V::Error>
|
||||
where V: de::SeqVisitor,
|
||||
{
|
||||
let (len, _) = visitor.size_hint();
|
||||
let mut values = Vec::with_capacity(len);
|
||||
|
||||
while let Some(value) = try!(visitor.visit()) {
|
||||
values.push(value);
|
||||
}
|
||||
|
||||
Ok(ByteBuf::from(values))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_bytes<E>(self, v: &[u8]) -> Result<ByteBuf, E>
|
||||
where E: de::Error,
|
||||
{
|
||||
Ok(ByteBuf::from(v))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<ByteBuf, E>
|
||||
where E: de::Error,
|
||||
{
|
||||
Ok(ByteBuf::from(v))
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, v: &str) -> Result<ByteBuf, E>
|
||||
where E: de::Error,
|
||||
{
|
||||
Ok(ByteBuf::from(v))
|
||||
}
|
||||
|
||||
fn visit_string<E>(self, v: String) -> Result<ByteBuf, E>
|
||||
where E: de::Error,
|
||||
{
|
||||
Ok(ByteBuf::from(v))
|
||||
}
|
||||
}
|
||||
|
||||
impl de::Deserialize for ByteBuf {
|
||||
#[inline]
|
||||
fn deserialize<D>(deserializer: D) -> Result<ByteBuf, D::Error>
|
||||
where D: de::Deserializer
|
||||
{
|
||||
deserializer.deserialize_byte_buf(ByteBufVisitor)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[inline]
|
||||
fn escape_bytestring<'a>(bytes: &'a [u8]) -> iter::FlatMap<slice::Iter<'a, u8>, char::EscapeDefault, fn(&u8) -> char::EscapeDefault> {
|
||||
fn f(b: &u8) -> char::EscapeDefault {
|
||||
char::from_u32(*b as u32).unwrap().escape_default()
|
||||
}
|
||||
bytes.iter().flat_map(f as fn(&u8) -> char::EscapeDefault)
|
||||
}
|
||||
@@ -0,0 +1,761 @@
|
||||
// This module is doc(hidden) and nothing here should be used outside of
|
||||
// generated code.
|
||||
//
|
||||
// We will iterate on the implementation for a few releases and only have to
|
||||
// worry about backward compatibility for the `untagged` and `tag` attributes
|
||||
// rather than for this entire mechanism.
|
||||
//
|
||||
// This issue is tracking making some of this stuff public:
|
||||
// https://github.com/serde-rs/serde/issues/741
|
||||
|
||||
#![doc(hidden)]
|
||||
|
||||
use core::fmt;
|
||||
use core::marker::PhantomData;
|
||||
|
||||
#[cfg(all(not(feature = "std"), feature = "collections"))]
|
||||
use collections::{String, Vec};
|
||||
|
||||
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||
use alloc::boxed::Box;
|
||||
|
||||
use de::{
|
||||
self,
|
||||
Deserialize,
|
||||
DeserializeSeed,
|
||||
Deserializer,
|
||||
Visitor,
|
||||
SeqVisitor,
|
||||
MapVisitor,
|
||||
EnumVisitor,
|
||||
};
|
||||
|
||||
/// Used from generated code to buffer the contents of the Deserializer when
|
||||
/// deserializing untagged enums and internally tagged enums.
|
||||
///
|
||||
/// Not public API. Use serde-value instead.
|
||||
#[derive(Debug)]
|
||||
pub enum Content {
|
||||
// Don't mind the PhantomData, just need to use E somewhere.
|
||||
Bool(bool),
|
||||
|
||||
U8(u8),
|
||||
U16(u16),
|
||||
U32(u32),
|
||||
U64(u64),
|
||||
|
||||
I8(i8),
|
||||
I16(i16),
|
||||
I32(i32),
|
||||
I64(i64),
|
||||
|
||||
F32(f32),
|
||||
F64(f64),
|
||||
|
||||
Char(char),
|
||||
String(String),
|
||||
Bytes(Vec<u8>),
|
||||
|
||||
None,
|
||||
Some(Box<Content>),
|
||||
|
||||
Unit,
|
||||
Newtype(Box<Content>),
|
||||
Seq(Vec<Content>),
|
||||
Map(Vec<(Content, Content)>),
|
||||
}
|
||||
|
||||
impl Deserialize for Content {
|
||||
fn deserialize<D: Deserializer>(deserializer: D) -> Result<Self, D::Error> {
|
||||
// Untagged and internally tagged enums are only supported in
|
||||
// self-describing formats.
|
||||
deserializer.deserialize(ContentVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
struct ContentVisitor;
|
||||
|
||||
impl Visitor for ContentVisitor {
|
||||
type Value = Content;
|
||||
|
||||
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
fmt.write_str("any value")
|
||||
}
|
||||
|
||||
fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::Bool(value))
|
||||
}
|
||||
|
||||
fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::I8(value))
|
||||
}
|
||||
|
||||
fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::I16(value))
|
||||
}
|
||||
|
||||
fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::I32(value))
|
||||
}
|
||||
|
||||
fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::I64(value))
|
||||
}
|
||||
|
||||
fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::U8(value))
|
||||
}
|
||||
|
||||
fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::U16(value))
|
||||
}
|
||||
|
||||
fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::U32(value))
|
||||
}
|
||||
|
||||
fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::U64(value))
|
||||
}
|
||||
|
||||
fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::F32(value))
|
||||
}
|
||||
|
||||
fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::F64(value))
|
||||
}
|
||||
|
||||
fn visit_char<F>(self, value: char) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::Char(value))
|
||||
}
|
||||
|
||||
fn visit_str<F>(self, value: &str) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::String(value.into()))
|
||||
}
|
||||
|
||||
fn visit_string<F>(self, value: String) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::String(value))
|
||||
}
|
||||
|
||||
fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::Bytes(value.into()))
|
||||
}
|
||||
|
||||
fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::Bytes(value))
|
||||
}
|
||||
|
||||
fn visit_unit<F>(self) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::Unit)
|
||||
}
|
||||
|
||||
fn visit_none<F>(self) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::None)
|
||||
}
|
||||
|
||||
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where D: Deserializer
|
||||
{
|
||||
Deserialize::deserialize(deserializer).map(|v| Content::Some(Box::new(v)))
|
||||
}
|
||||
|
||||
fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where D: Deserializer
|
||||
{
|
||||
Deserialize::deserialize(deserializer).map(|v| Content::Newtype(Box::new(v)))
|
||||
}
|
||||
|
||||
fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: SeqVisitor
|
||||
{
|
||||
let mut vec = Vec::with_capacity(visitor.size_hint().0);
|
||||
while let Some(e) = try!(visitor.visit()) {
|
||||
vec.push(e);
|
||||
}
|
||||
Ok(Content::Seq(vec))
|
||||
}
|
||||
|
||||
fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: MapVisitor
|
||||
{
|
||||
let mut vec = Vec::with_capacity(visitor.size_hint().0);
|
||||
while let Some(kv) = try!(visitor.visit()) {
|
||||
vec.push(kv);
|
||||
}
|
||||
Ok(Content::Map(vec))
|
||||
}
|
||||
|
||||
fn visit_enum<V>(self, _visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: EnumVisitor
|
||||
{
|
||||
Err(de::Error::custom("untagged and internally tagged enums do not support enum input"))
|
||||
}
|
||||
}
|
||||
|
||||
/// This is the type of the map keys in an internally tagged enum.
|
||||
///
|
||||
/// Not public API.
|
||||
pub enum TagOrContent {
|
||||
Tag,
|
||||
Content(Content),
|
||||
}
|
||||
|
||||
struct TagOrContentVisitor {
|
||||
name: &'static str,
|
||||
}
|
||||
|
||||
impl TagOrContentVisitor {
|
||||
fn new(name: &'static str) -> Self {
|
||||
TagOrContentVisitor {
|
||||
name: name,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DeserializeSeed for TagOrContentVisitor {
|
||||
type Value = TagOrContent;
|
||||
|
||||
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where D: Deserializer
|
||||
{
|
||||
// Internally tagged enums are only supported in self-describing
|
||||
// formats.
|
||||
deserializer.deserialize(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Visitor for TagOrContentVisitor {
|
||||
type Value = TagOrContent;
|
||||
|
||||
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(fmt, "a type tag `{}` or any other value", self.name)
|
||||
}
|
||||
|
||||
fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_bool(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_i8(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_i16(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_i32(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_i64(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_u8(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_u16(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_u32(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_u64(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_f32(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_f64(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_char<F>(self, value: char) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_char(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_str<F>(self, value: &str) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
if value == self.name {
|
||||
Ok(TagOrContent::Tag)
|
||||
} else {
|
||||
ContentVisitor.visit_str(value).map(TagOrContent::Content)
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_string<F>(self, value: String) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
if value == self.name {
|
||||
Ok(TagOrContent::Tag)
|
||||
} else {
|
||||
ContentVisitor.visit_string(value).map(TagOrContent::Content)
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
if value == self.name.as_bytes() {
|
||||
Ok(TagOrContent::Tag)
|
||||
} else {
|
||||
ContentVisitor.visit_bytes(value).map(TagOrContent::Content)
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
if value == self.name.as_bytes() {
|
||||
Ok(TagOrContent::Tag)
|
||||
} else {
|
||||
ContentVisitor.visit_byte_buf(value).map(TagOrContent::Content)
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_unit<F>(self) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_unit().map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_none<F>(self) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_none().map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where D: Deserializer
|
||||
{
|
||||
ContentVisitor.visit_some(deserializer).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where D: Deserializer
|
||||
{
|
||||
ContentVisitor.visit_newtype_struct(deserializer).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_seq<V>(self, visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: SeqVisitor
|
||||
{
|
||||
ContentVisitor.visit_seq(visitor).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_map<V>(self, visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: MapVisitor
|
||||
{
|
||||
ContentVisitor.visit_map(visitor).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_enum<V>(self, visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: EnumVisitor
|
||||
{
|
||||
ContentVisitor.visit_enum(visitor).map(TagOrContent::Content)
|
||||
}
|
||||
}
|
||||
|
||||
/// Used by generated code to deserialize an internally tagged enum.
|
||||
///
|
||||
/// Not public API.
|
||||
pub struct TaggedContent<T> {
|
||||
pub tag: T,
|
||||
pub content: Content,
|
||||
}
|
||||
|
||||
/// Not public API.
|
||||
pub struct TaggedContentVisitor<T> {
|
||||
tag_name: &'static str,
|
||||
tag: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T> TaggedContentVisitor<T> {
|
||||
/// Visitor for the content of an internally tagged enum with the given tag
|
||||
/// name.
|
||||
pub fn new(name: &'static str) -> Self {
|
||||
TaggedContentVisitor {
|
||||
tag_name: name,
|
||||
tag: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> DeserializeSeed for TaggedContentVisitor<T>
|
||||
where T: Deserialize
|
||||
{
|
||||
type Value = TaggedContent<T>;
|
||||
|
||||
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where D: Deserializer
|
||||
{
|
||||
// Internally tagged enums are only supported in self-describing
|
||||
// formats.
|
||||
deserializer.deserialize(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Visitor for TaggedContentVisitor<T>
|
||||
where T: Deserialize
|
||||
{
|
||||
type Value = TaggedContent<T>;
|
||||
|
||||
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
fmt.write_str("any value")
|
||||
}
|
||||
|
||||
fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: MapVisitor
|
||||
{
|
||||
let mut tag = None;
|
||||
let mut vec = Vec::with_capacity(visitor.size_hint().0);
|
||||
while let Some(k) = try!(visitor.visit_key_seed(TagOrContentVisitor::new(self.tag_name))) {
|
||||
match k {
|
||||
TagOrContent::Tag => {
|
||||
if tag.is_some() {
|
||||
return Err(de::Error::duplicate_field(self.tag_name));
|
||||
}
|
||||
tag = Some(try!(visitor.visit_value()));
|
||||
}
|
||||
TagOrContent::Content(k) => {
|
||||
let v = try!(visitor.visit_value());
|
||||
vec.push((k, v));
|
||||
}
|
||||
}
|
||||
}
|
||||
match tag {
|
||||
None => {
|
||||
Err(de::Error::missing_field(self.tag_name))
|
||||
}
|
||||
Some(tag) => {
|
||||
Ok(TaggedContent {
|
||||
tag: tag,
|
||||
content: Content::Map(vec),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Not public API
|
||||
pub struct ContentDeserializer<E> {
|
||||
content: Content,
|
||||
err: PhantomData<E>,
|
||||
}
|
||||
|
||||
/// Used when deserializing an internally tagged enum because the content will
|
||||
/// be used exactly once.
|
||||
impl<E> Deserializer for ContentDeserializer<E>
|
||||
where E: de::Error
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor
|
||||
{
|
||||
match self.content {
|
||||
Content::Bool(v) => visitor.visit_bool(v),
|
||||
Content::U8(v) => visitor.visit_u8(v),
|
||||
Content::U16(v) => visitor.visit_u16(v),
|
||||
Content::U32(v) => visitor.visit_u32(v),
|
||||
Content::U64(v) => visitor.visit_u64(v),
|
||||
Content::I8(v) => visitor.visit_i8(v),
|
||||
Content::I16(v) => visitor.visit_i16(v),
|
||||
Content::I32(v) => visitor.visit_i32(v),
|
||||
Content::I64(v) => visitor.visit_i64(v),
|
||||
Content::F32(v) => visitor.visit_f32(v),
|
||||
Content::F64(v) => visitor.visit_f64(v),
|
||||
Content::Char(v) => visitor.visit_char(v),
|
||||
Content::String(v) => visitor.visit_string(v),
|
||||
Content::Unit => visitor.visit_unit(),
|
||||
Content::None => visitor.visit_none(),
|
||||
Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)),
|
||||
Content::Newtype(v) => visitor.visit_newtype_struct(ContentDeserializer::new(*v)),
|
||||
Content::Seq(v) => {
|
||||
let seq = v.into_iter().map(ContentDeserializer::new);
|
||||
let mut seq_visitor = de::value::SeqDeserializer::new(seq);
|
||||
let value = try!(visitor.visit_seq(&mut seq_visitor));
|
||||
try!(seq_visitor.end());
|
||||
Ok(value)
|
||||
},
|
||||
Content::Map(v) => {
|
||||
let map = v.into_iter().map(|(k, v)| (ContentDeserializer::new(k), ContentDeserializer::new(v)));
|
||||
let mut map_visitor = de::value::MapDeserializer::new(map);
|
||||
let value = try!(visitor.visit_map(&mut map_visitor));
|
||||
try!(map_visitor.end());
|
||||
Ok(value)
|
||||
},
|
||||
Content::Bytes(v) => visitor.visit_byte_buf(v),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor
|
||||
{
|
||||
match self.content {
|
||||
Content::None => visitor.visit_none(),
|
||||
Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)),
|
||||
Content::Unit => visitor.visit_unit(),
|
||||
_ => visitor.visit_some(self)
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor
|
||||
{
|
||||
visitor.visit_newtype_struct(self)
|
||||
}
|
||||
|
||||
forward_to_deserialize! {
|
||||
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
|
||||
seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct
|
||||
struct_field tuple enum ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> ContentDeserializer<E> {
|
||||
/// private API, don't use
|
||||
pub fn new(content: Content) -> Self {
|
||||
ContentDeserializer {
|
||||
content: content,
|
||||
err: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Not public API.
|
||||
pub struct ContentRefDeserializer<'a, E> {
|
||||
content: &'a Content,
|
||||
err: PhantomData<E>,
|
||||
}
|
||||
|
||||
/// Used when deserializing an untagged enum because the content may need to be
|
||||
/// used more than once.
|
||||
impl<'a, E> Deserializer for ContentRefDeserializer<'a, E>
|
||||
where E: de::Error
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor
|
||||
{
|
||||
match *self.content {
|
||||
Content::Bool(v) => visitor.visit_bool(v),
|
||||
Content::U8(v) => visitor.visit_u8(v),
|
||||
Content::U16(v) => visitor.visit_u16(v),
|
||||
Content::U32(v) => visitor.visit_u32(v),
|
||||
Content::U64(v) => visitor.visit_u64(v),
|
||||
Content::I8(v) => visitor.visit_i8(v),
|
||||
Content::I16(v) => visitor.visit_i16(v),
|
||||
Content::I32(v) => visitor.visit_i32(v),
|
||||
Content::I64(v) => visitor.visit_i64(v),
|
||||
Content::F32(v) => visitor.visit_f32(v),
|
||||
Content::F64(v) => visitor.visit_f64(v),
|
||||
Content::Char(v) => visitor.visit_char(v),
|
||||
Content::String(ref v) => visitor.visit_str(v),
|
||||
Content::Unit => visitor.visit_unit(),
|
||||
Content::None => visitor.visit_none(),
|
||||
Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)),
|
||||
Content::Newtype(ref v) => visitor.visit_newtype_struct(ContentRefDeserializer::new(v)),
|
||||
Content::Seq(ref v) => {
|
||||
let seq = v.into_iter().map(ContentRefDeserializer::new);
|
||||
let mut seq_visitor = de::value::SeqDeserializer::new(seq);
|
||||
let value = try!(visitor.visit_seq(&mut seq_visitor));
|
||||
try!(seq_visitor.end());
|
||||
Ok(value)
|
||||
},
|
||||
Content::Map(ref v) => {
|
||||
let map = v.into_iter().map(|&(ref k, ref v)| (ContentRefDeserializer::new(k), ContentRefDeserializer::new(v)));
|
||||
let mut map_visitor = de::value::MapDeserializer::new(map);
|
||||
let value = try!(visitor.visit_map(&mut map_visitor));
|
||||
try!(map_visitor.end());
|
||||
Ok(value)
|
||||
},
|
||||
Content::Bytes(ref v) => visitor.visit_bytes(v),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor
|
||||
{
|
||||
match *self.content {
|
||||
Content::None => visitor.visit_none(),
|
||||
Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)),
|
||||
Content::Unit => visitor.visit_unit(),
|
||||
_ => visitor.visit_some(self)
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor
|
||||
{
|
||||
visitor.visit_newtype_struct(self)
|
||||
}
|
||||
|
||||
forward_to_deserialize! {
|
||||
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
|
||||
seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct
|
||||
struct_field tuple enum ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, E> ContentRefDeserializer<'a, E> {
|
||||
/// private API, don't use
|
||||
pub fn new(content: &'a Content) -> Self {
|
||||
ContentRefDeserializer {
|
||||
content: content,
|
||||
err: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> de::value::ValueDeserializer<E> for ContentDeserializer<E>
|
||||
where E: de::Error
|
||||
{
|
||||
type Deserializer = Self;
|
||||
|
||||
fn into_deserializer(self) -> Self {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, E> de::value::ValueDeserializer<E> for ContentRefDeserializer<'a, E>
|
||||
where E: de::Error
|
||||
{
|
||||
type Deserializer = Self;
|
||||
|
||||
fn into_deserializer(self) -> Self {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Visitor for deserializing an internally tagged unit variant.
|
||||
///
|
||||
/// Not public API.
|
||||
pub struct InternallyTaggedUnitVisitor<'a> {
|
||||
type_name: &'a str,
|
||||
variant_name: &'a str,
|
||||
}
|
||||
|
||||
impl<'a> InternallyTaggedUnitVisitor<'a> {
|
||||
/// Not public API.
|
||||
pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
|
||||
InternallyTaggedUnitVisitor {
|
||||
type_name: type_name,
|
||||
variant_name: variant_name,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Visitor for InternallyTaggedUnitVisitor<'a> {
|
||||
type Value = ();
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(formatter, "unit variant {}::{}", self.type_name, self.variant_name)
|
||||
}
|
||||
|
||||
fn visit_map<V>(self, _: V) -> Result<(), V::Error>
|
||||
where V: MapVisitor
|
||||
{
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Visitor for deserializing an untagged unit variant.
|
||||
///
|
||||
/// Not public API.
|
||||
pub struct UntaggedUnitVisitor<'a> {
|
||||
type_name: &'a str,
|
||||
variant_name: &'a str,
|
||||
}
|
||||
|
||||
impl<'a> UntaggedUnitVisitor<'a> {
|
||||
/// Not public API.
|
||||
pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
|
||||
UntaggedUnitVisitor {
|
||||
type_name: type_name,
|
||||
variant_name: variant_name,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Visitor for UntaggedUnitVisitor<'a> {
|
||||
type Value = ();
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(formatter, "unit variant {}::{}", self.type_name, self.variant_name)
|
||||
}
|
||||
|
||||
fn visit_unit<E>(self) -> Result<(), E>
|
||||
where E: de::Error
|
||||
{
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
|
||||
// file at the top-level directory of this distribution and at
|
||||
// http://rust-lang.org/COPYRIGHT.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
// Extracted from https://github.com/rust-num/num.
|
||||
|
||||
// Rust 1.5 is unhappy that this private module is undocumented.
|
||||
#![allow(missing_docs)]
|
||||
|
||||
use core::{usize, u8, u16, u32, u64};
|
||||
use core::{isize, i8, i16, i32, i64};
|
||||
use core::{f32, f64};
|
||||
use core::mem::size_of;
|
||||
|
||||
/// Numbers which have upper and lower bounds
|
||||
pub trait Bounded {
|
||||
// FIXME (#5527): These should be associated constants
|
||||
/// returns the smallest finite number this type can represent
|
||||
fn min_value() -> Self;
|
||||
/// returns the largest finite number this type can represent
|
||||
fn max_value() -> Self;
|
||||
}
|
||||
|
||||
macro_rules! bounded_impl {
|
||||
($t:ty, $min:expr, $max:expr) => {
|
||||
impl Bounded for $t {
|
||||
#[inline]
|
||||
fn min_value() -> $t { $min }
|
||||
|
||||
#[inline]
|
||||
fn max_value() -> $t { $max }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bounded_impl!(usize, usize::MIN, usize::MAX);
|
||||
bounded_impl!(u8, u8::MIN, u8::MAX);
|
||||
bounded_impl!(u16, u16::MIN, u16::MAX);
|
||||
bounded_impl!(u32, u32::MIN, u32::MAX);
|
||||
bounded_impl!(u64, u64::MIN, u64::MAX);
|
||||
|
||||
bounded_impl!(isize, isize::MIN, isize::MAX);
|
||||
bounded_impl!(i8, i8::MIN, i8::MAX);
|
||||
bounded_impl!(i16, i16::MIN, i16::MAX);
|
||||
bounded_impl!(i32, i32::MIN, i32::MAX);
|
||||
bounded_impl!(i64, i64::MIN, i64::MAX);
|
||||
|
||||
bounded_impl!(f32, f32::MIN, f32::MAX);
|
||||
bounded_impl!(f64, f64::MIN, f64::MAX);
|
||||
|
||||
/// A generic trait for converting a value to a number.
|
||||
pub trait ToPrimitive {
|
||||
/// Converts the value of `self` to an `isize`.
|
||||
#[inline]
|
||||
fn to_isize(&self) -> Option<isize> {
|
||||
self.to_i64().and_then(|x| x.to_isize())
|
||||
}
|
||||
|
||||
/// Converts the value of `self` to an `i8`.
|
||||
#[inline]
|
||||
fn to_i8(&self) -> Option<i8> {
|
||||
self.to_i64().and_then(|x| x.to_i8())
|
||||
}
|
||||
|
||||
/// Converts the value of `self` to an `i16`.
|
||||
#[inline]
|
||||
fn to_i16(&self) -> Option<i16> {
|
||||
self.to_i64().and_then(|x| x.to_i16())
|
||||
}
|
||||
|
||||
/// Converts the value of `self` to an `i32`.
|
||||
#[inline]
|
||||
fn to_i32(&self) -> Option<i32> {
|
||||
self.to_i64().and_then(|x| x.to_i32())
|
||||
}
|
||||
|
||||
/// Converts the value of `self` to an `i64`.
|
||||
fn to_i64(&self) -> Option<i64>;
|
||||
|
||||
/// Converts the value of `self` to a `usize`.
|
||||
#[inline]
|
||||
fn to_usize(&self) -> Option<usize> {
|
||||
self.to_u64().and_then(|x| x.to_usize())
|
||||
}
|
||||
|
||||
/// Converts the value of `self` to an `u8`.
|
||||
#[inline]
|
||||
fn to_u8(&self) -> Option<u8> {
|
||||
self.to_u64().and_then(|x| x.to_u8())
|
||||
}
|
||||
|
||||
/// Converts the value of `self` to an `u16`.
|
||||
#[inline]
|
||||
fn to_u16(&self) -> Option<u16> {
|
||||
self.to_u64().and_then(|x| x.to_u16())
|
||||
}
|
||||
|
||||
/// Converts the value of `self` to an `u32`.
|
||||
#[inline]
|
||||
fn to_u32(&self) -> Option<u32> {
|
||||
self.to_u64().and_then(|x| x.to_u32())
|
||||
}
|
||||
|
||||
/// Converts the value of `self` to an `u64`.
|
||||
#[inline]
|
||||
fn to_u64(&self) -> Option<u64>;
|
||||
|
||||
/// Converts the value of `self` to an `f32`.
|
||||
#[inline]
|
||||
fn to_f32(&self) -> Option<f32> {
|
||||
self.to_f64().and_then(|x| x.to_f32())
|
||||
}
|
||||
|
||||
/// Converts the value of `self` to an `f64`.
|
||||
#[inline]
|
||||
fn to_f64(&self) -> Option<f64> {
|
||||
self.to_i64().and_then(|x| x.to_f64())
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_to_primitive_int_to_int {
|
||||
($SrcT:ty, $DstT:ty, $slf:expr) => (
|
||||
{
|
||||
if size_of::<$SrcT>() <= size_of::<$DstT>() {
|
||||
Some($slf as $DstT)
|
||||
} else {
|
||||
let n = $slf as i64;
|
||||
let min_value: $DstT = Bounded::min_value();
|
||||
let max_value: $DstT = Bounded::max_value();
|
||||
if min_value as i64 <= n && n <= max_value as i64 {
|
||||
Some($slf as $DstT)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
macro_rules! impl_to_primitive_int_to_uint {
|
||||
($SrcT:ty, $DstT:ty, $slf:expr) => (
|
||||
{
|
||||
let zero: $SrcT = 0;
|
||||
let max_value: $DstT = Bounded::max_value();
|
||||
if zero <= $slf && $slf as u64 <= max_value as u64 {
|
||||
Some($slf as $DstT)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
macro_rules! impl_to_primitive_int {
|
||||
($T:ty) => (
|
||||
impl ToPrimitive for $T {
|
||||
#[inline]
|
||||
fn to_isize(&self) -> Option<isize> { impl_to_primitive_int_to_int!($T, isize, *self) }
|
||||
#[inline]
|
||||
fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8, *self) }
|
||||
#[inline]
|
||||
fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16, *self) }
|
||||
#[inline]
|
||||
fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32, *self) }
|
||||
#[inline]
|
||||
fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64, *self) }
|
||||
|
||||
#[inline]
|
||||
fn to_usize(&self) -> Option<usize> { impl_to_primitive_int_to_uint!($T, usize, *self) }
|
||||
#[inline]
|
||||
fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8, *self) }
|
||||
#[inline]
|
||||
fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16, *self) }
|
||||
#[inline]
|
||||
fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32, *self) }
|
||||
#[inline]
|
||||
fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64, *self) }
|
||||
|
||||
#[inline]
|
||||
fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
|
||||
#[inline]
|
||||
fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
impl_to_primitive_int! { isize }
|
||||
impl_to_primitive_int! { i8 }
|
||||
impl_to_primitive_int! { i16 }
|
||||
impl_to_primitive_int! { i32 }
|
||||
impl_to_primitive_int! { i64 }
|
||||
|
||||
macro_rules! impl_to_primitive_uint_to_int {
|
||||
($DstT:ty, $slf:expr) => (
|
||||
{
|
||||
let max_value: $DstT = Bounded::max_value();
|
||||
if $slf as u64 <= max_value as u64 {
|
||||
Some($slf as $DstT)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
macro_rules! impl_to_primitive_uint_to_uint {
|
||||
($SrcT:ty, $DstT:ty, $slf:expr) => (
|
||||
{
|
||||
if size_of::<$SrcT>() <= size_of::<$DstT>() {
|
||||
Some($slf as $DstT)
|
||||
} else {
|
||||
let zero: $SrcT = 0;
|
||||
let max_value: $DstT = Bounded::max_value();
|
||||
if zero <= $slf && $slf as u64 <= max_value as u64 {
|
||||
Some($slf as $DstT)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
macro_rules! impl_to_primitive_uint {
|
||||
($T:ty) => (
|
||||
impl ToPrimitive for $T {
|
||||
#[inline]
|
||||
fn to_isize(&self) -> Option<isize> { impl_to_primitive_uint_to_int!(isize, *self) }
|
||||
#[inline]
|
||||
fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8, *self) }
|
||||
#[inline]
|
||||
fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16, *self) }
|
||||
#[inline]
|
||||
fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32, *self) }
|
||||
#[inline]
|
||||
fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64, *self) }
|
||||
|
||||
#[inline]
|
||||
fn to_usize(&self) -> Option<usize> {
|
||||
impl_to_primitive_uint_to_uint!($T, usize, *self)
|
||||
}
|
||||
#[inline]
|
||||
fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8, *self) }
|
||||
#[inline]
|
||||
fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16, *self) }
|
||||
#[inline]
|
||||
fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32, *self) }
|
||||
#[inline]
|
||||
fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64, *self) }
|
||||
|
||||
#[inline]
|
||||
fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
|
||||
#[inline]
|
||||
fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
impl_to_primitive_uint! { usize }
|
||||
impl_to_primitive_uint! { u8 }
|
||||
impl_to_primitive_uint! { u16 }
|
||||
impl_to_primitive_uint! { u32 }
|
||||
impl_to_primitive_uint! { u64 }
|
||||
|
||||
macro_rules! impl_to_primitive_float_to_float {
|
||||
($SrcT:ident, $DstT:ident, $slf:expr) => (
|
||||
if size_of::<$SrcT>() <= size_of::<$DstT>() {
|
||||
Some($slf as $DstT)
|
||||
} else {
|
||||
let n = $slf as f64;
|
||||
let max_value: $SrcT = ::core::$SrcT::MAX;
|
||||
if -max_value as f64 <= n && n <= max_value as f64 {
|
||||
Some($slf as $DstT)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
macro_rules! impl_to_primitive_float {
|
||||
($T:ident) => (
|
||||
impl ToPrimitive for $T {
|
||||
#[inline]
|
||||
fn to_isize(&self) -> Option<isize> { Some(*self as isize) }
|
||||
#[inline]
|
||||
fn to_i8(&self) -> Option<i8> { Some(*self as i8) }
|
||||
#[inline]
|
||||
fn to_i16(&self) -> Option<i16> { Some(*self as i16) }
|
||||
#[inline]
|
||||
fn to_i32(&self) -> Option<i32> { Some(*self as i32) }
|
||||
#[inline]
|
||||
fn to_i64(&self) -> Option<i64> { Some(*self as i64) }
|
||||
|
||||
#[inline]
|
||||
fn to_usize(&self) -> Option<usize> { Some(*self as usize) }
|
||||
#[inline]
|
||||
fn to_u8(&self) -> Option<u8> { Some(*self as u8) }
|
||||
#[inline]
|
||||
fn to_u16(&self) -> Option<u16> { Some(*self as u16) }
|
||||
#[inline]
|
||||
fn to_u32(&self) -> Option<u32> { Some(*self as u32) }
|
||||
#[inline]
|
||||
fn to_u64(&self) -> Option<u64> { Some(*self as u64) }
|
||||
|
||||
#[inline]
|
||||
fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32, *self) }
|
||||
#[inline]
|
||||
fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64, *self) }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
impl_to_primitive_float! { f32 }
|
||||
impl_to_primitive_float! { f64 }
|
||||
|
||||
pub trait FromPrimitive: Sized {
|
||||
#[inline]
|
||||
fn from_isize(n: isize) -> Option<Self> {
|
||||
FromPrimitive::from_i64(n as i64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_i8(n: i8) -> Option<Self> {
|
||||
FromPrimitive::from_i64(n as i64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_i16(n: i16) -> Option<Self> {
|
||||
FromPrimitive::from_i64(n as i64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_i32(n: i32) -> Option<Self> {
|
||||
FromPrimitive::from_i64(n as i64)
|
||||
}
|
||||
|
||||
fn from_i64(n: i64) -> Option<Self>;
|
||||
|
||||
#[inline]
|
||||
fn from_usize(n: usize) -> Option<Self> {
|
||||
FromPrimitive::from_u64(n as u64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_u8(n: u8) -> Option<Self> {
|
||||
FromPrimitive::from_u64(n as u64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_u16(n: u16) -> Option<Self> {
|
||||
FromPrimitive::from_u64(n as u64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_u32(n: u32) -> Option<Self> {
|
||||
FromPrimitive::from_u64(n as u64)
|
||||
}
|
||||
|
||||
fn from_u64(n: u64) -> Option<Self>;
|
||||
|
||||
#[inline]
|
||||
fn from_f32(n: f32) -> Option<Self> {
|
||||
FromPrimitive::from_f64(n as f64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_f64(n: f64) -> Option<Self> {
|
||||
FromPrimitive::from_i64(n as i64)
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_from_primitive {
|
||||
($T:ty, $to_ty:ident) => (
|
||||
impl FromPrimitive for $T {
|
||||
#[inline] fn from_i8(n: i8) -> Option<$T> { n.$to_ty() }
|
||||
#[inline] fn from_i16(n: i16) -> Option<$T> { n.$to_ty() }
|
||||
#[inline] fn from_i32(n: i32) -> Option<$T> { n.$to_ty() }
|
||||
#[inline] fn from_i64(n: i64) -> Option<$T> { n.$to_ty() }
|
||||
|
||||
#[inline] fn from_u8(n: u8) -> Option<$T> { n.$to_ty() }
|
||||
#[inline] fn from_u16(n: u16) -> Option<$T> { n.$to_ty() }
|
||||
#[inline] fn from_u32(n: u32) -> Option<$T> { n.$to_ty() }
|
||||
#[inline] fn from_u64(n: u64) -> Option<$T> { n.$to_ty() }
|
||||
|
||||
#[inline] fn from_f32(n: f32) -> Option<$T> { n.$to_ty() }
|
||||
#[inline] fn from_f64(n: f64) -> Option<$T> { n.$to_ty() }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
impl_from_primitive! { isize, to_isize }
|
||||
impl_from_primitive! { i8, to_i8 }
|
||||
impl_from_primitive! { i16, to_i16 }
|
||||
impl_from_primitive! { i32, to_i32 }
|
||||
impl_from_primitive! { i64, to_i64 }
|
||||
impl_from_primitive! { usize, to_usize }
|
||||
impl_from_primitive! { u8, to_u8 }
|
||||
impl_from_primitive! { u16, to_u16 }
|
||||
impl_from_primitive! { u32, to_u32 }
|
||||
impl_from_primitive! { u64, to_u64 }
|
||||
impl_from_primitive! { f32, to_f32 }
|
||||
impl_from_primitive! { f64, to_f64 }
|
||||
File diff suppressed because it is too large
Load Diff
+1602
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,49 @@
|
||||
use core::marker::PhantomData;
|
||||
|
||||
use de::{Deserialize, Deserializer, Error, Visitor};
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
pub use de::content::{
|
||||
Content,
|
||||
ContentRefDeserializer,
|
||||
ContentDeserializer,
|
||||
TaggedContentVisitor,
|
||||
InternallyTaggedUnitVisitor,
|
||||
UntaggedUnitVisitor,
|
||||
};
|
||||
|
||||
/// If the missing field is of type `Option<T>` then treat is as `None`,
|
||||
/// otherwise it is an error.
|
||||
pub fn missing_field<V, E>(field: &'static str) -> Result<V, E>
|
||||
where V: Deserialize,
|
||||
E: Error
|
||||
{
|
||||
struct MissingFieldDeserializer<E>(&'static str, PhantomData<E>);
|
||||
|
||||
impl<E> Deserializer for MissingFieldDeserializer<E>
|
||||
where E: Error
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn deserialize<V>(self, _visitor: V) -> Result<V::Value, E>
|
||||
where V: Visitor
|
||||
{
|
||||
Err(Error::missing_field(self.0))
|
||||
}
|
||||
|
||||
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, E>
|
||||
where V: Visitor
|
||||
{
|
||||
visitor.visit_none()
|
||||
}
|
||||
|
||||
forward_to_deserialize! {
|
||||
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
|
||||
seq_fixed_size bytes byte_buf map unit_struct newtype_struct
|
||||
tuple_struct struct struct_field tuple enum ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
let deserializer = MissingFieldDeserializer(field, PhantomData);
|
||||
Deserialize::deserialize(deserializer)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,15 @@
|
||||
//! A stand-in for `std::error`
|
||||
use core::fmt::{Debug, Display};
|
||||
|
||||
/// A stand-in for `std::error::Error`, which requires no allocation.
|
||||
pub trait Error: Debug + Display {
|
||||
/// A short description of the error.
|
||||
///
|
||||
/// The description should not contain newlines or sentence-ending
|
||||
/// punctuation, to facilitate embedding in larger user-facing
|
||||
/// strings.
|
||||
fn description(&self) -> &str;
|
||||
|
||||
/// The lower-level cause of this error, if any.
|
||||
fn cause(&self) -> Option<&Error> { None }
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||
use collections::String;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use std::borrow::Cow;
|
||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||
use collections::borrow::Cow;
|
||||
|
||||
pub use core::default::Default;
|
||||
pub use core::fmt;
|
||||
pub use core::marker::PhantomData;
|
||||
pub use core::option::Option::{self, None, Some};
|
||||
pub use core::result::Result::{self, Ok, Err};
|
||||
|
||||
#[cfg(any(feature = "collections", feature = "std"))]
|
||||
pub fn from_utf8_lossy(bytes: &[u8]) -> Cow<str> {
|
||||
String::from_utf8_lossy(bytes)
|
||||
}
|
||||
|
||||
// The generated code calls this like:
|
||||
//
|
||||
// let value = &_serde::export::from_utf8_lossy(bytes);
|
||||
// Err(_serde::de::Error::unknown_variant(value, VARIANTS))
|
||||
//
|
||||
// so it is okay for the return type to be different from the std case as long
|
||||
// as the above works.
|
||||
#[cfg(not(any(feature = "collections", feature = "std")))]
|
||||
pub fn from_utf8_lossy(bytes: &[u8]) -> &str {
|
||||
use core::str;
|
||||
// Three unicode replacement characters if it fails. They look like a
|
||||
// white-on-black question mark. The user will recognize it as invalid
|
||||
// UTF-8.
|
||||
str::from_utf8(bytes).unwrap_or("\u{fffd}\u{fffd}\u{fffd}")
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Module that contains helper iterators.
|
||||
|
||||
use std::io;
|
||||
use std::iter::Peekable;
|
||||
|
||||
/// Iterator over a byte stream that tracks the current position's line and column.
|
||||
pub struct LineColIterator<Iter: Iterator<Item=io::Result<u8>>> {
|
||||
iter: Iter,
|
||||
line: usize,
|
||||
col: usize,
|
||||
}
|
||||
|
||||
impl<Iter: Iterator<Item=io::Result<u8>>> LineColIterator<Iter> {
|
||||
/// Construct a new `LineColIterator<Iter>`.
|
||||
pub fn new(iter: Iter) -> LineColIterator<Iter> {
|
||||
LineColIterator {
|
||||
iter: iter,
|
||||
line: 1,
|
||||
col: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Report the current line inside the iterator.
|
||||
pub fn line(&self) -> usize { self.line }
|
||||
|
||||
/// Report the current column inside the iterator.
|
||||
pub fn col(&self) -> usize { self.col }
|
||||
|
||||
/// Gets a reference to the underlying iterator.
|
||||
pub fn get_ref(&self) -> &Iter { &self.iter }
|
||||
|
||||
/// Gets a mutable reference to the underlying iterator.
|
||||
pub fn get_mut(&mut self) -> &mut Iter { &mut self.iter }
|
||||
|
||||
/// Unwraps this `LineColIterator`, returning the underlying iterator.
|
||||
pub fn into_inner(self) -> Iter { self.iter }
|
||||
}
|
||||
|
||||
impl<Iter: Iterator<Item=io::Result<u8>>> LineColIterator<Peekable<Iter>> {
|
||||
/// peeks at the next value
|
||||
pub fn peek(&mut self) -> Option<&io::Result<u8>> { self.iter.peek() }
|
||||
}
|
||||
|
||||
impl<Iter: Iterator<Item=io::Result<u8>>> Iterator for LineColIterator<Iter> {
|
||||
type Item = io::Result<u8>;
|
||||
fn next(&mut self) -> Option<io::Result<u8>> {
|
||||
match self.iter.next() {
|
||||
None => None,
|
||||
Some(Ok(b'\n')) => {
|
||||
self.line += 1;
|
||||
self.col = 0;
|
||||
Some(Ok(b'\n'))
|
||||
},
|
||||
Some(Ok(c)) => {
|
||||
self.col += 1;
|
||||
Some(Ok(c))
|
||||
},
|
||||
Some(Err(e)) => Some(Err(e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//! # Serde
|
||||
//!
|
||||
//! Serde is a framework for ***ser***ializing and ***de***serializing Rust data
|
||||
//! structures efficiently and generically.
|
||||
//!
|
||||
//! The Serde ecosystem consists of data structures that know how to serialize
|
||||
//! and deserialize themselves along with data formats that know how to
|
||||
//! serialize and deserialize other things. Serde provides the layer by which
|
||||
//! these two groups interact with each other, allowing any supported data
|
||||
//! structure to be serialized and deserialized using any supported data format.
|
||||
//!
|
||||
//! See the Serde website https://serde.rs/ for additional documentation and
|
||||
//! usage examples.
|
||||
//!
|
||||
//! ### Design
|
||||
//!
|
||||
//! Where many other languages rely on runtime reflection for serializing data,
|
||||
//! Serde is instead built on Rust's powerful trait system. A data structure
|
||||
//! that knows how to serialize and deserialize itself is one that implements
|
||||
//! Serde's `Serialize` and `Deserialize` traits (or uses Serde's code
|
||||
//! generation to automatically derive implementations at compile time). This
|
||||
//! avoids any overhead of reflection or runtime type information. In fact in
|
||||
//! many situations the interaction between data structure and data format can
|
||||
//! be completely optimized away by the Rust compiler, leaving Serde
|
||||
//! serialization to perform roughly the same speed as a handwritten serializer
|
||||
//! for the specific selection of data structure and data format.
|
||||
//!
|
||||
//! ### Data formats
|
||||
//!
|
||||
//! The following is a partial list of data formats that have been implemented
|
||||
//! for Serde by the community.
|
||||
//!
|
||||
//! - [JSON](https://github.com/serde-rs/json), the ubiquitous JavaScript Object
|
||||
//! Notation used by many HTTP APIs.
|
||||
//! - [Bincode](https://github.com/TyOverby/bincode), a compact binary format
|
||||
//! used for IPC within the Servo rendering engine.
|
||||
//! - [CBOR](https://github.com/pyfisch/cbor), a Concise Binary Object
|
||||
//! Representation designed for small message size without the need for
|
||||
//! version negotiation.
|
||||
//! - [YAML](https://github.com/dtolnay/serde-yaml), a popular human-friendly
|
||||
//! configuration language that ain't markup language.
|
||||
//! - [MessagePack](https://github.com/3Hren/msgpack-rust), an efficient binary
|
||||
//! format that resembles a compact JSON.
|
||||
//! - [TOML](https://github.com/alexcrichton/toml-rs), a minimal configuration
|
||||
//! format used by [Cargo](http://doc.crates.io/manifest.html).
|
||||
//! - [Pickle](https://github.com/birkenfeld/serde-pickle), a format common in
|
||||
//! the Python world.
|
||||
//! - [Hjson](https://github.com/laktak/hjson-rust), a variant of JSON designed
|
||||
//! to be readable and writable by humans.
|
||||
//! - [BSON](https://github.com/zonyitoo/bson-rs), the data storage and network
|
||||
//! transfer format used by MongoDB.
|
||||
//! - [URL](https://github.com/nox/serde_urlencoded), the x-www-form-urlencoded
|
||||
//! format.
|
||||
//! - [XML](https://github.com/serde-rs/xml), the flexible machine-friendly W3C
|
||||
//! standard. *(deserialization only)*
|
||||
//! - [Envy](https://github.com/softprops/envy), a way to deserialize
|
||||
//! environment variables into Rust structs. *(deserialization only)*
|
||||
//! - [Redis](https://github.com/OneSignal/serde-redis), deserialize values from
|
||||
//! Redis when using [redis-rs](https://crates.io/crates/redis).
|
||||
//! *(deserialization only)*
|
||||
|
||||
#![doc(html_root_url="https://docs.serde.rs")]
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
#![cfg_attr(feature = "unstable", feature(inclusive_range, nonzero, specialization, zero_one))]
|
||||
#![cfg_attr(feature = "alloc", feature(alloc))]
|
||||
#![cfg_attr(feature = "collections", feature(collections))]
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(linkedlist, type_complexity, doc_markdown))]
|
||||
#![deny(missing_docs)]
|
||||
|
||||
#[cfg(feature = "collections")]
|
||||
extern crate collections;
|
||||
|
||||
#[cfg(feature = "alloc")]
|
||||
extern crate alloc;
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
extern crate core as actual_core;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
mod core {
|
||||
pub use std::{ops, hash, fmt, cmp, marker, mem, i8, i16, i32, i64, u8, u16, u32, u64, isize,
|
||||
usize, f32, f64, char, str, num, slice, iter, cell, default, result, option};
|
||||
#[cfg(feature = "unstable")]
|
||||
pub use actual_core::nonzero;
|
||||
}
|
||||
|
||||
#[doc(inline)]
|
||||
pub use ser::{Serialize, Serializer};
|
||||
#[doc(inline)]
|
||||
pub use de::{Deserialize, Deserializer};
|
||||
|
||||
#[macro_use]
|
||||
mod macros;
|
||||
|
||||
pub mod bytes;
|
||||
pub mod de;
|
||||
#[cfg(feature = "std")]
|
||||
#[doc(hidden)]
|
||||
pub mod iter;
|
||||
pub mod ser;
|
||||
#[cfg_attr(feature = "std", doc(hidden))]
|
||||
pub mod error;
|
||||
mod utils;
|
||||
|
||||
// Generated code uses these to support no_std. Not public API.
|
||||
#[doc(hidden)]
|
||||
pub mod export;
|
||||
@@ -0,0 +1,190 @@
|
||||
#[cfg(feature = "std")]
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
macro_rules! forward_to_deserialize_method {
|
||||
($func:ident($($arg:ty),*)) => {
|
||||
#[inline]
|
||||
fn $func<__V>(self, $(_: $arg,)* visitor: __V) -> ::std::result::Result<__V::Value, Self::Error>
|
||||
where __V: $crate::de::Visitor
|
||||
{
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "std"))]
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
macro_rules! forward_to_deserialize_method {
|
||||
($func:ident($($arg:ty),*)) => {
|
||||
#[inline]
|
||||
fn $func<__V>(self, $(_: $arg,)* visitor: __V) -> ::core::result::Result<__V::Value, Self::Error>
|
||||
where __V: $crate::de::Visitor
|
||||
{
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
macro_rules! forward_to_deserialize_helper {
|
||||
(bool) => {
|
||||
forward_to_deserialize_method!{deserialize_bool()}
|
||||
};
|
||||
(u8) => {
|
||||
forward_to_deserialize_method!{deserialize_u8()}
|
||||
};
|
||||
(u16) => {
|
||||
forward_to_deserialize_method!{deserialize_u16()}
|
||||
};
|
||||
(u32) => {
|
||||
forward_to_deserialize_method!{deserialize_u32()}
|
||||
};
|
||||
(u64) => {
|
||||
forward_to_deserialize_method!{deserialize_u64()}
|
||||
};
|
||||
(i8) => {
|
||||
forward_to_deserialize_method!{deserialize_i8()}
|
||||
};
|
||||
(i16) => {
|
||||
forward_to_deserialize_method!{deserialize_i16()}
|
||||
};
|
||||
(i32) => {
|
||||
forward_to_deserialize_method!{deserialize_i32()}
|
||||
};
|
||||
(i64) => {
|
||||
forward_to_deserialize_method!{deserialize_i64()}
|
||||
};
|
||||
(f32) => {
|
||||
forward_to_deserialize_method!{deserialize_f32()}
|
||||
};
|
||||
(f64) => {
|
||||
forward_to_deserialize_method!{deserialize_f64()}
|
||||
};
|
||||
(char) => {
|
||||
forward_to_deserialize_method!{deserialize_char()}
|
||||
};
|
||||
(str) => {
|
||||
forward_to_deserialize_method!{deserialize_str()}
|
||||
};
|
||||
(string) => {
|
||||
forward_to_deserialize_method!{deserialize_string()}
|
||||
};
|
||||
(unit) => {
|
||||
forward_to_deserialize_method!{deserialize_unit()}
|
||||
};
|
||||
(option) => {
|
||||
forward_to_deserialize_method!{deserialize_option()}
|
||||
};
|
||||
(seq) => {
|
||||
forward_to_deserialize_method!{deserialize_seq()}
|
||||
};
|
||||
(seq_fixed_size) => {
|
||||
forward_to_deserialize_method!{deserialize_seq_fixed_size(usize)}
|
||||
};
|
||||
(bytes) => {
|
||||
forward_to_deserialize_method!{deserialize_bytes()}
|
||||
};
|
||||
(byte_buf) => {
|
||||
forward_to_deserialize_method!{deserialize_byte_buf()}
|
||||
};
|
||||
(map) => {
|
||||
forward_to_deserialize_method!{deserialize_map()}
|
||||
};
|
||||
(unit_struct) => {
|
||||
forward_to_deserialize_method!{deserialize_unit_struct(&'static str)}
|
||||
};
|
||||
(newtype_struct) => {
|
||||
forward_to_deserialize_method!{deserialize_newtype_struct(&'static str)}
|
||||
};
|
||||
(tuple_struct) => {
|
||||
forward_to_deserialize_method!{deserialize_tuple_struct(&'static str, usize)}
|
||||
};
|
||||
(struct) => {
|
||||
forward_to_deserialize_method!{deserialize_struct(&'static str, &'static [&'static str])}
|
||||
};
|
||||
(struct_field) => {
|
||||
forward_to_deserialize_method!{deserialize_struct_field()}
|
||||
};
|
||||
(tuple) => {
|
||||
forward_to_deserialize_method!{deserialize_tuple(usize)}
|
||||
};
|
||||
(enum) => {
|
||||
forward_to_deserialize_method!{deserialize_enum(&'static str, &'static [&'static str])}
|
||||
};
|
||||
(ignored_any) => {
|
||||
forward_to_deserialize_method!{deserialize_ignored_any()}
|
||||
};
|
||||
}
|
||||
|
||||
// Super explicit first paragraph because this shows up at the top level and
|
||||
// trips up people who are just looking for basic Serialize / Deserialize
|
||||
// documentation.
|
||||
//
|
||||
/// Helper macro when implementing the `Deserializer` part of a new data format
|
||||
/// for Serde.
|
||||
///
|
||||
/// Some `Deserializer` implementations for self-describing formats do not care
|
||||
/// what hint the `Visitor` gives them, they just want to blindly call the
|
||||
/// `Visitor` method corresponding to the data they can tell is in the input.
|
||||
/// This requires repetitive implementations of all the `Deserializer` trait
|
||||
/// methods.
|
||||
///
|
||||
/// ```rust
|
||||
/// # #[macro_use] extern crate serde;
|
||||
/// # use serde::de::{value, Deserializer, Visitor};
|
||||
/// # pub struct MyDeserializer;
|
||||
/// # impl Deserializer for MyDeserializer {
|
||||
/// # type Error = value::Error;
|
||||
/// # fn deserialize<V>(self, _: V) -> Result<V::Value, Self::Error>
|
||||
/// # where V: Visitor
|
||||
/// # { unimplemented!() }
|
||||
/// #
|
||||
/// #[inline]
|
||||
/// fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
/// where V: Visitor
|
||||
/// {
|
||||
/// self.deserialize(visitor)
|
||||
/// }
|
||||
/// # forward_to_deserialize! {
|
||||
/// # u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
|
||||
/// # seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
|
||||
/// # tuple_struct struct struct_field tuple enum ignored_any
|
||||
/// # }
|
||||
/// # }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
///
|
||||
/// The `forward_to_deserialize!` macro implements these simple forwarding
|
||||
/// methods so that they forward directly to `Deserializer::deserialize`. You
|
||||
/// can choose which methods to forward.
|
||||
///
|
||||
/// ```rust
|
||||
/// # #[macro_use] extern crate serde;
|
||||
/// # use serde::de::{value, Deserializer, Visitor};
|
||||
/// # pub struct MyDeserializer;
|
||||
/// impl Deserializer for MyDeserializer {
|
||||
/// # type Error = value::Error;
|
||||
/// fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
/// where V: Visitor
|
||||
/// {
|
||||
/// /* ... */
|
||||
/// # let _ = visitor;
|
||||
/// # unimplemented!()
|
||||
/// }
|
||||
///
|
||||
/// forward_to_deserialize! {
|
||||
/// bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
|
||||
/// seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
|
||||
/// tuple_struct struct struct_field tuple enum ignored_any
|
||||
/// }
|
||||
/// }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
#[macro_export]
|
||||
macro_rules! forward_to_deserialize {
|
||||
($($func:ident)*) => {
|
||||
$(forward_to_deserialize_helper!{$func})*
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,731 @@
|
||||
#[cfg(feature = "std")]
|
||||
use std::borrow::Cow;
|
||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||
use collections::borrow::Cow;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use std::collections::{
|
||||
BinaryHeap,
|
||||
BTreeMap,
|
||||
BTreeSet,
|
||||
LinkedList,
|
||||
HashMap,
|
||||
HashSet,
|
||||
VecDeque,
|
||||
};
|
||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||
use collections::{
|
||||
BinaryHeap,
|
||||
BTreeMap,
|
||||
BTreeSet,
|
||||
LinkedList,
|
||||
VecDeque,
|
||||
String,
|
||||
Vec,
|
||||
};
|
||||
|
||||
#[cfg(feature = "collections")]
|
||||
use collections::borrow::ToOwned;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use core::hash::{Hash, BuildHasher};
|
||||
#[cfg(feature = "unstable")]
|
||||
use core::iter;
|
||||
#[cfg(feature = "std")]
|
||||
use std::net;
|
||||
#[cfg(feature = "unstable")]
|
||||
use core::ops;
|
||||
#[cfg(feature = "std")]
|
||||
use std::path;
|
||||
#[cfg(feature = "std")]
|
||||
use std::rc::Rc;
|
||||
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||
use alloc::rc::Rc;
|
||||
#[cfg(feature = "std")]
|
||||
use std::time::Duration;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use std::sync::Arc;
|
||||
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||
use alloc::arc::Arc;
|
||||
|
||||
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||
use alloc::boxed::Box;
|
||||
|
||||
use core::marker::PhantomData;
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
use core::nonzero::{NonZero, Zeroable};
|
||||
|
||||
use super::{
|
||||
Serialize,
|
||||
SerializeSeq,
|
||||
SerializeTuple,
|
||||
Serializer,
|
||||
};
|
||||
#[cfg(feature = "std")]
|
||||
use super::Error;
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! impl_visit {
|
||||
($ty:ty, $method:ident $($cast:tt)*) => {
|
||||
impl Serialize for $ty {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
serializer.$method(*self $($cast)*)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl_visit!(bool, serialize_bool);
|
||||
impl_visit!(isize, serialize_i64 as i64);
|
||||
impl_visit!(i8, serialize_i8);
|
||||
impl_visit!(i16, serialize_i16);
|
||||
impl_visit!(i32, serialize_i32);
|
||||
impl_visit!(i64, serialize_i64);
|
||||
impl_visit!(usize, serialize_u64 as u64);
|
||||
impl_visit!(u8, serialize_u8);
|
||||
impl_visit!(u16, serialize_u16);
|
||||
impl_visit!(u32, serialize_u32);
|
||||
impl_visit!(u64, serialize_u64);
|
||||
impl_visit!(f32, serialize_f32);
|
||||
impl_visit!(f64, serialize_f64);
|
||||
impl_visit!(char, serialize_char);
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl Serialize for str {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl Serialize for String {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
(&self[..]).serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<T> Serialize for Option<T>
|
||||
where T: Serialize
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
match *self {
|
||||
Some(ref value) => serializer.serialize_some(value),
|
||||
None => serializer.serialize_none(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<T> Serialize for PhantomData<T> {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
serializer.serialize_unit_struct("PhantomData")
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! array_impls {
|
||||
($len:expr) => {
|
||||
impl<T> Serialize for [T; $len] where T: Serialize {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
let mut seq = try!(serializer.serialize_seq_fixed_size($len));
|
||||
for e in self {
|
||||
try!(seq.serialize_element(e));
|
||||
}
|
||||
seq.end()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
array_impls!(0);
|
||||
array_impls!(1);
|
||||
array_impls!(2);
|
||||
array_impls!(3);
|
||||
array_impls!(4);
|
||||
array_impls!(5);
|
||||
array_impls!(6);
|
||||
array_impls!(7);
|
||||
array_impls!(8);
|
||||
array_impls!(9);
|
||||
array_impls!(10);
|
||||
array_impls!(11);
|
||||
array_impls!(12);
|
||||
array_impls!(13);
|
||||
array_impls!(14);
|
||||
array_impls!(15);
|
||||
array_impls!(16);
|
||||
array_impls!(17);
|
||||
array_impls!(18);
|
||||
array_impls!(19);
|
||||
array_impls!(20);
|
||||
array_impls!(21);
|
||||
array_impls!(22);
|
||||
array_impls!(23);
|
||||
array_impls!(24);
|
||||
array_impls!(25);
|
||||
array_impls!(26);
|
||||
array_impls!(27);
|
||||
array_impls!(28);
|
||||
array_impls!(29);
|
||||
array_impls!(30);
|
||||
array_impls!(31);
|
||||
array_impls!(32);
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! serialize_seq {
|
||||
() => {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
serializer.collect_seq(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Serialize for [T]
|
||||
where T: Serialize,
|
||||
{
|
||||
serialize_seq!();
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<T> Serialize for BinaryHeap<T>
|
||||
where T: Serialize + Ord
|
||||
{
|
||||
serialize_seq!();
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<T> Serialize for BTreeSet<T>
|
||||
where T: Serialize + Ord,
|
||||
{
|
||||
serialize_seq!();
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<T, H> Serialize for HashSet<T, H>
|
||||
where T: Serialize + Eq + Hash,
|
||||
H: BuildHasher,
|
||||
{
|
||||
serialize_seq!();
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<T> Serialize for LinkedList<T>
|
||||
where T: Serialize,
|
||||
{
|
||||
serialize_seq!();
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<T> Serialize for Vec<T>
|
||||
where T: Serialize
|
||||
{
|
||||
serialize_seq!();
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<T> Serialize for VecDeque<T>
|
||||
where T: Serialize
|
||||
{
|
||||
serialize_seq!();
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
impl<A> Serialize for ops::Range<A>
|
||||
where ops::Range<A>: ExactSizeIterator + iter::Iterator<Item = A> + Clone,
|
||||
A: Serialize,
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
|
||||
for e in self.clone() {
|
||||
try!(seq.serialize_element(&e));
|
||||
}
|
||||
seq.end()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
impl<A> Serialize for ops::RangeInclusive<A>
|
||||
where ops::RangeInclusive<A>: ExactSizeIterator + iter::Iterator<Item = A> + Clone,
|
||||
A: Serialize,
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
|
||||
for e in self.clone() {
|
||||
try!(seq.serialize_element(&e));
|
||||
}
|
||||
seq.end()
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl Serialize for () {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
serializer.serialize_unit()
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! tuple_impls {
|
||||
($(
|
||||
$TupleVisitor:ident ($len:expr, $($T:ident),+) {
|
||||
$($state:pat => $idx:tt,)+
|
||||
}
|
||||
)+) => {
|
||||
$(
|
||||
impl<$($T),+> Serialize for ($($T,)+)
|
||||
where $($T: Serialize),+
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
let mut tuple = try!(serializer.serialize_tuple($len));
|
||||
$(
|
||||
try!(tuple.serialize_element(&self.$idx));
|
||||
)+
|
||||
tuple.end()
|
||||
}
|
||||
}
|
||||
)+
|
||||
}
|
||||
}
|
||||
|
||||
tuple_impls! {
|
||||
TupleVisitor1 (1, T0) {
|
||||
0 => 0,
|
||||
}
|
||||
TupleVisitor2 (2, T0, T1) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
}
|
||||
TupleVisitor3 (3, T0, T1, T2) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
}
|
||||
TupleVisitor4 (4, T0, T1, T2, T3) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
}
|
||||
TupleVisitor5 (5, T0, T1, T2, T3, T4) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
}
|
||||
TupleVisitor6 (6, T0, T1, T2, T3, T4, T5) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
}
|
||||
TupleVisitor7 (7, T0, T1, T2, T3, T4, T5, T6) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
}
|
||||
TupleVisitor8 (8, T0, T1, T2, T3, T4, T5, T6, T7) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
}
|
||||
TupleVisitor9 (9, T0, T1, T2, T3, T4, T5, T6, T7, T8) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
8 => 8,
|
||||
}
|
||||
TupleVisitor10 (10, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
8 => 8,
|
||||
9 => 9,
|
||||
}
|
||||
TupleVisitor11 (11, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
8 => 8,
|
||||
9 => 9,
|
||||
10 => 10,
|
||||
}
|
||||
TupleVisitor12 (12, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
8 => 8,
|
||||
9 => 9,
|
||||
10 => 10,
|
||||
11 => 11,
|
||||
}
|
||||
TupleVisitor13 (13, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
8 => 8,
|
||||
9 => 9,
|
||||
10 => 10,
|
||||
11 => 11,
|
||||
12 => 12,
|
||||
}
|
||||
TupleVisitor14 (14, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
8 => 8,
|
||||
9 => 9,
|
||||
10 => 10,
|
||||
11 => 11,
|
||||
12 => 12,
|
||||
13 => 13,
|
||||
}
|
||||
TupleVisitor15 (15, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
8 => 8,
|
||||
9 => 9,
|
||||
10 => 10,
|
||||
11 => 11,
|
||||
12 => 12,
|
||||
13 => 13,
|
||||
14 => 14,
|
||||
}
|
||||
TupleVisitor16 (16, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
8 => 8,
|
||||
9 => 9,
|
||||
10 => 10,
|
||||
11 => 11,
|
||||
12 => 12,
|
||||
13 => 13,
|
||||
14 => 14,
|
||||
15 => 15,
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! serialize_map {
|
||||
() => {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
serializer.collect_map(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<K, V> Serialize for BTreeMap<K, V>
|
||||
where K: Serialize + Ord,
|
||||
V: Serialize,
|
||||
{
|
||||
serialize_map!();
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<K, V, H> Serialize for HashMap<K, V, H>
|
||||
where K: Serialize + Eq + Hash,
|
||||
V: Serialize,
|
||||
H: BuildHasher,
|
||||
{
|
||||
serialize_map!();
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<'a, T: ?Sized> Serialize for &'a T where T: Serialize {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
(**self).serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: ?Sized> Serialize for &'a mut T where T: Serialize {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
(**self).serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<T: ?Sized> Serialize for Box<T>
|
||||
where T: Serialize
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
(**self).serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<T> Serialize for Rc<T>
|
||||
where T: Serialize
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
(**self).serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<T> Serialize for Arc<T>
|
||||
where T: Serialize
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
(**self).serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<'a, T: ?Sized> Serialize for Cow<'a, T>
|
||||
where T: Serialize + ToOwned
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
(**self).serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<T, E> Serialize for Result<T, E>
|
||||
where T: Serialize,
|
||||
E: Serialize
|
||||
{
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
match *self {
|
||||
Result::Ok(ref value) => {
|
||||
serializer.serialize_newtype_variant("Result", 0, "Ok", value)
|
||||
}
|
||||
Result::Err(ref value) => {
|
||||
serializer.serialize_newtype_variant("Result", 1, "Err", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for Duration {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
use super::SerializeStruct;
|
||||
let mut state = try!(serializer.serialize_struct("Duration", 2));
|
||||
try!(state.serialize_field("secs", &self.as_secs()));
|
||||
try!(state.serialize_field("nanos", &self.subsec_nanos()));
|
||||
state.end()
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for net::IpAddr {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
self.to_string().serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for net::Ipv4Addr {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
self.to_string().serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for net::Ipv6Addr {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
self.to_string().serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for net::SocketAddr {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
match *self {
|
||||
net::SocketAddr::V4(ref addr) => addr.serialize(serializer),
|
||||
net::SocketAddr::V6(ref addr) => addr.serialize(serializer),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for net::SocketAddrV4 {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
self.to_string().serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for net::SocketAddrV6 {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
self.to_string().serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for path::Path {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
match self.to_str() {
|
||||
Some(s) => s.serialize(serializer),
|
||||
None => Err(Error::custom("path contains invalid UTF-8 characters")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for path::PathBuf {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
self.as_path().serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
impl<T> Serialize for NonZero<T>
|
||||
where T: Serialize + Zeroable
|
||||
{
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
(**self).serialize(serializer)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
//! This module contains `Impossible` serializer and its implementations.
|
||||
|
||||
use core::marker::PhantomData;
|
||||
|
||||
use ser::{
|
||||
self,
|
||||
Serialize,
|
||||
SerializeSeq,
|
||||
SerializeTuple,
|
||||
SerializeTupleStruct,
|
||||
SerializeTupleVariant,
|
||||
SerializeMap,
|
||||
SerializeStruct,
|
||||
SerializeStructVariant,
|
||||
};
|
||||
|
||||
/// Helper type for implementing a `Serializer` that does not support
|
||||
/// serializing one of the compound types.
|
||||
///
|
||||
/// This type cannot be instantiated, but implements every one of the traits
|
||||
/// corresponding to the `Serializer` compound types: `SerializeSeq`,
|
||||
/// `SerializeTuple`, `SerializeTupleStruct`, `SerializeTupleVariant`,
|
||||
/// `SerializeMap`, `SerializeStruct`, and `SerializeStructVariant`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// impl Serializer for MySerializer {
|
||||
/// type Ok = ();
|
||||
/// type Error = Error;
|
||||
///
|
||||
/// type SerializeSeq = Impossible<(), Error>;
|
||||
/// /* other associated types */
|
||||
///
|
||||
/// /// This data format does not support serializing sequences.
|
||||
/// fn serialize_seq(self,
|
||||
/// len: Option<usize>)
|
||||
/// -> Result<Self::SerializeSeq, Error> {
|
||||
/// // Given Impossible cannot be instantiated, the only
|
||||
/// // thing we can do here is to return an error.
|
||||
/// Err(...)
|
||||
/// }
|
||||
///
|
||||
/// /* other Serializer methods */
|
||||
/// }
|
||||
/// ```
|
||||
pub struct Impossible<Ok, E> {
|
||||
void: Void,
|
||||
_marker: PhantomData<(Ok, E)>,
|
||||
}
|
||||
|
||||
enum Void {}
|
||||
|
||||
impl<Ok, E> SerializeSeq for Impossible<Ok, E>
|
||||
where E: ser::Error,
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_element<T: ?Sized + Serialize>(&mut self,
|
||||
_value: &T)
|
||||
-> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ok, E> SerializeTuple for Impossible<Ok, E>
|
||||
where E: ser::Error,
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_element<T: ?Sized + Serialize>(&mut self,
|
||||
_value: &T)
|
||||
-> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ok, E> SerializeTupleStruct for Impossible<Ok, E>
|
||||
where E: ser::Error,
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||
_value: &T)
|
||||
-> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ok, E> SerializeTupleVariant for Impossible<Ok, E>
|
||||
where E: ser::Error,
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||
_value: &T)
|
||||
-> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ok, E> SerializeMap for Impossible<Ok, E>
|
||||
where E: ser::Error,
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_key<T: ?Sized + Serialize>(&mut self,
|
||||
_key: &T)
|
||||
-> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn serialize_value<T: ?Sized + Serialize>(&mut self,
|
||||
_value: &T)
|
||||
-> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ok, E> SerializeStruct for Impossible<Ok, E>
|
||||
where E: ser::Error,
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||
_key: &'static str,
|
||||
_value: &T)
|
||||
-> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ok, E> SerializeStructVariant for Impossible<Ok, E>
|
||||
where E: ser::Error,
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||
_key: &'static str,
|
||||
_value: &T)
|
||||
-> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,867 @@
|
||||
//! Generic data structure serialization framework.
|
||||
//!
|
||||
//! The two most important traits in this module are `Serialize` and
|
||||
//! `Serializer`.
|
||||
//!
|
||||
//! - **A type that implements `Serialize` is a data structure** that can be
|
||||
//! serialized to any data format supported by Serde, and conversely
|
||||
//! - **A type that implements `Serializer` is a data format** that can
|
||||
//! serialize any data structure supported by Serde.
|
||||
//!
|
||||
//! # The Serialize trait
|
||||
//!
|
||||
//! Serde provides `Serialize` implementations for many Rust primitive and
|
||||
//! standard library types. The complete list is below. All of these can be
|
||||
//! serialized using Serde out of the box.
|
||||
//!
|
||||
//! Additionally, Serde provides a procedural macro called `serde_derive` to
|
||||
//! automatically generate `Serialize` implementations for structs and enums in
|
||||
//! your program. See the [codegen section of the manual][codegen] for how to
|
||||
//! use this.
|
||||
//!
|
||||
//! In rare cases it may be necessary to implement `Serialize` manually for some
|
||||
//! type in your program. See the [Implementing `Serialize`][impl-serialize]
|
||||
//! section of the manual for more about this.
|
||||
//!
|
||||
//! Third-party crates may provide `Serialize` implementations for types that
|
||||
//! they expose. For example the `linked-hash-map` crate provides a
|
||||
//! `LinkedHashMap<K, V>` type that is serializable by Serde because the crate
|
||||
//! provides an implementation of `Serialize` for it.
|
||||
//!
|
||||
//! # The Serializer trait
|
||||
//!
|
||||
//! `Serializer` implementations are provided by third-party crates, for example
|
||||
//! [`serde_json`][serde_json], [`serde_yaml`][serde_yaml] and
|
||||
//! [`bincode`][bincode].
|
||||
//!
|
||||
//! A partial list of well-maintained formats is given on the [Serde
|
||||
//! website][data-formats].
|
||||
//!
|
||||
//! # Implementations of Serialize provided by Serde
|
||||
//!
|
||||
//! - **Primitive types**:
|
||||
//! - bool
|
||||
//! - isize, i8, i16, i32, i64
|
||||
//! - usize, u8, u16, u32, u64
|
||||
//! - f32, f64
|
||||
//! - char
|
||||
//! - str
|
||||
//! - &T and &mut T
|
||||
//! - **Compound types**:
|
||||
//! - [T]
|
||||
//! - [T; 0] through [T; 32]
|
||||
//! - tuples up to size 16
|
||||
//! - **Common standard library types**:
|
||||
//! - String
|
||||
//! - Option\<T\>
|
||||
//! - Result\<T, E\>
|
||||
//! - PhantomData\<T\>
|
||||
//! - **Wrapper types**:
|
||||
//! - Box\<T\>
|
||||
//! - Rc\<T\>
|
||||
//! - Arc\<T\>
|
||||
//! - Cow\<'a, T\>
|
||||
//! - **Collection types**:
|
||||
//! - BTreeMap\<K, V\>
|
||||
//! - BTreeSet\<T\>
|
||||
//! - BinaryHeap\<T\>
|
||||
//! - HashMap\<K, V, H\>
|
||||
//! - HashSet\<T, H\>
|
||||
//! - LinkedList\<T\>
|
||||
//! - VecDeque\<T\>
|
||||
//! - Vec\<T\>
|
||||
//! - EnumSet\<T\> (unstable)
|
||||
//! - Range\<T\> (unstable)
|
||||
//! - RangeInclusive\<T\> (unstable)
|
||||
//! - **Miscellaneous standard library types**:
|
||||
//! - Duration
|
||||
//! - Path
|
||||
//! - PathBuf
|
||||
//! - NonZero\<T\> (unstable)
|
||||
//! - **Net types**:
|
||||
//! - IpAddr
|
||||
//! - Ipv4Addr
|
||||
//! - Ipv6Addr
|
||||
//! - SocketAddr
|
||||
//! - SocketAddrV4
|
||||
//! - SocketAddrV6
|
||||
//!
|
||||
//! [codegen]: https://serde.rs/codegen.html
|
||||
//! [impl-serialize]: https://serde.rs/impl-serialize.html
|
||||
//! [serde_json]: https://github.com/serde-rs/json
|
||||
//! [serde_yaml]: https://github.com/dtolnay/serde-yaml
|
||||
//! [bincode]: https://github.com/TyOverby/bincode
|
||||
//! [data-formats]: https://serde.rs/#data-formats
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use std::error;
|
||||
#[cfg(not(feature = "std"))]
|
||||
use error;
|
||||
|
||||
use core::fmt::Display;
|
||||
use core::iter::IntoIterator;
|
||||
|
||||
mod impls;
|
||||
mod impossible;
|
||||
|
||||
// Helpers used by generated code. Not public API.
|
||||
#[doc(hidden)]
|
||||
pub mod private;
|
||||
|
||||
pub use self::impossible::Impossible;
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// Trait used by `Serialize` implementations to generically construct errors
|
||||
/// belonging to the `Serializer` against which they are currently running.
|
||||
pub trait Error: Sized + error::Error {
|
||||
/// Raised when a `Serialize` implementation encounters a general error
|
||||
/// while serializing a type.
|
||||
///
|
||||
/// The message should not be capitalized and should not end with a period.
|
||||
///
|
||||
/// For example, a filesystem `Path` may refuse to serialize itself if it
|
||||
/// contains invalid UTF-8 data.
|
||||
///
|
||||
/// ```rust
|
||||
/// # use serde::ser::{Serialize, Serializer, Error};
|
||||
/// # struct Path;
|
||||
/// # impl Path { fn to_str(&self) -> Option<&str> { unimplemented!() } }
|
||||
/// impl Serialize for Path {
|
||||
/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
/// where S: Serializer
|
||||
/// {
|
||||
/// match self.to_str() {
|
||||
/// Some(s) => s.serialize(serializer),
|
||||
/// None => Err(Error::custom("path contains invalid UTF-8 characters")),
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
fn custom<T: Display>(msg: T) -> Self;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// A **data structure** that can be serialized into any data format supported
|
||||
/// by Serde.
|
||||
///
|
||||
/// Serde provides `Serialize` implementations for many Rust primitive and
|
||||
/// standard library types. The complete list is [here][ser]. All of these can
|
||||
/// be serialized using Serde out of the box.
|
||||
///
|
||||
/// Additionally, Serde provides a procedural macro called `serde_derive` to
|
||||
/// automatically generate `Serialize` implementations for structs and enums in
|
||||
/// your program. See the [codegen section of the manual][codegen] for how to
|
||||
/// use this.
|
||||
///
|
||||
/// In rare cases it may be necessary to implement `Serialize` manually for some
|
||||
/// type in your program. See the [Implementing `Serialize`][impl-serialize]
|
||||
/// section of the manual for more about this.
|
||||
///
|
||||
/// Third-party crates may provide `Serialize` implementations for types that
|
||||
/// they expose. For example the `linked-hash-map` crate provides a
|
||||
/// `LinkedHashMap<K, V>` type that is serializable by Serde because the crate
|
||||
/// provides an implementation of `Serialize` for it.
|
||||
///
|
||||
/// [ser]: https://docs.serde.rs/serde/ser/index.html
|
||||
/// [codegen]: https://serde.rs/codegen.html
|
||||
/// [impl-serialize]: https://serde.rs/impl-serialize.html
|
||||
pub trait Serialize {
|
||||
/// Serialize this value into the given Serde serializer.
|
||||
///
|
||||
/// See the [Implementing `Serialize`][impl-serialize] section of the manual
|
||||
/// for more information about how to implement this method.
|
||||
///
|
||||
/// [impl-serialize]: https://serde.rs/impl-serialize.html
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// A **data format** that can serialize any data structure supported by Serde.
|
||||
///
|
||||
/// The role of this trait is to define the serialization half of the Serde data
|
||||
/// model, which is a way to categorize every Rust data structure into one of 28
|
||||
/// possible types. Each method of the `Serializer` trait corresponds to one of
|
||||
/// the types of the data model.
|
||||
///
|
||||
/// Implementations of `Serialize` map themselves into this data model by
|
||||
/// invoking exactly one of the `Serializer` methods.
|
||||
///
|
||||
/// The types that make up the Serde data model are:
|
||||
///
|
||||
/// - 12 primitive types:
|
||||
/// - bool
|
||||
/// - i8, i16, i32, i64
|
||||
/// - u8, u16, u32, u64
|
||||
/// - f32, f64
|
||||
/// - char
|
||||
/// - string
|
||||
/// - byte array - [u8]
|
||||
/// - option
|
||||
/// - either none or some value
|
||||
/// - unit
|
||||
/// - unit is the type of () in Rust
|
||||
/// - unit_struct
|
||||
/// - for example `struct Unit` or `PhantomData<T>`
|
||||
/// - unit_variant
|
||||
/// - the `E::A` and `E::B` in `enum E { A, B }`
|
||||
/// - newtype_struct
|
||||
/// - for example `struct Millimeters(u8)`
|
||||
/// - newtype_variant
|
||||
/// - the `E::N` in `enum E { N(u8) }`
|
||||
/// - seq
|
||||
/// - a dynamically sized sequence of values, for example `Vec<T>` or
|
||||
/// `HashSet<T>`
|
||||
/// - seq_fixed_size
|
||||
/// - a statically sized sequence of values for which the size will be known
|
||||
/// at deserialization time without looking at the serialized data, for
|
||||
/// example `[u64; 10]`
|
||||
/// - tuple
|
||||
/// - for example `(u8,)` or `(String, u64, Vec<T>)`
|
||||
/// - tuple_struct
|
||||
/// - for example `struct Rgb(u8, u8, u8)`
|
||||
/// - tuple_variant
|
||||
/// - the `E::T` in `enum E { T(u8, u8) }`
|
||||
/// - map
|
||||
/// - for example `BTreeMap<K, V>`
|
||||
/// - struct
|
||||
/// - a key-value pairing in which the keys will be known at deserialization
|
||||
/// time without looking at the serialized data, for example `struct S { r:
|
||||
/// u8, g: u8, b: u8 }`
|
||||
/// - struct_variant
|
||||
/// - the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`
|
||||
///
|
||||
/// Many Serde serializers produce text or binary data as output, for example
|
||||
/// JSON or Bincode. This is not a requirement of the `Serializer` trait, and
|
||||
/// there are serializers that do not produce text or binary output. One example
|
||||
/// is the `serde_json::value::Serializer` (distinct from the main `serde_json`
|
||||
/// serializer) that produces a `serde_json::Value` data structure in memory as
|
||||
/// output.
|
||||
pub trait Serializer: Sized {
|
||||
/// The output type produced by this `Serializer` during successful
|
||||
/// serialization. Most serializers that produce text or binary output
|
||||
/// should set `Ok = ()` and serialize into an `io::Write` or buffer
|
||||
/// contained within the `Serializer` instance. Serializers that build
|
||||
/// in-memory data structures may be simplified by using `Ok` to propagate
|
||||
/// the data structure around.
|
||||
type Ok;
|
||||
|
||||
/// The error type when some error occurs during serialization.
|
||||
type Error: Error;
|
||||
|
||||
/// Type returned from `serialize_seq` and `serialize_seq_fixed_size` for
|
||||
/// serializing the content of the sequence.
|
||||
type SerializeSeq: SerializeSeq<Ok=Self::Ok, Error=Self::Error>;
|
||||
|
||||
/// Type returned from `serialize_tuple` for serializing the content of the
|
||||
/// tuple.
|
||||
type SerializeTuple: SerializeTuple<Ok=Self::Ok, Error=Self::Error>;
|
||||
|
||||
/// Type returned from `serialize_tuple_struct` for serializing the content
|
||||
/// of the tuple struct.
|
||||
type SerializeTupleStruct: SerializeTupleStruct<Ok=Self::Ok, Error=Self::Error>;
|
||||
|
||||
/// Type returned from `serialize_tuple_variant` for serializing the content
|
||||
/// of the tuple variant.
|
||||
type SerializeTupleVariant: SerializeTupleVariant<Ok=Self::Ok, Error=Self::Error>;
|
||||
|
||||
/// Type returned from `serialize_map` for serializing the content of the
|
||||
/// map.
|
||||
type SerializeMap: SerializeMap<Ok=Self::Ok, Error=Self::Error>;
|
||||
|
||||
/// Type returned from `serialize_struct` for serializing the content of the
|
||||
/// struct.
|
||||
type SerializeStruct: SerializeStruct<Ok=Self::Ok, Error=Self::Error>;
|
||||
|
||||
/// Type returned from `serialize_struct_variant` for serializing the
|
||||
/// content of the struct variant.
|
||||
type SerializeStructVariant: SerializeStructVariant<Ok=Self::Ok, Error=Self::Error>;
|
||||
|
||||
/// Serialize a `bool` value.
|
||||
fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize an `i8` value.
|
||||
///
|
||||
/// If the format does not differentiate between `i8` and `i64`, a
|
||||
/// reasonable implementation would be to cast the value to `i64` and
|
||||
/// forward to `serialize_i64`.
|
||||
fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize an `i16` value.
|
||||
///
|
||||
/// If the format does not differentiate between `i16` and `i64`, a
|
||||
/// reasonable implementation would be to cast the value to `i64` and
|
||||
/// forward to `serialize_i64`.
|
||||
fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize an `i32` value.
|
||||
///
|
||||
/// If the format does not differentiate between `i32` and `i64`, a
|
||||
/// reasonable implementation would be to cast the value to `i64` and
|
||||
/// forward to `serialize_i64`.
|
||||
fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize an `i64` value.
|
||||
fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a `u8` value.
|
||||
///
|
||||
/// If the format does not differentiate between `u8` and `u64`, a
|
||||
/// reasonable implementation would be to cast the value to `u64` and
|
||||
/// forward to `serialize_u64`.
|
||||
fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a `u16` value.
|
||||
///
|
||||
/// If the format does not differentiate between `u16` and `u64`, a
|
||||
/// reasonable implementation would be to cast the value to `u64` and
|
||||
/// forward to `serialize_u64`.
|
||||
fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a `u32` value.
|
||||
///
|
||||
/// If the format does not differentiate between `u32` and `u64`, a
|
||||
/// reasonable implementation would be to cast the value to `u64` and
|
||||
/// forward to `serialize_u64`.
|
||||
fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a `u64` value.
|
||||
fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize an `f32` value.
|
||||
///
|
||||
/// If the format does not differentiate between `f32` and `f64`, a
|
||||
/// reasonable implementation would be to cast the value to `f64` and
|
||||
/// forward to `serialize_f64`.
|
||||
fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize an `f64` value.
|
||||
fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a character.
|
||||
///
|
||||
/// If the format does not support characters, it is reasonable to serialize
|
||||
/// it as a single element `str` or a `u32`.
|
||||
fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a `&str`.
|
||||
fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a chunk of raw byte data.
|
||||
///
|
||||
/// Enables serializers to serialize byte slices more compactly or more
|
||||
/// efficiently than other types of slices. If no efficient implementation
|
||||
/// is available, a reasonable implementation would be to forward to
|
||||
/// `serialize_seq`. If forwarded, the implementation looks usually just
|
||||
/// like this:
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut seq = self.serialize_seq(Some(value.len()))?;
|
||||
/// for b in value {
|
||||
/// seq.serialize_element(b)?;
|
||||
/// }
|
||||
/// seq.end()
|
||||
/// ```
|
||||
fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a `None` value.
|
||||
fn serialize_none(self) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a `Some(T)` value.
|
||||
fn serialize_some<T: ?Sized + Serialize>(
|
||||
self,
|
||||
value: &T,
|
||||
) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a `()` value.
|
||||
fn serialize_unit(self) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a unit struct like `struct Unit` or `PhantomData<T>`.
|
||||
///
|
||||
/// A reasonable implementation would be to forward to `serialize_unit`.
|
||||
fn serialize_unit_struct(
|
||||
self,
|
||||
name: &'static str,
|
||||
) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a unit variant like `E::A` in `enum E { A, B }`.
|
||||
///
|
||||
/// The `name` is the name of the enum, the `variant_index` is the index of
|
||||
/// this variant within the enum, and the `variant` is the name of the
|
||||
/// variant.
|
||||
///
|
||||
/// A reasonable implementation would be to forward to `serialize_unit`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// match *self {
|
||||
/// E::A => serializer.serialize_unit_variant("E", 0, "A"),
|
||||
/// E::B => serializer.serialize_unit_variant("E", 1, "B"),
|
||||
/// }
|
||||
/// ```
|
||||
fn serialize_unit_variant(
|
||||
self,
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str,
|
||||
) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a newtype struct like `struct Millimeters(u8)`.
|
||||
///
|
||||
/// Serializers are encouraged to treat newtype structs as insignificant
|
||||
/// wrappers around the data they contain. A reasonable implementation would
|
||||
/// be to forward to `value.serialize(self)`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// serializer.serialize_newtype_struct("Millimeters", &self.0)
|
||||
/// ```
|
||||
fn serialize_newtype_struct<T: ?Sized + Serialize>(
|
||||
self,
|
||||
name: &'static str,
|
||||
value: &T,
|
||||
) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a newtype variant like `E::N` in `enum E { N(u8) }`.
|
||||
///
|
||||
/// The `name` is the name of the enum, the `variant_index` is the index of
|
||||
/// this variant within the enum, and the `variant` is the name of the
|
||||
/// variant. The `value` is the data contained within this newtype variant.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// match *self {
|
||||
/// E::N(ref n) => serializer.serialize_newtype_variant("E", 0, "N", n),
|
||||
/// }
|
||||
/// ```
|
||||
fn serialize_newtype_variant<T: ?Sized + Serialize>(
|
||||
self,
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str,
|
||||
value: &T,
|
||||
) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Begin to serialize a dynamically sized sequence. This call must be
|
||||
/// followed by zero or more calls to `serialize_element`, then a call to
|
||||
/// `end`.
|
||||
///
|
||||
/// The argument is the number of elements in the sequence, which may or may
|
||||
/// not be computable before the sequence is iterated. Some serializers only
|
||||
/// support sequences whose length is known up front.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut seq = serializer.serialize_seq(Some(self.len()))?;
|
||||
/// for element in self {
|
||||
/// seq.serialize_element(element)?;
|
||||
/// }
|
||||
/// seq.end()
|
||||
/// ```
|
||||
fn serialize_seq(
|
||||
self,
|
||||
len: Option<usize>,
|
||||
) -> Result<Self::SerializeSeq, Self::Error>;
|
||||
|
||||
/// Begin to serialize a statically sized sequence whose length will be
|
||||
/// known at deserialization time without looking at the serialized data.
|
||||
/// This call must be followed by zero or more calls to `serialize_element`,
|
||||
/// then a call to `end`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut seq = serializer.serialize_seq_fixed_size(self.len())?;
|
||||
/// for element in self {
|
||||
/// seq.serialize_element(element)?;
|
||||
/// }
|
||||
/// seq.end()
|
||||
/// ```
|
||||
fn serialize_seq_fixed_size(
|
||||
self,
|
||||
size: usize,
|
||||
) -> Result<Self::SerializeSeq, Self::Error>;
|
||||
|
||||
/// Begin to serialize a tuple. This call must be followed by zero or more
|
||||
/// calls to `serialize_field`, then a call to `end`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut tup = serializer.serialize_tuple(3)?;
|
||||
/// tup.serialize_field(&self.0)?;
|
||||
/// tup.serialize_field(&self.1)?;
|
||||
/// tup.serialize_field(&self.2)?;
|
||||
/// tup.end()
|
||||
/// ```
|
||||
fn serialize_tuple(
|
||||
self,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeTuple, Self::Error>;
|
||||
|
||||
/// Begin to serialize a tuple struct like `struct Rgb(u8, u8, u8)`. This
|
||||
/// call must be followed by zero or more calls to `serialize_field`, then a
|
||||
/// call to `end`.
|
||||
///
|
||||
/// The `name` is the name of the tuple struct and the `len` is the number
|
||||
/// of data fields that will be serialized.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?;
|
||||
/// ts.serialize_field(&self.0)?;
|
||||
/// ts.serialize_field(&self.1)?;
|
||||
/// ts.serialize_field(&self.2)?;
|
||||
/// ts.end()
|
||||
/// ```
|
||||
fn serialize_tuple_struct(
|
||||
self,
|
||||
name: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeTupleStruct, Self::Error>;
|
||||
|
||||
/// Begin to serialize a tuple variant like `E::T` in `enum E { T(u8, u8)
|
||||
/// }`. This call must be followed by zero or more calls to
|
||||
/// `serialize_field`, then a call to `end`.
|
||||
///
|
||||
/// The `name` is the name of the enum, the `variant_index` is the index of
|
||||
/// this variant within the enum, the `variant` is the name of the variant,
|
||||
/// and the `len` is the number of data fields that will be serialized.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// match *self {
|
||||
/// E::T(ref a, ref b) => {
|
||||
/// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?;
|
||||
/// tv.serialize_field(a)?;
|
||||
/// tv.serialize_field(b)?;
|
||||
/// tv.end()
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
fn serialize_tuple_variant(
|
||||
self,
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeTupleVariant, Self::Error>;
|
||||
|
||||
/// Begin to serialize a map. This call must be followed by zero or more
|
||||
/// calls to `serialize_key` and `serialize_value`, then a call to `end`.
|
||||
///
|
||||
/// The argument is the number of elements in the map, which may or may not
|
||||
/// be computable before the map is iterated. Some serializers only support
|
||||
/// maps whose length is known up front.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut map = serializer.serialize_map(Some(self.len()))?;
|
||||
/// for (k, v) in self {
|
||||
/// map.serialize_entry(k, v)?;
|
||||
/// }
|
||||
/// map.end()
|
||||
/// ```
|
||||
fn serialize_map(
|
||||
self,
|
||||
len: Option<usize>,
|
||||
) -> Result<Self::SerializeMap, Self::Error>;
|
||||
|
||||
/// Begin to serialize a struct like `struct Rgb { r: u8, g: u8, b: u8 }`.
|
||||
/// This call must be followed by zero or more calls to `serialize_field`,
|
||||
/// then a call to `end`.
|
||||
///
|
||||
/// The `name` is the name of the struct and the `len` is the number of
|
||||
/// data fields that will be serialized.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut struc = serializer.serialize_struct("Rgb", 3)?;
|
||||
/// struc.serialize_field("r", &self.r)?;
|
||||
/// struc.serialize_field("g", &self.g)?;
|
||||
/// struc.serialize_field("b", &self.b)?;
|
||||
/// struc.end()
|
||||
/// ```
|
||||
fn serialize_struct(
|
||||
self,
|
||||
name: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeStruct, Self::Error>;
|
||||
|
||||
/// Begin to serialize a struct variant like `E::S` in `enum E { S { r: u8,
|
||||
/// g: u8, b: u8 } }`. This call must be followed by zero or more calls to
|
||||
/// `serialize_field`, then a call to `end`.
|
||||
///
|
||||
/// The `name` is the name of the enum, the `variant_index` is the index of
|
||||
/// this variant within the enum, the `variant` is the name of the variant,
|
||||
/// and the `len` is the number of data fields that will be serialized.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// match *self {
|
||||
/// E::S { ref r, ref g, ref b } => {
|
||||
/// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?;
|
||||
/// sv.serialize_field("r", r)?;
|
||||
/// sv.serialize_field("g", g)?;
|
||||
/// sv.serialize_field("b", b)?;
|
||||
/// sv.end()
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
fn serialize_struct_variant(
|
||||
self,
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeStructVariant, Self::Error>;
|
||||
|
||||
/// Collect an iterator as a sequence.
|
||||
///
|
||||
/// The default implementation serializes each item yielded by the iterator
|
||||
/// using `Self::SerializeSeq`. Implementors should not need to override
|
||||
/// this method.
|
||||
fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error>
|
||||
where I: IntoIterator,
|
||||
<I as IntoIterator>::Item: Serialize,
|
||||
{
|
||||
let iter = iter.into_iter();
|
||||
let mut serializer = try!(self.serialize_seq(iter.len_hint()));
|
||||
for item in iter {
|
||||
try!(serializer.serialize_element(&item));
|
||||
}
|
||||
serializer.end()
|
||||
}
|
||||
|
||||
/// Collect an iterator as a map.
|
||||
///
|
||||
/// The default implementation serializes each pair yielded by the iterator
|
||||
/// using `Self::SerializeMap`. Implementors should not need to override
|
||||
/// this method.
|
||||
fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error>
|
||||
where K: Serialize,
|
||||
V: Serialize,
|
||||
I: IntoIterator<Item = (K, V)>,
|
||||
{
|
||||
let iter = iter.into_iter();
|
||||
let mut serializer = try!(self.serialize_map(iter.len_hint()));
|
||||
for (key, value) in iter {
|
||||
try!(serializer.serialize_entry(&key, &value));
|
||||
}
|
||||
serializer.end()
|
||||
}
|
||||
}
|
||||
|
||||
/// Returned from `Serializer::serialize_seq` and
|
||||
/// `Serializer::serialize_seq_fixed_size`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut seq = serializer.serialize_seq(Some(self.len()))?;
|
||||
/// for element in self {
|
||||
/// seq.serialize_element(element)?;
|
||||
/// }
|
||||
/// seq.end()
|
||||
/// ```
|
||||
pub trait SerializeSeq {
|
||||
/// Must match the `Ok` type of our `Serializer`.
|
||||
type Ok;
|
||||
|
||||
/// Must match the `Error` type of our `Serializer`.
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a sequence element.
|
||||
fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;
|
||||
|
||||
/// Finish serializing a sequence.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
}
|
||||
|
||||
/// Returned from `Serializer::serialize_tuple`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut tup = serializer.serialize_tuple(3)?;
|
||||
/// tup.serialize_field(&self.0)?;
|
||||
/// tup.serialize_field(&self.1)?;
|
||||
/// tup.serialize_field(&self.2)?;
|
||||
/// tup.end()
|
||||
/// ```
|
||||
pub trait SerializeTuple {
|
||||
/// Must match the `Ok` type of our `Serializer`.
|
||||
type Ok;
|
||||
|
||||
/// Must match the `Error` type of our `Serializer`.
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a tuple element.
|
||||
fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;
|
||||
|
||||
/// Finish serializing a tuple.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
}
|
||||
|
||||
/// Returned from `Serializer::serialize_tuple_struct`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?;
|
||||
/// ts.serialize_field(&self.0)?;
|
||||
/// ts.serialize_field(&self.1)?;
|
||||
/// ts.serialize_field(&self.2)?;
|
||||
/// ts.end()
|
||||
/// ```
|
||||
pub trait SerializeTupleStruct {
|
||||
/// Must match the `Ok` type of our `Serializer`.
|
||||
type Ok;
|
||||
|
||||
/// Must match the `Error` type of our `Serializer`.
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a tuple struct field.
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;
|
||||
|
||||
/// Finish serializing a tuple struct.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
}
|
||||
|
||||
/// Returned from `Serializer::serialize_tuple_variant`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// match *self {
|
||||
/// E::T(ref a, ref b) => {
|
||||
/// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?;
|
||||
/// tv.serialize_field(a)?;
|
||||
/// tv.serialize_field(b)?;
|
||||
/// tv.end()
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub trait SerializeTupleVariant {
|
||||
/// Must match the `Ok` type of our `Serializer`.
|
||||
type Ok;
|
||||
|
||||
/// Must match the `Error` type of our `Serializer`.
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a tuple variant field.
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;
|
||||
|
||||
/// Finish serializing a tuple variant.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
}
|
||||
|
||||
/// Returned from `Serializer::serialize_map`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut map = serializer.serialize_map(Some(self.len()))?;
|
||||
/// for (k, v) in self {
|
||||
/// map.serialize_entry(k, v)?;
|
||||
/// }
|
||||
/// map.end()
|
||||
/// ```
|
||||
pub trait SerializeMap {
|
||||
/// Must match the `Ok` type of our `Serializer`.
|
||||
type Ok;
|
||||
|
||||
/// Must match the `Error` type of our `Serializer`.
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a map key.
|
||||
fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> Result<(), Self::Error>;
|
||||
|
||||
/// Serialize a map value.
|
||||
fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;
|
||||
|
||||
/// Serialize a map entry consisting of a key and a value.
|
||||
///
|
||||
/// Some `Serialize` types are not able to hold a key and value in memory at
|
||||
/// the same time so `SerializeMap` implementations are required to support
|
||||
/// `serialize_key` and `serialize_value` individually. The
|
||||
/// `serialize_entry` method allows serializers to optimize for the case
|
||||
/// where key and value are both available. `Serialize` implementations are
|
||||
/// encouraged to use `serialize_entry` if possible.
|
||||
///
|
||||
/// The default implementation delegates to `serialize_key` and
|
||||
/// `serialize_value`. This is appropriate for serializers that do not care
|
||||
/// about performance or are not able to optimize `serialize_entry` any
|
||||
/// better than this.
|
||||
fn serialize_entry<K: ?Sized + Serialize, V: ?Sized + Serialize>(
|
||||
&mut self,
|
||||
key: &K,
|
||||
value: &V,
|
||||
) -> Result<(), Self::Error> {
|
||||
try!(self.serialize_key(key));
|
||||
self.serialize_value(value)
|
||||
}
|
||||
|
||||
/// Finish serializing a map.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
}
|
||||
|
||||
/// Returned from `Serializer::serialize_struct`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut struc = serializer.serialize_struct("Rgb", 3)?;
|
||||
/// struc.serialize_field("r", &self.r)?;
|
||||
/// struc.serialize_field("g", &self.g)?;
|
||||
/// struc.serialize_field("b", &self.b)?;
|
||||
/// struc.end()
|
||||
/// ```
|
||||
pub trait SerializeStruct {
|
||||
/// Must match the `Ok` type of our `Serializer`.
|
||||
type Ok;
|
||||
|
||||
/// Must match the `Error` type of our `Serializer`.
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a struct field.
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>;
|
||||
|
||||
/// Finish serializing a struct.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
}
|
||||
|
||||
/// Returned from `Serializer::serialize_struct_variant`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// match *self {
|
||||
/// E::S { ref r, ref g, ref b } => {
|
||||
/// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?;
|
||||
/// sv.serialize_field("r", r)?;
|
||||
/// sv.serialize_field("g", g)?;
|
||||
/// sv.serialize_field("b", b)?;
|
||||
/// sv.end()
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub trait SerializeStructVariant {
|
||||
/// Must match the `Ok` type of our `Serializer`.
|
||||
type Ok;
|
||||
|
||||
/// Must match the `Error` type of our `Serializer`.
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a struct variant field.
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>;
|
||||
|
||||
/// Finish serializing a struct variant.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
}
|
||||
|
||||
trait LenHint: Iterator {
|
||||
fn len_hint(&self) -> Option<usize>;
|
||||
}
|
||||
|
||||
impl<I: Iterator> LenHint for I {
|
||||
#[cfg(not(feature = "unstable"))]
|
||||
fn len_hint(&self) -> Option<usize> {
|
||||
iterator_len_hint(self)
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
default fn len_hint(&self) -> Option<usize> {
|
||||
iterator_len_hint(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
impl<I: ExactSizeIterator> LenHint for I {
|
||||
fn len_hint(&self) -> Option<usize> {
|
||||
Some(self.len())
|
||||
}
|
||||
}
|
||||
|
||||
fn iterator_len_hint<I: Iterator>(iter: &I) -> Option<usize> {
|
||||
match iter.size_hint() {
|
||||
(lo, Some(hi)) if lo == hi => Some(lo),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
use core::fmt::{self, Display};
|
||||
|
||||
use ser::{self, Serialize, Serializer, SerializeMap, SerializeStruct};
|
||||
|
||||
/// Not public API.
|
||||
pub fn serialize_tagged_newtype<S, T>(
|
||||
serializer: S,
|
||||
type_ident: &'static str,
|
||||
variant_ident: &'static str,
|
||||
tag: &'static str,
|
||||
variant_name: &'static str,
|
||||
value: T,
|
||||
) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
T: Serialize
|
||||
{
|
||||
value.serialize(TaggedSerializer {
|
||||
type_ident: type_ident,
|
||||
variant_ident: variant_ident,
|
||||
tag: tag,
|
||||
variant_name: variant_name,
|
||||
delegate: serializer,
|
||||
})
|
||||
}
|
||||
|
||||
struct TaggedSerializer<S> {
|
||||
type_ident: &'static str,
|
||||
variant_ident: &'static str,
|
||||
tag: &'static str,
|
||||
variant_name: &'static str,
|
||||
delegate: S,
|
||||
}
|
||||
|
||||
enum Unsupported {
|
||||
Boolean,
|
||||
Integer,
|
||||
Float,
|
||||
Char,
|
||||
String,
|
||||
ByteArray,
|
||||
Optional,
|
||||
Unit,
|
||||
UnitStruct,
|
||||
Sequence,
|
||||
Tuple,
|
||||
TupleStruct,
|
||||
Enum,
|
||||
}
|
||||
|
||||
impl Display for Unsupported {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
Unsupported::Boolean => formatter.write_str("a boolean"),
|
||||
Unsupported::Integer => formatter.write_str("an integer"),
|
||||
Unsupported::Float => formatter.write_str("a float"),
|
||||
Unsupported::Char => formatter.write_str("a char"),
|
||||
Unsupported::String => formatter.write_str("a string"),
|
||||
Unsupported::ByteArray => formatter.write_str("a byte array"),
|
||||
Unsupported::Optional => formatter.write_str("an optional"),
|
||||
Unsupported::Unit => formatter.write_str("unit"),
|
||||
Unsupported::UnitStruct => formatter.write_str("a unit struct"),
|
||||
Unsupported::Sequence => formatter.write_str("a sequence"),
|
||||
Unsupported::Tuple => formatter.write_str("a tuple"),
|
||||
Unsupported::TupleStruct => formatter.write_str("a tuple struct"),
|
||||
Unsupported::Enum => formatter.write_str("an enum"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Error {
|
||||
type_ident: &'static str,
|
||||
variant_ident: &'static str,
|
||||
ty: Unsupported,
|
||||
}
|
||||
|
||||
impl Display for Error {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(formatter,
|
||||
"cannot serialize tagged newtype variant {}::{} containing {}",
|
||||
self.type_ident, self.variant_ident, self.ty)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> TaggedSerializer<S>
|
||||
where S: Serializer
|
||||
{
|
||||
fn bad_type(self, what: Unsupported) -> S::Error {
|
||||
ser::Error::custom(Error {
|
||||
type_ident: self.type_ident,
|
||||
variant_ident: self.variant_ident,
|
||||
ty: what,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Serializer for TaggedSerializer<S>
|
||||
where S: Serializer
|
||||
{
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
|
||||
type SerializeSeq = S::SerializeSeq;
|
||||
type SerializeTuple = S::SerializeTuple;
|
||||
type SerializeTupleStruct = S::SerializeTupleStruct;
|
||||
type SerializeTupleVariant = S::SerializeTupleVariant;
|
||||
type SerializeMap = S::SerializeMap;
|
||||
type SerializeStruct = S::SerializeStruct;
|
||||
type SerializeStructVariant = S::SerializeStructVariant;
|
||||
|
||||
fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Boolean))
|
||||
}
|
||||
|
||||
fn serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_u8(self, _: u8) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_u16(self, _: u16) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_u32(self, _: u32) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_u64(self, _: u64) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Float))
|
||||
}
|
||||
|
||||
fn serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Float))
|
||||
}
|
||||
|
||||
fn serialize_char(self, _: char) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Char))
|
||||
}
|
||||
|
||||
fn serialize_str(self, _: &str) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::String))
|
||||
}
|
||||
|
||||
fn serialize_bytes(self, _: &[u8]) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::ByteArray))
|
||||
}
|
||||
|
||||
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Optional))
|
||||
}
|
||||
|
||||
fn serialize_some<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error>
|
||||
where T: Serialize
|
||||
{
|
||||
Err(self.bad_type(Unsupported::Optional))
|
||||
}
|
||||
|
||||
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Unit))
|
||||
}
|
||||
|
||||
fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::UnitStruct))
|
||||
}
|
||||
|
||||
fn serialize_unit_variant(self, _: &'static str, _: usize, _: &'static str) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Enum))
|
||||
}
|
||||
|
||||
fn serialize_newtype_struct<T: ?Sized>(self, _: &'static str, value: &T) -> Result<Self::Ok, Self::Error>
|
||||
where T: Serialize
|
||||
{
|
||||
value.serialize(self)
|
||||
}
|
||||
|
||||
fn serialize_newtype_variant<T: ?Sized>(self, _: &'static str, _: usize, _: &'static str, _: &T) -> Result<Self::Ok, Self::Error>
|
||||
where T: Serialize
|
||||
{
|
||||
Err(self.bad_type(Unsupported::Enum))
|
||||
}
|
||||
|
||||
fn serialize_seq(self, _: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Sequence))
|
||||
}
|
||||
|
||||
fn serialize_seq_fixed_size(self, _: usize) -> Result<Self::SerializeSeq, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Sequence))
|
||||
}
|
||||
|
||||
fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Tuple))
|
||||
}
|
||||
|
||||
fn serialize_tuple_struct(self, _: &'static str, _: usize) -> Result<Self::SerializeTupleStruct, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::TupleStruct))
|
||||
}
|
||||
|
||||
fn serialize_tuple_variant(self, _: &'static str, _: usize, _: &'static str, _: usize) -> Result<Self::SerializeTupleVariant, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Enum))
|
||||
}
|
||||
|
||||
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
|
||||
let mut map = try!(self.delegate.serialize_map(len.map(|len| len + 1)));
|
||||
try!(map.serialize_entry(self.tag, self.variant_name));
|
||||
Ok(map)
|
||||
}
|
||||
|
||||
fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct, Self::Error> {
|
||||
let mut state = try!(self.delegate.serialize_struct(name, len + 1));
|
||||
try!(state.serialize_field(self.tag, self.variant_name));
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
fn serialize_struct_variant(self, _: &'static str, _: usize, _: &'static str, _: usize) -> Result<Self::SerializeStructVariant, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Enum))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Private utility functions
|
||||
|
||||
const TAG_CONT: u8 = 0b1000_0000;
|
||||
const TAG_TWO_B: u8 = 0b1100_0000;
|
||||
const TAG_THREE_B: u8 = 0b1110_0000;
|
||||
const TAG_FOUR_B: u8 = 0b1111_0000;
|
||||
const MAX_ONE_B: u32 = 0x80;
|
||||
const MAX_TWO_B: u32 = 0x800;
|
||||
const MAX_THREE_B: u32 = 0x10000;
|
||||
|
||||
#[inline]
|
||||
pub fn encode_utf8(c: char) -> EncodeUtf8 {
|
||||
let code = c as u32;
|
||||
let mut buf = [0; 4];
|
||||
let pos = if code < MAX_ONE_B {
|
||||
buf[3] = code as u8;
|
||||
3
|
||||
} else if code < MAX_TWO_B {
|
||||
buf[2] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
|
||||
buf[3] = (code & 0x3F) as u8 | TAG_CONT;
|
||||
2
|
||||
} else if code < MAX_THREE_B {
|
||||
buf[1] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
|
||||
buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[3] = (code & 0x3F) as u8 | TAG_CONT;
|
||||
1
|
||||
} else {
|
||||
buf[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
|
||||
buf[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[3] = (code & 0x3F) as u8 | TAG_CONT;
|
||||
0
|
||||
};
|
||||
EncodeUtf8 { buf: buf, pos: pos }
|
||||
}
|
||||
|
||||
pub struct EncodeUtf8 {
|
||||
buf: [u8; 4],
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl EncodeUtf8 {
|
||||
// FIXME: use this from_utf8_unchecked, since we know it can never fail
|
||||
pub fn as_str(&self) -> &str {
|
||||
::core::str::from_utf8(&self.buf[self.pos..]).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(non_upper_case_globals)]
|
||||
const Pattern_White_Space_table: &'static [(char, char)] = &[
|
||||
('\u{9}', '\u{d}'), ('\u{20}', '\u{20}'), ('\u{85}', '\u{85}'), ('\u{200e}', '\u{200f}'),
|
||||
('\u{2028}', '\u{2029}')
|
||||
];
|
||||
|
||||
fn bsearch_range_table(c: char, r: &'static [(char, char)]) -> bool {
|
||||
use core::cmp::Ordering::{Equal, Less, Greater};
|
||||
r.binary_search_by(|&(lo, hi)| {
|
||||
if c < lo {
|
||||
Greater
|
||||
} else if hi < c {
|
||||
Less
|
||||
} else {
|
||||
Equal
|
||||
}
|
||||
})
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
pub fn Pattern_White_Space(c: char) -> bool {
|
||||
bsearch_range_table(c, Pattern_White_Space_table)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "serde_codegen_internals"
|
||||
version = "0.13.0"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "AST representation used by Serde codegen. Unstable."
|
||||
homepage = "https://serde.rs"
|
||||
repository = "https://github.com/serde-rs/serde"
|
||||
documentation = "https://docs.serde.rs/serde_codegen_internals/"
|
||||
keywords = ["serde", "serialization"]
|
||||
include = ["Cargo.toml", "src/**/*.rs"]
|
||||
|
||||
[dependencies]
|
||||
syn = "0.11"
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "serde-rs/serde" }
|
||||
@@ -0,0 +1,116 @@
|
||||
use syn;
|
||||
use attr;
|
||||
use Ctxt;
|
||||
|
||||
pub struct Item<'a> {
|
||||
pub ident: syn::Ident,
|
||||
pub attrs: attr::Item,
|
||||
pub body: Body<'a>,
|
||||
pub generics: &'a syn::Generics,
|
||||
}
|
||||
|
||||
pub enum Body<'a> {
|
||||
Enum(Vec<Variant<'a>>),
|
||||
Struct(Style, Vec<Field<'a>>),
|
||||
}
|
||||
|
||||
pub struct Variant<'a> {
|
||||
pub ident: syn::Ident,
|
||||
pub attrs: attr::Variant,
|
||||
pub style: Style,
|
||||
pub fields: Vec<Field<'a>>,
|
||||
}
|
||||
|
||||
pub struct Field<'a> {
|
||||
pub ident: Option<syn::Ident>,
|
||||
pub attrs: attr::Field,
|
||||
pub ty: &'a syn::Ty,
|
||||
}
|
||||
|
||||
pub enum Style {
|
||||
Struct,
|
||||
Tuple,
|
||||
Newtype,
|
||||
Unit,
|
||||
}
|
||||
|
||||
impl<'a> Item<'a> {
|
||||
pub fn from_ast(cx: &Ctxt, item: &'a syn::MacroInput) -> Item<'a> {
|
||||
let attrs = attr::Item::from_ast(cx, item);
|
||||
|
||||
let body = match item.body {
|
||||
syn::Body::Enum(ref variants) => {
|
||||
Body::Enum(enum_from_ast(cx, variants))
|
||||
}
|
||||
syn::Body::Struct(ref variant_data) => {
|
||||
let (style, fields) = struct_from_ast(cx, variant_data);
|
||||
Body::Struct(style, fields)
|
||||
}
|
||||
};
|
||||
|
||||
Item {
|
||||
ident: item.ident.clone(),
|
||||
attrs: attrs,
|
||||
body: body,
|
||||
generics: &item.generics,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Body<'a> {
|
||||
pub fn all_fields(&'a self) -> Box<Iterator<Item=&'a Field<'a>> + 'a> {
|
||||
match *self {
|
||||
Body::Enum(ref variants) => {
|
||||
Box::new(variants.iter()
|
||||
.flat_map(|variant| variant.fields.iter()))
|
||||
}
|
||||
Body::Struct(_, ref fields) => {
|
||||
Box::new(fields.iter())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn enum_from_ast<'a>(cx: &Ctxt, variants: &'a [syn::Variant]) -> Vec<Variant<'a>> {
|
||||
variants.iter()
|
||||
.map(|variant| {
|
||||
let (style, fields) = struct_from_ast(cx, &variant.data);
|
||||
Variant {
|
||||
ident: variant.ident.clone(),
|
||||
attrs: attr::Variant::from_ast(cx, variant),
|
||||
style: style,
|
||||
fields: fields,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn struct_from_ast<'a>(cx: &Ctxt, data: &'a syn::VariantData) -> (Style, Vec<Field<'a>>) {
|
||||
match *data {
|
||||
syn::VariantData::Struct(ref fields) => {
|
||||
(Style::Struct, fields_from_ast(cx, fields))
|
||||
}
|
||||
syn::VariantData::Tuple(ref fields) if fields.len() == 1 => {
|
||||
(Style::Newtype, fields_from_ast(cx, fields))
|
||||
}
|
||||
syn::VariantData::Tuple(ref fields) => {
|
||||
(Style::Tuple, fields_from_ast(cx, fields))
|
||||
}
|
||||
syn::VariantData::Unit => {
|
||||
(Style::Unit, Vec::new())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fields_from_ast<'a>(cx: &Ctxt, fields: &'a [syn::Field]) -> Vec<Field<'a>> {
|
||||
fields.iter()
|
||||
.enumerate()
|
||||
.map(|(i, field)| {
|
||||
Field {
|
||||
ident: field.ident.clone(),
|
||||
attrs: attr::Field::from_ast(cx, i, field),
|
||||
ty: &field.ty,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,628 @@
|
||||
use Ctxt;
|
||||
use syn;
|
||||
use syn::MetaItem::{List, NameValue, Word};
|
||||
use syn::NestedMetaItem::{Literal, MetaItem};
|
||||
|
||||
// This module handles parsing of `#[serde(...)]` attributes. The entrypoints
|
||||
// are `attr::Item::from_ast`, `attr::Variant::from_ast`, and
|
||||
// `attr::Field::from_ast`. Each returns an instance of the corresponding
|
||||
// struct. Note that none of them return a Result. Unrecognized, malformed, or
|
||||
// duplicated attributes result in a span_err but otherwise are ignored. The
|
||||
// user will see errors simultaneously for all bad attributes in the crate
|
||||
// rather than just the first.
|
||||
|
||||
struct Attr<'c, T> {
|
||||
cx: &'c Ctxt,
|
||||
name: &'static str,
|
||||
value: Option<T>,
|
||||
}
|
||||
|
||||
impl<'c, T> Attr<'c, T> {
|
||||
fn none(cx: &'c Ctxt, name: &'static str) -> Self {
|
||||
Attr {
|
||||
cx: cx,
|
||||
name: name,
|
||||
value: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn set(&mut self, value: T) {
|
||||
if self.value.is_some() {
|
||||
self.cx.error(format!("duplicate serde attribute `{}`", self.name));
|
||||
} else {
|
||||
self.value = Some(value);
|
||||
}
|
||||
}
|
||||
|
||||
fn set_opt(&mut self, value: Option<T>) {
|
||||
if let Some(value) = value {
|
||||
self.set(value);
|
||||
}
|
||||
}
|
||||
|
||||
fn set_if_none(&mut self, value: T) {
|
||||
if self.value.is_none() {
|
||||
self.value = Some(value);
|
||||
}
|
||||
}
|
||||
|
||||
fn get(self) -> Option<T> {
|
||||
self.value
|
||||
}
|
||||
}
|
||||
|
||||
struct BoolAttr<'c>(Attr<'c, ()>);
|
||||
|
||||
impl<'c> BoolAttr<'c> {
|
||||
fn none(cx: &'c Ctxt, name: &'static str) -> Self {
|
||||
BoolAttr(Attr::none(cx, name))
|
||||
}
|
||||
|
||||
fn set_true(&mut self) {
|
||||
self.0.set(());
|
||||
}
|
||||
|
||||
fn get(&self) -> bool {
|
||||
self.0.value.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Name {
|
||||
serialize: String,
|
||||
deserialize: String,
|
||||
}
|
||||
|
||||
impl Name {
|
||||
/// Return the container name for the container when serializing.
|
||||
pub fn serialize_name(&self) -> String {
|
||||
self.serialize.clone()
|
||||
}
|
||||
|
||||
/// Return the container name for the container when deserializing.
|
||||
pub fn deserialize_name(&self) -> String {
|
||||
self.deserialize.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents container (e.g. struct) attribute information
|
||||
#[derive(Debug)]
|
||||
pub struct Item {
|
||||
name: Name,
|
||||
deny_unknown_fields: bool,
|
||||
ser_bound: Option<Vec<syn::WherePredicate>>,
|
||||
de_bound: Option<Vec<syn::WherePredicate>>,
|
||||
tag: EnumTag,
|
||||
}
|
||||
|
||||
/// Styles of representing an enum.
|
||||
#[derive(Debug)]
|
||||
pub enum EnumTag {
|
||||
/// The default.
|
||||
///
|
||||
/// ```json
|
||||
/// {"variant1": {"key1": "value1", "key2": "value2"}}
|
||||
/// ```
|
||||
External,
|
||||
|
||||
/// `#[serde(tag = "type")]`
|
||||
///
|
||||
/// ```json
|
||||
/// {"type": "variant1", "key1": "value1", "key2": "value2"}
|
||||
/// ```
|
||||
Internal(String),
|
||||
|
||||
/// `#[serde(untagged)]`
|
||||
///
|
||||
/// ```json
|
||||
/// {"key1": "value1", "key2": "value2"}
|
||||
/// ```
|
||||
None,
|
||||
}
|
||||
|
||||
impl Item {
|
||||
/// Extract out the `#[serde(...)]` attributes from an item.
|
||||
pub fn from_ast(cx: &Ctxt, item: &syn::MacroInput) -> Self {
|
||||
let mut ser_name = Attr::none(cx, "rename");
|
||||
let mut de_name = Attr::none(cx, "rename");
|
||||
let mut deny_unknown_fields = BoolAttr::none(cx, "deny_unknown_fields");
|
||||
let mut ser_bound = Attr::none(cx, "bound");
|
||||
let mut de_bound = Attr::none(cx, "bound");
|
||||
let mut untagged = BoolAttr::none(cx, "untagged");
|
||||
let mut internal_tag = Attr::none(cx, "tag");
|
||||
|
||||
for meta_items in item.attrs.iter().filter_map(get_serde_meta_items) {
|
||||
for meta_item in meta_items {
|
||||
match meta_item {
|
||||
// Parse `#[serde(rename="foo")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "rename" => {
|
||||
if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) {
|
||||
ser_name.set(s.clone());
|
||||
de_name.set(s);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(rename(serialize="foo", deserialize="bar"))]`
|
||||
MetaItem(List(ref name, ref meta_items)) if name == "rename" => {
|
||||
if let Ok((ser, de)) = get_renames(cx, meta_items) {
|
||||
ser_name.set_opt(ser);
|
||||
de_name.set_opt(de);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(deny_unknown_fields)]`
|
||||
MetaItem(Word(ref name)) if name == "deny_unknown_fields" => {
|
||||
deny_unknown_fields.set_true();
|
||||
}
|
||||
|
||||
// Parse `#[serde(bound="D: Serialize")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "bound" => {
|
||||
if let Ok(where_predicates) = parse_lit_into_where(cx, name.as_ref(), name.as_ref(), lit) {
|
||||
ser_bound.set(where_predicates.clone());
|
||||
de_bound.set(where_predicates);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(bound(serialize="D: Serialize", deserialize="D: Deserialize"))]`
|
||||
MetaItem(List(ref name, ref meta_items)) if name == "bound" => {
|
||||
if let Ok((ser, de)) = get_where_predicates(cx, meta_items) {
|
||||
ser_bound.set_opt(ser);
|
||||
de_bound.set_opt(de);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(untagged)]`
|
||||
MetaItem(Word(ref name)) if name == "untagged" => {
|
||||
match item.body {
|
||||
syn::Body::Enum(_) => {
|
||||
untagged.set_true();
|
||||
}
|
||||
syn::Body::Struct(_) => {
|
||||
cx.error("#[serde(untagged)] can only be used on enums")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(tag = "type")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "tag" => {
|
||||
if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) {
|
||||
match item.body {
|
||||
syn::Body::Enum(_) => {
|
||||
internal_tag.set(s);
|
||||
}
|
||||
syn::Body::Struct(_) => {
|
||||
cx.error("#[serde(tag = \"...\")] can only be used on enums")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MetaItem(ref meta_item) => {
|
||||
cx.error(format!("unknown serde container attribute `{}`",
|
||||
meta_item.name()));
|
||||
}
|
||||
|
||||
Literal(_) => {
|
||||
cx.error("unexpected literal in serde container attribute");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let tag = match (untagged.get(), internal_tag.get()) {
|
||||
(false, None) => EnumTag::External,
|
||||
(true, None) => EnumTag::None,
|
||||
(false, Some(tag)) => {
|
||||
// Check that there are no tuple variants.
|
||||
if let syn::Body::Enum(ref variants) = item.body {
|
||||
for variant in variants {
|
||||
match variant.data {
|
||||
syn::VariantData::Struct(_) | syn::VariantData::Unit => {}
|
||||
syn::VariantData::Tuple(ref fields) => {
|
||||
if fields.len() != 1 {
|
||||
cx.error("#[serde(tag = \"...\")] cannot be used with tuple variants");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
EnumTag::Internal(tag)
|
||||
}
|
||||
(true, Some(_)) => {
|
||||
cx.error("enum cannot be both untagged and internally tagged");
|
||||
EnumTag::External // doesn't matter, will error
|
||||
}
|
||||
};
|
||||
|
||||
Item {
|
||||
name: Name {
|
||||
serialize: ser_name.get().unwrap_or_else(|| item.ident.to_string()),
|
||||
deserialize: de_name.get().unwrap_or_else(|| item.ident.to_string()),
|
||||
},
|
||||
deny_unknown_fields: deny_unknown_fields.get(),
|
||||
ser_bound: ser_bound.get(),
|
||||
de_bound: de_bound.get(),
|
||||
tag: tag,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &Name {
|
||||
&self.name
|
||||
}
|
||||
|
||||
pub fn deny_unknown_fields(&self) -> bool {
|
||||
self.deny_unknown_fields
|
||||
}
|
||||
|
||||
pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> {
|
||||
self.ser_bound.as_ref().map(|vec| &vec[..])
|
||||
}
|
||||
|
||||
pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> {
|
||||
self.de_bound.as_ref().map(|vec| &vec[..])
|
||||
}
|
||||
|
||||
pub fn tag(&self) -> &EnumTag {
|
||||
&self.tag
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents variant attribute information
|
||||
#[derive(Debug)]
|
||||
pub struct Variant {
|
||||
name: Name,
|
||||
skip_deserializing: bool,
|
||||
skip_serializing: bool,
|
||||
}
|
||||
|
||||
impl Variant {
|
||||
pub fn from_ast(cx: &Ctxt, variant: &syn::Variant) -> Self {
|
||||
let mut ser_name = Attr::none(cx, "rename");
|
||||
let mut de_name = Attr::none(cx, "rename");
|
||||
let mut skip_deserializing = BoolAttr::none(cx, "skip_deserializing");
|
||||
let mut skip_serializing = BoolAttr::none(cx, "skip_serializing");
|
||||
|
||||
for meta_items in variant.attrs.iter().filter_map(get_serde_meta_items) {
|
||||
for meta_item in meta_items {
|
||||
match meta_item {
|
||||
// Parse `#[serde(rename="foo")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "rename" => {
|
||||
if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) {
|
||||
ser_name.set(s.clone());
|
||||
de_name.set(s);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(rename(serialize="foo", deserialize="bar"))]`
|
||||
MetaItem(List(ref name, ref meta_items)) if name == "rename" => {
|
||||
if let Ok((ser, de)) = get_renames(cx, meta_items) {
|
||||
ser_name.set_opt(ser);
|
||||
de_name.set_opt(de);
|
||||
}
|
||||
}
|
||||
// Parse `#[serde(skip_deserializing)]`
|
||||
MetaItem(Word(ref name)) if name == "skip_deserializing" => {
|
||||
skip_deserializing.set_true();
|
||||
}
|
||||
// Parse `#[serde(skip_serializing)]`
|
||||
MetaItem(Word(ref name)) if name == "skip_serializing" => {
|
||||
skip_serializing.set_true();
|
||||
}
|
||||
|
||||
MetaItem(ref meta_item) => {
|
||||
cx.error(format!("unknown serde variant attribute `{}`",
|
||||
meta_item.name()));
|
||||
}
|
||||
|
||||
Literal(_) => {
|
||||
cx.error("unexpected literal in serde variant attribute");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Variant {
|
||||
name: Name {
|
||||
serialize: ser_name.get().unwrap_or_else(|| variant.ident.to_string()),
|
||||
deserialize: de_name.get().unwrap_or_else(|| variant.ident.to_string()),
|
||||
},
|
||||
skip_deserializing: skip_deserializing.get(),
|
||||
skip_serializing: skip_serializing.get(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &Name {
|
||||
&self.name
|
||||
}
|
||||
|
||||
pub fn skip_deserializing(&self) -> bool {
|
||||
self.skip_deserializing
|
||||
}
|
||||
|
||||
pub fn skip_serializing(&self) -> bool {
|
||||
self.skip_serializing
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents field attribute information
|
||||
#[derive(Debug)]
|
||||
pub struct Field {
|
||||
name: Name,
|
||||
skip_serializing: bool,
|
||||
skip_deserializing: bool,
|
||||
skip_serializing_if: Option<syn::Path>,
|
||||
default: FieldDefault,
|
||||
serialize_with: Option<syn::Path>,
|
||||
deserialize_with: Option<syn::Path>,
|
||||
ser_bound: Option<Vec<syn::WherePredicate>>,
|
||||
de_bound: Option<Vec<syn::WherePredicate>>,
|
||||
}
|
||||
|
||||
/// Represents the default to use for a field when deserializing.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum FieldDefault {
|
||||
/// Field must always be specified because it does not have a default.
|
||||
None,
|
||||
/// The default is given by `std::default::Default::default()`.
|
||||
Default,
|
||||
/// The default is given by this function.
|
||||
Path(syn::Path),
|
||||
}
|
||||
|
||||
impl Field {
|
||||
/// Extract out the `#[serde(...)]` attributes from a struct field.
|
||||
pub fn from_ast(cx: &Ctxt,
|
||||
index: usize,
|
||||
field: &syn::Field) -> Self {
|
||||
let mut ser_name = Attr::none(cx, "rename");
|
||||
let mut de_name = Attr::none(cx, "rename");
|
||||
let mut skip_serializing = BoolAttr::none(cx, "skip_serializing");
|
||||
let mut skip_deserializing = BoolAttr::none(cx, "skip_deserializing");
|
||||
let mut skip_serializing_if = Attr::none(cx, "skip_serializing_if");
|
||||
let mut default = Attr::none(cx, "default");
|
||||
let mut serialize_with = Attr::none(cx, "serialize_with");
|
||||
let mut deserialize_with = Attr::none(cx, "deserialize_with");
|
||||
let mut ser_bound = Attr::none(cx, "bound");
|
||||
let mut de_bound = Attr::none(cx, "bound");
|
||||
|
||||
let ident = match field.ident {
|
||||
Some(ref ident) => ident.to_string(),
|
||||
None => index.to_string(),
|
||||
};
|
||||
|
||||
for meta_items in field.attrs.iter().filter_map(get_serde_meta_items) {
|
||||
for meta_item in meta_items {
|
||||
match meta_item {
|
||||
// Parse `#[serde(rename="foo")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "rename" => {
|
||||
if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) {
|
||||
ser_name.set(s.clone());
|
||||
de_name.set(s);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(rename(serialize="foo", deserialize="bar"))]`
|
||||
MetaItem(List(ref name, ref meta_items)) if name == "rename" => {
|
||||
if let Ok((ser, de)) = get_renames(cx, meta_items) {
|
||||
ser_name.set_opt(ser);
|
||||
de_name.set_opt(de);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(default)]`
|
||||
MetaItem(Word(ref name)) if name == "default" => {
|
||||
default.set(FieldDefault::Default);
|
||||
}
|
||||
|
||||
// Parse `#[serde(default="...")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "default" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
|
||||
default.set(FieldDefault::Path(path));
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(skip_serializing)]`
|
||||
MetaItem(Word(ref name)) if name == "skip_serializing" => {
|
||||
skip_serializing.set_true();
|
||||
}
|
||||
|
||||
// Parse `#[serde(skip_deserializing)]`
|
||||
MetaItem(Word(ref name)) if name == "skip_deserializing" => {
|
||||
skip_deserializing.set_true();
|
||||
}
|
||||
|
||||
// Parse `#[serde(skip_serializing_if="...")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "skip_serializing_if" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
|
||||
skip_serializing_if.set(path);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(serialize_with="...")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "serialize_with" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
|
||||
serialize_with.set(path);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(deserialize_with="...")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "deserialize_with" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
|
||||
deserialize_with.set(path);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(bound="D: Serialize")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "bound" => {
|
||||
if let Ok(where_predicates) = parse_lit_into_where(cx, name.as_ref(), name.as_ref(), lit) {
|
||||
ser_bound.set(where_predicates.clone());
|
||||
de_bound.set(where_predicates);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(bound(serialize="D: Serialize", deserialize="D: Deserialize"))]`
|
||||
MetaItem(List(ref name, ref meta_items)) if name == "bound" => {
|
||||
if let Ok((ser, de)) = get_where_predicates(cx, meta_items) {
|
||||
ser_bound.set_opt(ser);
|
||||
de_bound.set_opt(de);
|
||||
}
|
||||
}
|
||||
|
||||
MetaItem(ref meta_item) => {
|
||||
cx.error(format!("unknown serde field attribute `{}`",
|
||||
meta_item.name()));
|
||||
}
|
||||
|
||||
Literal(_) => {
|
||||
cx.error("unexpected literal in serde field attribute");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Is skip_deserializing, initialize the field to Default::default()
|
||||
// unless a different default is specified by `#[serde(default="...")]`
|
||||
if skip_deserializing.0.value.is_some() {
|
||||
default.set_if_none(FieldDefault::Default);
|
||||
}
|
||||
|
||||
Field {
|
||||
name: Name {
|
||||
serialize: ser_name.get().unwrap_or_else(|| ident.clone()),
|
||||
deserialize: de_name.get().unwrap_or(ident),
|
||||
},
|
||||
skip_serializing: skip_serializing.get(),
|
||||
skip_deserializing: skip_deserializing.get(),
|
||||
skip_serializing_if: skip_serializing_if.get(),
|
||||
default: default.get().unwrap_or(FieldDefault::None),
|
||||
serialize_with: serialize_with.get(),
|
||||
deserialize_with: deserialize_with.get(),
|
||||
ser_bound: ser_bound.get(),
|
||||
de_bound: de_bound.get(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &Name {
|
||||
&self.name
|
||||
}
|
||||
|
||||
pub fn skip_serializing(&self) -> bool {
|
||||
self.skip_serializing
|
||||
}
|
||||
|
||||
pub fn skip_deserializing(&self) -> bool {
|
||||
self.skip_deserializing
|
||||
}
|
||||
|
||||
pub fn skip_serializing_if(&self) -> Option<&syn::Path> {
|
||||
self.skip_serializing_if.as_ref()
|
||||
}
|
||||
|
||||
pub fn default(&self) -> &FieldDefault {
|
||||
&self.default
|
||||
}
|
||||
|
||||
pub fn serialize_with(&self) -> Option<&syn::Path> {
|
||||
self.serialize_with.as_ref()
|
||||
}
|
||||
|
||||
pub fn deserialize_with(&self) -> Option<&syn::Path> {
|
||||
self.deserialize_with.as_ref()
|
||||
}
|
||||
|
||||
pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> {
|
||||
self.ser_bound.as_ref().map(|vec| &vec[..])
|
||||
}
|
||||
|
||||
pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> {
|
||||
self.de_bound.as_ref().map(|vec| &vec[..])
|
||||
}
|
||||
}
|
||||
|
||||
type SerAndDe<T> = (Option<T>, Option<T>);
|
||||
|
||||
fn get_ser_and_de<T, F>(
|
||||
cx: &Ctxt,
|
||||
attr_name: &'static str,
|
||||
items: &[syn::NestedMetaItem],
|
||||
f: F
|
||||
) -> Result<SerAndDe<T>, ()>
|
||||
where F: Fn(&Ctxt, &str, &str, &syn::Lit) -> Result<T, ()>,
|
||||
{
|
||||
let mut ser_item = Attr::none(cx, attr_name);
|
||||
let mut de_item = Attr::none(cx, attr_name);
|
||||
|
||||
for item in items {
|
||||
match *item {
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "serialize" => {
|
||||
if let Ok(v) = f(cx, attr_name, name.as_ref(), lit) {
|
||||
ser_item.set(v);
|
||||
}
|
||||
}
|
||||
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "deserialize" => {
|
||||
if let Ok(v) = f(cx, attr_name, name.as_ref(), lit) {
|
||||
de_item.set(v);
|
||||
}
|
||||
}
|
||||
|
||||
_ => {
|
||||
cx.error(format!("malformed {0} attribute, expected `{0}(serialize = ..., deserialize = ...)`",
|
||||
attr_name));
|
||||
return Err(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok((ser_item.get(), de_item.get()))
|
||||
}
|
||||
|
||||
fn get_renames(
|
||||
cx: &Ctxt,
|
||||
items: &[syn::NestedMetaItem],
|
||||
) -> Result<SerAndDe<String>, ()> {
|
||||
get_ser_and_de(cx, "rename", items, get_string_from_lit)
|
||||
}
|
||||
|
||||
fn get_where_predicates(
|
||||
cx: &Ctxt,
|
||||
items: &[syn::NestedMetaItem],
|
||||
) -> Result<SerAndDe<Vec<syn::WherePredicate>>, ()> {
|
||||
get_ser_and_de(cx, "bound", items, parse_lit_into_where)
|
||||
}
|
||||
|
||||
pub fn get_serde_meta_items(attr: &syn::Attribute) -> Option<Vec<syn::NestedMetaItem>> {
|
||||
match attr.value {
|
||||
List(ref name, ref items) if name == "serde" => {
|
||||
Some(items.iter().cloned().collect())
|
||||
}
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
|
||||
fn get_string_from_lit(cx: &Ctxt, attr_name: &str, meta_item_name: &str, lit: &syn::Lit) -> Result<String, ()> {
|
||||
if let syn::Lit::Str(ref s, _) = *lit {
|
||||
Ok(s.clone())
|
||||
} else {
|
||||
cx.error(format!("expected serde {} attribute to be a string: `{} = \"...\"`",
|
||||
attr_name, meta_item_name));
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_lit_into_path(cx: &Ctxt, attr_name: &str, lit: &syn::Lit) -> Result<syn::Path, ()> {
|
||||
let string = try!(get_string_from_lit(cx, attr_name, attr_name, lit));
|
||||
syn::parse_path(&string).map_err(|err| cx.error(err))
|
||||
}
|
||||
|
||||
fn parse_lit_into_where(cx: &Ctxt, attr_name: &str, meta_item_name: &str, lit: &syn::Lit) -> Result<Vec<syn::WherePredicate>, ()> {
|
||||
let string = try!(get_string_from_lit(cx, attr_name, meta_item_name, lit));
|
||||
if string.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let where_string = format!("where {}", string);
|
||||
|
||||
syn::parse_where_clause(&where_string).map(|wh| wh.predicates).map_err(|err| cx.error(err))
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use std::fmt::Display;
|
||||
use std::cell::RefCell;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Ctxt {
|
||||
errors: RefCell<Option<Vec<String>>>,
|
||||
}
|
||||
|
||||
impl Ctxt {
|
||||
pub fn new() -> Self {
|
||||
Ctxt {
|
||||
errors: RefCell::new(Some(Vec::new())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn error<T: Display>(&self, msg: T) {
|
||||
self.errors.borrow_mut().as_mut().unwrap().push(msg.to_string());
|
||||
}
|
||||
|
||||
pub fn check(self) -> Result<(), String> {
|
||||
let mut errors = self.errors.borrow_mut().take().unwrap();
|
||||
match errors.len() {
|
||||
0 => Ok(()),
|
||||
1 => Err(errors.pop().unwrap()),
|
||||
n => {
|
||||
let mut msg = format!("{} errors:", n);
|
||||
for err in errors {
|
||||
msg.push_str("\n\t# ");
|
||||
msg.push_str(&err);
|
||||
}
|
||||
Err(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Ctxt {
|
||||
fn drop(&mut self) {
|
||||
if self.errors.borrow().is_some() {
|
||||
panic!("forgot to check for errors");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
extern crate syn;
|
||||
|
||||
pub mod ast;
|
||||
pub mod attr;
|
||||
|
||||
mod ctxt;
|
||||
pub use ctxt::Ctxt;
|
||||
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "serde_derive"
|
||||
version = "0.9.7"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "Macros 1.1 implementation of #[derive(Serialize, Deserialize)]"
|
||||
homepage = "https://serde.rs"
|
||||
repository = "https://github.com/serde-rs/serde"
|
||||
documentation = "https://serde.rs/codegen.html"
|
||||
keywords = ["serde", "serialization", "no_std"]
|
||||
include = ["Cargo.toml", "src/**/*.rs"]
|
||||
|
||||
[features]
|
||||
unstable = []
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "serde-rs/serde" }
|
||||
|
||||
[lib]
|
||||
name = "serde_derive"
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
quote = "0.3.8"
|
||||
serde_codegen_internals = { version = "=0.13.0", default-features = false, path = "../serde_codegen_internals" }
|
||||
syn = { version = "0.11", features = ["aster", "visit"] }
|
||||
@@ -0,0 +1,121 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use syn::{self, aster, visit};
|
||||
|
||||
use internals::ast::Item;
|
||||
use internals::attr;
|
||||
|
||||
// Remove the default from every type parameter because in the generated impls
|
||||
// they look like associated types: "error: associated type bindings are not
|
||||
// allowed here".
|
||||
pub fn without_defaults(generics: &syn::Generics) -> syn::Generics {
|
||||
syn::Generics {
|
||||
ty_params: generics.ty_params.iter().map(|ty_param| {
|
||||
syn::TyParam {
|
||||
default: None,
|
||||
.. ty_param.clone()
|
||||
}}).collect(),
|
||||
.. generics.clone()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_where_predicates(
|
||||
generics: &syn::Generics,
|
||||
predicates: &[syn::WherePredicate],
|
||||
) -> syn::Generics {
|
||||
aster::from_generics(generics.clone())
|
||||
.with_predicates(predicates.to_vec())
|
||||
.build()
|
||||
}
|
||||
|
||||
pub fn with_where_predicates_from_fields<F>(
|
||||
item: &Item,
|
||||
generics: &syn::Generics,
|
||||
from_field: F,
|
||||
) -> syn::Generics
|
||||
where F: Fn(&attr::Field) -> Option<&[syn::WherePredicate]>,
|
||||
{
|
||||
aster::from_generics(generics.clone())
|
||||
.with_predicates(
|
||||
item.body.all_fields()
|
||||
.flat_map(|field| from_field(&field.attrs))
|
||||
.flat_map(|predicates| predicates.to_vec()))
|
||||
.build()
|
||||
}
|
||||
|
||||
// Puts the given bound on any generic type parameters that are used in fields
|
||||
// for which filter returns true.
|
||||
//
|
||||
// For example, the following struct needs the bound `A: Serialize, B: Serialize`.
|
||||
//
|
||||
// struct S<'b, A, B: 'b, C> {
|
||||
// a: A,
|
||||
// b: Option<&'b B>
|
||||
// #[serde(skip_serializing)]
|
||||
// c: C,
|
||||
// }
|
||||
pub fn with_bound<F>(
|
||||
item: &Item,
|
||||
generics: &syn::Generics,
|
||||
filter: F,
|
||||
bound: &syn::Path,
|
||||
) -> syn::Generics
|
||||
where F: Fn(&attr::Field) -> bool,
|
||||
{
|
||||
struct FindTyParams {
|
||||
// Set of all generic type parameters on the current struct (A, B, C in
|
||||
// the example). Initialized up front.
|
||||
all_ty_params: HashSet<syn::Ident>,
|
||||
// Set of generic type parameters used in fields for which filter
|
||||
// returns true (A and B in the example). Filled in as the visitor sees
|
||||
// them.
|
||||
relevant_ty_params: HashSet<syn::Ident>,
|
||||
}
|
||||
impl visit::Visitor for FindTyParams {
|
||||
fn visit_path(&mut self, path: &syn::Path) {
|
||||
if let Some(seg) = path.segments.last() {
|
||||
if seg.ident == "PhantomData" {
|
||||
// Hardcoded exception, because PhantomData<T> implements
|
||||
// Serialize and Deserialize whether or not T implements it.
|
||||
return;
|
||||
}
|
||||
}
|
||||
if !path.global && path.segments.len() == 1 {
|
||||
let id = path.segments[0].ident.clone();
|
||||
if self.all_ty_params.contains(&id) {
|
||||
self.relevant_ty_params.insert(id);
|
||||
}
|
||||
}
|
||||
visit::walk_path(self, path);
|
||||
}
|
||||
}
|
||||
|
||||
let all_ty_params: HashSet<_> = generics.ty_params.iter()
|
||||
.map(|ty_param| ty_param.ident.clone())
|
||||
.collect();
|
||||
|
||||
let relevant_tys = item.body.all_fields()
|
||||
.filter(|&field| filter(&field.attrs))
|
||||
.map(|field| &field.ty);
|
||||
|
||||
let mut visitor = FindTyParams {
|
||||
all_ty_params: all_ty_params,
|
||||
relevant_ty_params: HashSet::new(),
|
||||
};
|
||||
for ty in relevant_tys {
|
||||
visit::walk_ty(&mut visitor, ty);
|
||||
}
|
||||
|
||||
aster::from_generics(generics.clone())
|
||||
.with_predicates(
|
||||
generics.ty_params.iter()
|
||||
.map(|ty_param| ty_param.ident.clone())
|
||||
.filter(|id| visitor.relevant_ty_params.contains(id))
|
||||
.map(|id| aster::where_predicate()
|
||||
// the type parameter that is being bounded e.g. T
|
||||
.bound().build(aster::ty().id(id))
|
||||
// the bound e.g. Serialize
|
||||
.bound().trait_(bound.clone()).build()
|
||||
.build()))
|
||||
.build()
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,36 @@
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(used_underscore_binding))]
|
||||
|
||||
// The `quote!` macro requires deep recursion.
|
||||
#![recursion_limit = "192"]
|
||||
|
||||
extern crate syn;
|
||||
#[macro_use]
|
||||
extern crate quote;
|
||||
|
||||
extern crate serde_codegen_internals as internals;
|
||||
|
||||
extern crate proc_macro;
|
||||
use proc_macro::TokenStream;
|
||||
|
||||
mod bound;
|
||||
mod de;
|
||||
mod ser;
|
||||
|
||||
#[proc_macro_derive(Serialize, attributes(serde))]
|
||||
pub fn derive_serialize(input: TokenStream) -> TokenStream {
|
||||
let input = syn::parse_derive_input(&input.to_string()).unwrap();
|
||||
match ser::expand_derive_serialize(&input) {
|
||||
Ok(expanded) => expanded.parse().unwrap(),
|
||||
Err(msg) => panic!(msg),
|
||||
}
|
||||
}
|
||||
|
||||
#[proc_macro_derive(Deserialize, attributes(serde))]
|
||||
pub fn derive_deserialize(input: TokenStream) -> TokenStream {
|
||||
let input = syn::parse_derive_input(&input.to_string()).unwrap();
|
||||
match de::expand_derive_deserialize(&input) {
|
||||
Ok(expanded) => expanded.parse().unwrap(),
|
||||
Err(msg) => panic!(msg),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,811 @@
|
||||
use syn::{self, aster, Ident};
|
||||
use quote::Tokens;
|
||||
|
||||
use bound;
|
||||
use internals::ast::{Body, Field, Item, Style, Variant};
|
||||
use internals::{self, attr};
|
||||
|
||||
pub fn expand_derive_serialize(item: &syn::DeriveInput) -> Result<Tokens, String> {
|
||||
let ctxt = internals::Ctxt::new();
|
||||
let item = Item::from_ast(&ctxt, item);
|
||||
try!(ctxt.check());
|
||||
|
||||
let impl_generics = build_impl_generics(&item);
|
||||
|
||||
let ty = aster::ty().path()
|
||||
.segment(item.ident.clone()).with_generics(impl_generics.clone()).build()
|
||||
.build();
|
||||
|
||||
let body = serialize_body(&item,
|
||||
&impl_generics,
|
||||
ty.clone());
|
||||
|
||||
let where_clause = &impl_generics.where_clause;
|
||||
|
||||
let dummy_const = Ident::new(format!("_IMPL_SERIALIZE_FOR_{}", item.ident));
|
||||
|
||||
Ok(quote! {
|
||||
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
|
||||
const #dummy_const: () = {
|
||||
extern crate serde as _serde;
|
||||
#[automatically_derived]
|
||||
impl #impl_generics _serde::Serialize for #ty #where_clause {
|
||||
fn serialize<__S>(&self, _serializer: __S) -> _serde::export::Result<__S::Ok, __S::Error>
|
||||
where __S: _serde::Serializer
|
||||
{
|
||||
#body
|
||||
}
|
||||
}
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
// All the generics in the input, plus a bound `T: Serialize` for each generic
|
||||
// field type that will be serialized by us.
|
||||
fn build_impl_generics(item: &Item) -> syn::Generics {
|
||||
let generics = bound::without_defaults(item.generics);
|
||||
|
||||
let generics = bound::with_where_predicates_from_fields(
|
||||
item, &generics,
|
||||
|attrs| attrs.ser_bound());
|
||||
|
||||
match item.attrs.ser_bound() {
|
||||
Some(predicates) => {
|
||||
bound::with_where_predicates(&generics, predicates)
|
||||
}
|
||||
None => {
|
||||
bound::with_bound(item, &generics,
|
||||
needs_serialize_bound,
|
||||
&aster::path().ids(&["_serde", "Serialize"]).build())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fields with a `skip_serializing` or `serialize_with` attribute are not
|
||||
// serialized by us so we do not generate a bound. Fields with a `bound`
|
||||
// attribute specify their own bound so we do not generate one. All other fields
|
||||
// may need a `T: Serialize` bound where T is the type of the field.
|
||||
fn needs_serialize_bound(attrs: &attr::Field) -> bool {
|
||||
!attrs.skip_serializing()
|
||||
&& attrs.serialize_with().is_none()
|
||||
&& attrs.ser_bound().is_none()
|
||||
}
|
||||
|
||||
fn serialize_body(
|
||||
item: &Item,
|
||||
impl_generics: &syn::Generics,
|
||||
ty: syn::Ty,
|
||||
) -> Tokens {
|
||||
match item.body {
|
||||
Body::Enum(ref variants) => {
|
||||
serialize_item_enum(
|
||||
&item.ident,
|
||||
impl_generics,
|
||||
ty,
|
||||
variants,
|
||||
&item.attrs)
|
||||
}
|
||||
Body::Struct(Style::Struct, ref fields) => {
|
||||
if fields.iter().any(|field| field.ident.is_none()) {
|
||||
panic!("struct has unnamed fields");
|
||||
}
|
||||
|
||||
serialize_struct(
|
||||
impl_generics,
|
||||
ty,
|
||||
fields,
|
||||
&item.attrs)
|
||||
}
|
||||
Body::Struct(Style::Tuple, ref fields) => {
|
||||
if fields.iter().any(|field| field.ident.is_some()) {
|
||||
panic!("tuple struct has named fields");
|
||||
}
|
||||
|
||||
serialize_tuple_struct(
|
||||
impl_generics,
|
||||
ty,
|
||||
fields,
|
||||
&item.attrs)
|
||||
}
|
||||
Body::Struct(Style::Newtype, ref fields) => {
|
||||
serialize_newtype_struct(
|
||||
impl_generics,
|
||||
ty,
|
||||
&fields[0],
|
||||
&item.attrs)
|
||||
}
|
||||
Body::Struct(Style::Unit, _) => {
|
||||
serialize_unit_struct(
|
||||
&item.attrs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_unit_struct(item_attrs: &attr::Item) -> Tokens {
|
||||
let type_name = item_attrs.name().serialize_name();
|
||||
|
||||
quote! {
|
||||
_serde::Serializer::serialize_unit_struct(_serializer, #type_name)
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_newtype_struct(
|
||||
impl_generics: &syn::Generics,
|
||||
item_ty: syn::Ty,
|
||||
field: &Field,
|
||||
item_attrs: &attr::Item,
|
||||
) -> Tokens {
|
||||
let type_name = item_attrs.name().serialize_name();
|
||||
|
||||
let mut field_expr = quote!(&self.0);
|
||||
if let Some(path) = field.attrs.serialize_with() {
|
||||
field_expr = wrap_serialize_with(
|
||||
&item_ty, impl_generics, field.ty, path, field_expr);
|
||||
}
|
||||
|
||||
quote! {
|
||||
_serde::Serializer::serialize_newtype_struct(_serializer, #type_name, #field_expr)
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_tuple_struct(
|
||||
impl_generics: &syn::Generics,
|
||||
ty: syn::Ty,
|
||||
fields: &[Field],
|
||||
item_attrs: &attr::Item,
|
||||
) -> Tokens {
|
||||
let serialize_stmts = serialize_tuple_struct_visitor(
|
||||
ty.clone(),
|
||||
fields,
|
||||
impl_generics,
|
||||
false,
|
||||
quote!(_serde::ser::SerializeTupleStruct::serialize_field),
|
||||
);
|
||||
|
||||
let type_name = item_attrs.name().serialize_name();
|
||||
let len = serialize_stmts.len();
|
||||
let let_mut = mut_if(len > 0);
|
||||
|
||||
quote! {
|
||||
let #let_mut __serde_state = try!(_serde::Serializer::serialize_tuple_struct(_serializer, #type_name, #len));
|
||||
#(#serialize_stmts)*
|
||||
_serde::ser::SerializeTupleStruct::end(__serde_state)
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_struct(
|
||||
impl_generics: &syn::Generics,
|
||||
ty: syn::Ty,
|
||||
fields: &[Field],
|
||||
item_attrs: &attr::Item,
|
||||
) -> Tokens {
|
||||
let serialize_fields = serialize_struct_visitor(
|
||||
ty.clone(),
|
||||
fields,
|
||||
impl_generics,
|
||||
false,
|
||||
quote!(_serde::ser::SerializeStruct::serialize_field),
|
||||
);
|
||||
|
||||
let type_name = item_attrs.name().serialize_name();
|
||||
|
||||
let mut serialized_fields = fields.iter()
|
||||
.filter(|&field| !field.attrs.skip_serializing())
|
||||
.peekable();
|
||||
|
||||
let let_mut = mut_if(serialized_fields.peek().is_some());
|
||||
|
||||
let len = serialized_fields
|
||||
.map(|field| {
|
||||
let ident = field.ident.clone().expect("struct has unnamed fields");
|
||||
let field_expr = quote!(&self.#ident);
|
||||
|
||||
match field.attrs.skip_serializing_if() {
|
||||
Some(path) => quote!(if #path(#field_expr) { 0 } else { 1 }),
|
||||
None => quote!(1),
|
||||
}
|
||||
})
|
||||
.fold(quote!(0), |sum, expr| quote!(#sum + #expr));
|
||||
|
||||
quote! {
|
||||
let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct(_serializer, #type_name, #len));
|
||||
#(#serialize_fields)*
|
||||
_serde::ser::SerializeStruct::end(__serde_state)
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_item_enum(
|
||||
type_ident: &syn::Ident,
|
||||
impl_generics: &syn::Generics,
|
||||
ty: syn::Ty,
|
||||
variants: &[Variant],
|
||||
item_attrs: &attr::Item,
|
||||
) -> Tokens {
|
||||
let arms: Vec<_> =
|
||||
variants.iter()
|
||||
.enumerate()
|
||||
.map(|(variant_index, variant)| {
|
||||
serialize_variant(
|
||||
type_ident,
|
||||
impl_generics,
|
||||
ty.clone(),
|
||||
variant,
|
||||
variant_index,
|
||||
item_attrs,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
quote! {
|
||||
match *self {
|
||||
#(#arms)*
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_variant(
|
||||
type_ident: &syn::Ident,
|
||||
generics: &syn::Generics,
|
||||
ty: syn::Ty,
|
||||
variant: &Variant,
|
||||
variant_index: usize,
|
||||
item_attrs: &attr::Item,
|
||||
) -> Tokens {
|
||||
let variant_ident = variant.ident.clone();
|
||||
|
||||
if variant.attrs.skip_serializing() {
|
||||
let skipped_msg = format!("the enum variant {}::{} cannot be serialized",
|
||||
type_ident, variant_ident);
|
||||
let skipped_err = quote! {
|
||||
_serde::export::Err(_serde::ser::Error::custom(#skipped_msg))
|
||||
};
|
||||
let fields_pat = match variant.style {
|
||||
Style::Unit => quote!(),
|
||||
Style::Newtype | Style::Tuple => quote!( (..) ),
|
||||
Style::Struct => quote!( {..} ),
|
||||
};
|
||||
quote! {
|
||||
#type_ident::#variant_ident #fields_pat => #skipped_err,
|
||||
}
|
||||
} else { // variant wasn't skipped
|
||||
let case = match variant.style {
|
||||
Style::Unit => {
|
||||
quote! {
|
||||
#type_ident::#variant_ident
|
||||
}
|
||||
}
|
||||
Style::Newtype => {
|
||||
quote! {
|
||||
#type_ident::#variant_ident(ref __simple_value)
|
||||
}
|
||||
}
|
||||
Style::Tuple => {
|
||||
let field_names = (0 .. variant.fields.len())
|
||||
.map(|i| Ident::new(format!("__field{}", i)));
|
||||
quote! {
|
||||
#type_ident::#variant_ident(#(ref #field_names),*)
|
||||
}
|
||||
}
|
||||
Style::Struct => {
|
||||
let fields = variant.fields.iter()
|
||||
.map(|f| f.ident.clone().expect("struct variant has unnamed fields"));
|
||||
quote! {
|
||||
#type_ident::#variant_ident { #(ref #fields),* }
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let body = match *item_attrs.tag() {
|
||||
attr::EnumTag::External => {
|
||||
serialize_externally_tagged_variant(
|
||||
generics,
|
||||
ty,
|
||||
variant,
|
||||
variant_index,
|
||||
item_attrs,
|
||||
)
|
||||
}
|
||||
attr::EnumTag::Internal(ref tag) => {
|
||||
serialize_internally_tagged_variant(
|
||||
type_ident.as_ref(),
|
||||
variant_ident.as_ref(),
|
||||
generics,
|
||||
ty,
|
||||
variant,
|
||||
item_attrs,
|
||||
tag,
|
||||
)
|
||||
}
|
||||
attr::EnumTag::None => {
|
||||
serialize_untagged_variant(
|
||||
generics,
|
||||
ty,
|
||||
variant,
|
||||
item_attrs,
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
quote! {
|
||||
#case => #body
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_externally_tagged_variant(
|
||||
generics: &syn::Generics,
|
||||
ty: syn::Ty,
|
||||
variant: &Variant,
|
||||
variant_index: usize,
|
||||
item_attrs: &attr::Item,
|
||||
) -> Tokens {
|
||||
let type_name = item_attrs.name().serialize_name();
|
||||
let variant_name = variant.attrs.name().serialize_name();
|
||||
|
||||
match variant.style {
|
||||
Style::Unit => {
|
||||
quote! {
|
||||
_serde::Serializer::serialize_unit_variant(
|
||||
_serializer,
|
||||
#type_name,
|
||||
#variant_index,
|
||||
#variant_name,
|
||||
),
|
||||
}
|
||||
}
|
||||
Style::Newtype => {
|
||||
let field = &variant.fields[0];
|
||||
let mut field_expr = quote!(__simple_value);
|
||||
if let Some(path) = field.attrs.serialize_with() {
|
||||
field_expr = wrap_serialize_with(
|
||||
&ty, generics, field.ty, path, field_expr);
|
||||
}
|
||||
|
||||
quote! {
|
||||
_serde::Serializer::serialize_newtype_variant(
|
||||
_serializer,
|
||||
#type_name,
|
||||
#variant_index,
|
||||
#variant_name,
|
||||
#field_expr,
|
||||
),
|
||||
}
|
||||
}
|
||||
Style::Tuple => {
|
||||
let block = serialize_tuple_variant(
|
||||
TupleVariant::ExternallyTagged {
|
||||
type_name: type_name,
|
||||
variant_index: variant_index,
|
||||
variant_name: variant_name,
|
||||
},
|
||||
generics,
|
||||
ty,
|
||||
&variant.fields,
|
||||
);
|
||||
|
||||
quote! {
|
||||
{ #block }
|
||||
}
|
||||
}
|
||||
Style::Struct => {
|
||||
let block = serialize_struct_variant(
|
||||
StructVariant::ExternallyTagged {
|
||||
variant_index: variant_index,
|
||||
variant_name: variant_name,
|
||||
},
|
||||
generics,
|
||||
ty,
|
||||
&variant.fields,
|
||||
item_attrs,
|
||||
);
|
||||
|
||||
quote! {
|
||||
{ #block }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_internally_tagged_variant(
|
||||
type_ident: &str,
|
||||
variant_ident: &str,
|
||||
generics: &syn::Generics,
|
||||
ty: syn::Ty,
|
||||
variant: &Variant,
|
||||
item_attrs: &attr::Item,
|
||||
tag: &str,
|
||||
) -> Tokens {
|
||||
let type_name = item_attrs.name().serialize_name();
|
||||
let variant_name = variant.attrs.name().serialize_name();
|
||||
|
||||
match variant.style {
|
||||
Style::Unit => {
|
||||
quote!({
|
||||
let mut __struct = try!(_serde::Serializer::serialize_struct(
|
||||
_serializer, #type_name, 1));
|
||||
try!(_serde::ser::SerializeStruct::serialize_field(
|
||||
&mut __struct, #tag, #variant_name));
|
||||
_serde::ser::SerializeStruct::end(__struct)
|
||||
})
|
||||
}
|
||||
Style::Newtype => {
|
||||
let field = &variant.fields[0];
|
||||
let mut field_expr = quote!(__simple_value);
|
||||
if let Some(path) = field.attrs.serialize_with() {
|
||||
field_expr = wrap_serialize_with(
|
||||
&ty, generics, field.ty, path, field_expr);
|
||||
}
|
||||
|
||||
quote! {
|
||||
_serde::ser::private::serialize_tagged_newtype(
|
||||
_serializer,
|
||||
#type_ident,
|
||||
#variant_ident,
|
||||
#tag,
|
||||
#variant_name,
|
||||
#field_expr,
|
||||
),
|
||||
}
|
||||
}
|
||||
Style::Struct => {
|
||||
let block = serialize_struct_variant(
|
||||
StructVariant::InternallyTagged {
|
||||
tag: tag,
|
||||
variant_name: variant_name,
|
||||
},
|
||||
generics,
|
||||
ty,
|
||||
&variant.fields,
|
||||
item_attrs,
|
||||
);
|
||||
|
||||
quote! {
|
||||
{ #block }
|
||||
}
|
||||
}
|
||||
Style::Tuple => unreachable!("checked in serde_codegen_internals"),
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_untagged_variant(
|
||||
generics: &syn::Generics,
|
||||
ty: syn::Ty,
|
||||
variant: &Variant,
|
||||
item_attrs: &attr::Item,
|
||||
) -> Tokens {
|
||||
match variant.style {
|
||||
Style::Unit => {
|
||||
quote! {
|
||||
_serde::Serializer::serialize_unit(_serializer),
|
||||
}
|
||||
}
|
||||
Style::Newtype => {
|
||||
let field = &variant.fields[0];
|
||||
let mut field_expr = quote!(__simple_value);
|
||||
if let Some(path) = field.attrs.serialize_with() {
|
||||
field_expr = wrap_serialize_with(
|
||||
&ty, generics, field.ty, path, field_expr);
|
||||
}
|
||||
|
||||
quote! {
|
||||
_serde::Serialize::serialize(#field_expr, _serializer),
|
||||
}
|
||||
}
|
||||
Style::Tuple => {
|
||||
let block = serialize_tuple_variant(
|
||||
TupleVariant::Untagged,
|
||||
generics,
|
||||
ty,
|
||||
&variant.fields,
|
||||
);
|
||||
|
||||
quote! {
|
||||
{ #block }
|
||||
}
|
||||
}
|
||||
Style::Struct => {
|
||||
let block = serialize_struct_variant(
|
||||
StructVariant::Untagged,
|
||||
generics,
|
||||
ty,
|
||||
&variant.fields,
|
||||
item_attrs,
|
||||
);
|
||||
|
||||
quote! {
|
||||
{ #block }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum TupleVariant {
|
||||
ExternallyTagged {
|
||||
type_name: String,
|
||||
variant_index: usize,
|
||||
variant_name: String,
|
||||
},
|
||||
Untagged,
|
||||
}
|
||||
|
||||
fn serialize_tuple_variant(
|
||||
context: TupleVariant,
|
||||
generics: &syn::Generics,
|
||||
structure_ty: syn::Ty,
|
||||
fields: &[Field],
|
||||
) -> Tokens {
|
||||
let method = match context {
|
||||
TupleVariant::ExternallyTagged{..} => {
|
||||
quote!(_serde::ser::SerializeTupleVariant::serialize_field)
|
||||
}
|
||||
TupleVariant::Untagged => {
|
||||
quote!(_serde::ser::SerializeTuple::serialize_element)
|
||||
}
|
||||
};
|
||||
|
||||
let serialize_stmts = serialize_tuple_struct_visitor(
|
||||
structure_ty,
|
||||
fields,
|
||||
generics,
|
||||
true,
|
||||
method,
|
||||
);
|
||||
|
||||
let len = serialize_stmts.len();
|
||||
let let_mut = mut_if(len > 0);
|
||||
|
||||
match context {
|
||||
TupleVariant::ExternallyTagged { type_name, variant_index, variant_name } => {
|
||||
quote! {
|
||||
let #let_mut __serde_state = try!(_serde::Serializer::serialize_tuple_variant(
|
||||
_serializer,
|
||||
#type_name,
|
||||
#variant_index,
|
||||
#variant_name,
|
||||
#len));
|
||||
#(#serialize_stmts)*
|
||||
_serde::ser::SerializeTupleVariant::end(__serde_state)
|
||||
}
|
||||
}
|
||||
TupleVariant::Untagged => {
|
||||
quote! {
|
||||
let #let_mut __serde_state = try!(_serde::Serializer::serialize_tuple(
|
||||
_serializer,
|
||||
#len));
|
||||
#(#serialize_stmts)*
|
||||
_serde::ser::SerializeTuple::end(__serde_state)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum StructVariant<'a> {
|
||||
ExternallyTagged {
|
||||
variant_index: usize,
|
||||
variant_name: String,
|
||||
},
|
||||
InternallyTagged {
|
||||
tag: &'a str,
|
||||
variant_name: String,
|
||||
},
|
||||
Untagged,
|
||||
}
|
||||
|
||||
fn serialize_struct_variant<'a>(
|
||||
context: StructVariant<'a>,
|
||||
generics: &syn::Generics,
|
||||
ty: syn::Ty,
|
||||
fields: &[Field],
|
||||
item_attrs: &attr::Item,
|
||||
) -> Tokens {
|
||||
let method = match context {
|
||||
StructVariant::ExternallyTagged{..} => {
|
||||
quote!(_serde::ser::SerializeStructVariant::serialize_field)
|
||||
}
|
||||
StructVariant::InternallyTagged{..} | StructVariant::Untagged => {
|
||||
quote!(_serde::ser::SerializeStruct::serialize_field)
|
||||
}
|
||||
};
|
||||
|
||||
let serialize_fields = serialize_struct_visitor(
|
||||
ty.clone(),
|
||||
fields,
|
||||
generics,
|
||||
true,
|
||||
method,
|
||||
);
|
||||
|
||||
let item_name = item_attrs.name().serialize_name();
|
||||
|
||||
let mut serialized_fields = fields.iter()
|
||||
.filter(|&field| !field.attrs.skip_serializing())
|
||||
.peekable();
|
||||
|
||||
let let_mut = mut_if(serialized_fields.peek().is_some());
|
||||
|
||||
let len = serialized_fields
|
||||
.map(|field| {
|
||||
let ident = field.ident.clone().expect("struct has unnamed fields");
|
||||
|
||||
match field.attrs.skip_serializing_if() {
|
||||
Some(path) => quote!(if #path(#ident) { 0 } else { 1 }),
|
||||
None => quote!(1),
|
||||
}
|
||||
})
|
||||
.fold(quote!(0), |sum, expr| quote!(#sum + #expr));
|
||||
|
||||
match context {
|
||||
StructVariant::ExternallyTagged { variant_index, variant_name } => {
|
||||
quote! {
|
||||
let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct_variant(
|
||||
_serializer,
|
||||
#item_name,
|
||||
#variant_index,
|
||||
#variant_name,
|
||||
#len,
|
||||
));
|
||||
#(#serialize_fields)*
|
||||
_serde::ser::SerializeStructVariant::end(__serde_state)
|
||||
}
|
||||
}
|
||||
StructVariant::InternallyTagged { tag, variant_name } => {
|
||||
quote! {
|
||||
let mut __serde_state = try!(_serde::Serializer::serialize_struct(
|
||||
_serializer,
|
||||
#item_name,
|
||||
#len + 1,
|
||||
));
|
||||
try!(_serde::ser::SerializeStruct::serialize_field(
|
||||
&mut __serde_state,
|
||||
#tag,
|
||||
#variant_name,
|
||||
));
|
||||
#(#serialize_fields)*
|
||||
_serde::ser::SerializeStruct::end(__serde_state)
|
||||
}
|
||||
}
|
||||
StructVariant::Untagged => {
|
||||
quote! {
|
||||
let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct(
|
||||
_serializer,
|
||||
#item_name,
|
||||
#len,
|
||||
));
|
||||
#(#serialize_fields)*
|
||||
_serde::ser::SerializeStruct::end(__serde_state)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_tuple_struct_visitor(
|
||||
structure_ty: syn::Ty,
|
||||
fields: &[Field],
|
||||
generics: &syn::Generics,
|
||||
is_enum: bool,
|
||||
func: Tokens,
|
||||
) -> Vec<Tokens> {
|
||||
fields.iter()
|
||||
.enumerate()
|
||||
.map(|(i, field)| {
|
||||
let mut field_expr = if is_enum {
|
||||
let id = Ident::new(format!("__field{}", i));
|
||||
quote!(#id)
|
||||
} else {
|
||||
let i = Ident::new(i);
|
||||
quote!(&self.#i)
|
||||
};
|
||||
|
||||
let skip = field.attrs.skip_serializing_if()
|
||||
.map(|path| quote!(#path(#field_expr)));
|
||||
|
||||
if let Some(path) = field.attrs.serialize_with() {
|
||||
field_expr = wrap_serialize_with(
|
||||
&structure_ty, generics, field.ty, path, field_expr);
|
||||
}
|
||||
|
||||
let ser = quote! {
|
||||
try!(#func(&mut __serde_state, #field_expr));
|
||||
};
|
||||
|
||||
match skip {
|
||||
None => ser,
|
||||
Some(skip) => quote!(if !#skip { #ser }),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn serialize_struct_visitor(
|
||||
structure_ty: syn::Ty,
|
||||
fields: &[Field],
|
||||
generics: &syn::Generics,
|
||||
is_enum: bool,
|
||||
func: Tokens,
|
||||
) -> Vec<Tokens> {
|
||||
fields.iter()
|
||||
.filter(|&field| !field.attrs.skip_serializing())
|
||||
.map(|field| {
|
||||
let ident = field.ident.clone().expect("struct has unnamed field");
|
||||
let mut field_expr = if is_enum {
|
||||
quote!(#ident)
|
||||
} else {
|
||||
quote!(&self.#ident)
|
||||
};
|
||||
|
||||
let key_expr = field.attrs.name().serialize_name();
|
||||
|
||||
let skip = field.attrs.skip_serializing_if()
|
||||
.map(|path| quote!(#path(#field_expr)));
|
||||
|
||||
if let Some(path) = field.attrs.serialize_with() {
|
||||
field_expr = wrap_serialize_with(
|
||||
&structure_ty, generics, field.ty, path, field_expr)
|
||||
}
|
||||
|
||||
let ser = quote! {
|
||||
try!(#func(&mut __serde_state, #key_expr, #field_expr));
|
||||
};
|
||||
|
||||
match skip {
|
||||
None => ser,
|
||||
Some(skip) => quote!(if !#skip { #ser }),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn wrap_serialize_with(
|
||||
item_ty: &syn::Ty,
|
||||
generics: &syn::Generics,
|
||||
field_ty: &syn::Ty,
|
||||
path: &syn::Path,
|
||||
value: Tokens,
|
||||
) -> Tokens {
|
||||
let where_clause = &generics.where_clause;
|
||||
|
||||
let wrapper_generics = aster::from_generics(generics.clone())
|
||||
.add_lifetime_bound("'__a")
|
||||
.lifetime_name("'__a")
|
||||
.build();
|
||||
|
||||
let wrapper_ty = aster::path()
|
||||
.segment("__SerializeWith")
|
||||
.with_generics(wrapper_generics.clone())
|
||||
.build()
|
||||
.build();
|
||||
|
||||
quote!({
|
||||
struct __SerializeWith #wrapper_generics #where_clause {
|
||||
value: &'__a #field_ty,
|
||||
phantom: _serde::export::PhantomData<#item_ty>,
|
||||
}
|
||||
|
||||
impl #wrapper_generics _serde::Serialize for #wrapper_ty #where_clause {
|
||||
fn serialize<__S>(&self, __s: __S) -> _serde::export::Result<__S::Ok, __S::Error>
|
||||
where __S: _serde::Serializer
|
||||
{
|
||||
#path(self.value, __s)
|
||||
}
|
||||
}
|
||||
|
||||
&__SerializeWith {
|
||||
value: #value,
|
||||
phantom: _serde::export::PhantomData::<#item_ty>,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Serialization of an empty struct results in code like:
|
||||
//
|
||||
// let mut __serde_state = try!(serializer.serialize_struct("S", 0));
|
||||
// _serde::ser::SerializeStruct::end(__serde_state)
|
||||
//
|
||||
// where we want to omit the `mut` to avoid a warning.
|
||||
fn mut_if(is_mut: bool) -> Option<Tokens> {
|
||||
if is_mut {
|
||||
Some(quote!(mut))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
/target
|
||||
/Cargo.lock
|
||||
@@ -1,16 +0,0 @@
|
||||
[package]
|
||||
name = "serde_macros"
|
||||
version = "0.2.0"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "A quasi-quoting macro system"
|
||||
repository = "https://github.com/erickt/rust-quasi"
|
||||
|
||||
[lib]
|
||||
name = "serde_macros"
|
||||
plugin = true
|
||||
|
||||
[dependencies]
|
||||
quasi = "0.1.3"
|
||||
quasi_macros = "0.1.3"
|
||||
aster = "0.1.3"
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "serde_test"
|
||||
version = "0.9.7"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "Token De/Serializer for testing De/Serialize implementations"
|
||||
homepage = "https://serde.rs"
|
||||
repository = "https://github.com/serde-rs/serde"
|
||||
documentation = "https://docs.serde.rs/serde_test/"
|
||||
readme = "../README.md"
|
||||
keywords = ["serde", "serialization"]
|
||||
include = ["Cargo.toml", "src/**/*.rs"]
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "0.9", path = "../serde" }
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "serde-rs/serde" }
|
||||
@@ -0,0 +1,54 @@
|
||||
use serde::{Serialize, Deserialize};
|
||||
|
||||
use de::Deserializer;
|
||||
use error::Error;
|
||||
use ser::Serializer;
|
||||
use token::Token;
|
||||
|
||||
use std::fmt::Debug;
|
||||
|
||||
pub fn assert_tokens<T>(value: &T, tokens: &[Token<'static>])
|
||||
where T: Serialize + Deserialize + PartialEq + Debug,
|
||||
{
|
||||
assert_ser_tokens(value, tokens);
|
||||
assert_de_tokens(value, tokens);
|
||||
}
|
||||
|
||||
pub fn assert_ser_tokens<T>(value: &T, tokens: &[Token])
|
||||
where T: Serialize,
|
||||
{
|
||||
let mut ser = Serializer::new(tokens.iter());
|
||||
assert_eq!(Serialize::serialize(value, &mut ser), Ok(()));
|
||||
assert_eq!(ser.next_token(), None);
|
||||
}
|
||||
|
||||
/// Expect an error serializing `T`.
|
||||
pub fn assert_ser_tokens_error<T>(value: &T, tokens: &[Token], error: Error)
|
||||
where T: Serialize + PartialEq + Debug,
|
||||
{
|
||||
let mut ser = Serializer::new(tokens.iter());
|
||||
let v: Result<(), Error> = Serialize::serialize(value, &mut ser);
|
||||
assert_eq!(v.as_ref(), Err(&error));
|
||||
assert_eq!(ser.next_token(), None);
|
||||
}
|
||||
|
||||
pub fn assert_de_tokens<T>(value: &T, tokens: &[Token<'static>])
|
||||
where T: Deserialize + PartialEq + Debug,
|
||||
{
|
||||
let mut de = Deserializer::new(tokens.to_vec().into_iter());
|
||||
let v: Result<T, Error> = Deserialize::deserialize(&mut de);
|
||||
assert_eq!(v.as_ref(), Ok(value));
|
||||
assert_eq!(de.next_token(), None);
|
||||
}
|
||||
|
||||
/// Expect an error deserializing tokens into a `T`.
|
||||
pub fn assert_de_tokens_error<T>(tokens: &[Token<'static>], error: Error)
|
||||
where T: Deserialize + PartialEq + Debug,
|
||||
{
|
||||
let mut de = Deserializer::new(tokens.to_vec().into_iter());
|
||||
let v: Result<T, Error> = Deserialize::deserialize(&mut de);
|
||||
assert_eq!(v, Err(error));
|
||||
// There may be one token left if a peek caused the error
|
||||
de.next_token();
|
||||
assert_eq!(de.next_token(), None);
|
||||
}
|
||||
@@ -0,0 +1,539 @@
|
||||
use std::iter;
|
||||
|
||||
use serde::de::{
|
||||
self,
|
||||
Deserialize,
|
||||
DeserializeSeed,
|
||||
EnumVisitor,
|
||||
MapVisitor,
|
||||
SeqVisitor,
|
||||
VariantVisitor,
|
||||
Visitor,
|
||||
};
|
||||
use serde::de::value::ValueDeserializer;
|
||||
|
||||
use error::Error;
|
||||
use token::Token;
|
||||
|
||||
pub struct Deserializer<I>
|
||||
where I: Iterator<Item=Token<'static>>,
|
||||
{
|
||||
tokens: iter::Peekable<I>,
|
||||
}
|
||||
|
||||
impl<I> Deserializer<I>
|
||||
where I: Iterator<Item=Token<'static>>,
|
||||
{
|
||||
pub fn new(tokens: I) -> Deserializer<I> {
|
||||
Deserializer {
|
||||
tokens: tokens.peekable(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn next_token(&mut self) -> Option<Token<'static>> {
|
||||
self.tokens.next()
|
||||
}
|
||||
|
||||
pub fn expect_token(&mut self, expected: Token) -> Result<(), Error> {
|
||||
match self.tokens.next() {
|
||||
Some(token) => {
|
||||
if expected == token {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnexpectedToken(token))
|
||||
}
|
||||
}
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_seq<V>(&mut self, len: Option<usize>, sep: Token<'static>, end: Token<'static>, visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
let value = try!(visitor.visit_seq(DeserializerSeqVisitor {
|
||||
de: self,
|
||||
len: len,
|
||||
sep: sep,
|
||||
end: end.clone(),
|
||||
}));
|
||||
try!(self.expect_token(end));
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn visit_map<V>(&mut self, len: Option<usize>, sep: Token<'static>, end: Token<'static>, visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
let value = try!(visitor.visit_map(DeserializerMapVisitor {
|
||||
de: self,
|
||||
len: len,
|
||||
sep: sep,
|
||||
end: end.clone(),
|
||||
}));
|
||||
try!(self.expect_token(end));
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
||||
where I: Iterator<Item=Token<'static>>,
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
forward_to_deserialize! {
|
||||
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit
|
||||
seq bytes byte_buf map struct_field ignored_any
|
||||
}
|
||||
|
||||
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
match self.tokens.next() {
|
||||
Some(Token::Bool(v)) => visitor.visit_bool(v),
|
||||
Some(Token::I8(v)) => visitor.visit_i8(v),
|
||||
Some(Token::I16(v)) => visitor.visit_i16(v),
|
||||
Some(Token::I32(v)) => visitor.visit_i32(v),
|
||||
Some(Token::I64(v)) => visitor.visit_i64(v),
|
||||
Some(Token::U8(v)) => visitor.visit_u8(v),
|
||||
Some(Token::U16(v)) => visitor.visit_u16(v),
|
||||
Some(Token::U32(v)) => visitor.visit_u32(v),
|
||||
Some(Token::U64(v)) => visitor.visit_u64(v),
|
||||
Some(Token::F32(v)) => visitor.visit_f32(v),
|
||||
Some(Token::F64(v)) => visitor.visit_f64(v),
|
||||
Some(Token::Char(v)) => visitor.visit_char(v),
|
||||
Some(Token::Str(v)) => visitor.visit_str(v),
|
||||
Some(Token::String(v)) => visitor.visit_string(v),
|
||||
Some(Token::Bytes(v)) => visitor.visit_bytes(v),
|
||||
Some(Token::ByteBuf(v)) => visitor.visit_byte_buf(v),
|
||||
Some(Token::Option(false)) => visitor.visit_none(),
|
||||
Some(Token::Option(true)) => visitor.visit_some(self),
|
||||
Some(Token::Unit) => visitor.visit_unit(),
|
||||
Some(Token::UnitStruct(_name)) => visitor.visit_unit(),
|
||||
Some(Token::SeqStart(len)) => {
|
||||
self.visit_seq(len, Token::SeqSep, Token::SeqEnd, visitor)
|
||||
}
|
||||
Some(Token::SeqArrayStart(len)) => {
|
||||
self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||
}
|
||||
Some(Token::TupleStart(len)) => {
|
||||
self.visit_seq(Some(len), Token::TupleSep, Token::TupleEnd, visitor)
|
||||
}
|
||||
Some(Token::TupleStructStart(_, len)) => {
|
||||
self.visit_seq(Some(len), Token::TupleStructSep, Token::TupleStructEnd, visitor)
|
||||
}
|
||||
Some(Token::MapStart(len)) => {
|
||||
self.visit_map(len, Token::MapSep, Token::MapEnd, visitor)
|
||||
}
|
||||
Some(Token::StructStart(_, len)) => {
|
||||
self.visit_map(Some(len), Token::StructSep, Token::StructEnd, visitor)
|
||||
}
|
||||
Some(token) => Err(Error::UnexpectedToken(token)),
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
/// Hook into `Option` deserializing so we can treat `Unit` as a
|
||||
/// `None`, or a regular value as `Some(value)`.
|
||||
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
match self.tokens.peek() {
|
||||
Some(&Token::Unit) | Some(&Token::Option(false)) => {
|
||||
self.tokens.next();
|
||||
visitor.visit_none()
|
||||
}
|
||||
Some(&Token::Option(true)) => {
|
||||
self.tokens.next();
|
||||
visitor.visit_some(self)
|
||||
}
|
||||
Some(_) => visitor.visit_some(self),
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_enum<V>(self,
|
||||
name: &str,
|
||||
_variants: &'static [&'static str],
|
||||
visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
match self.tokens.peek() {
|
||||
Some(&Token::EnumStart(n)) if name == n => {
|
||||
self.tokens.next();
|
||||
|
||||
visitor.visit_enum(DeserializerEnumVisitor {
|
||||
de: self,
|
||||
})
|
||||
}
|
||||
Some(&Token::EnumUnit(n, _))
|
||||
| Some(&Token::EnumNewType(n, _))
|
||||
| Some(&Token::EnumSeqStart(n, _, _))
|
||||
| Some(&Token::EnumMapStart(n, _, _)) if name == n => {
|
||||
visitor.visit_enum(DeserializerEnumVisitor {
|
||||
de: self,
|
||||
})
|
||||
}
|
||||
Some(_) => {
|
||||
let token = self.tokens.next().unwrap();
|
||||
Err(Error::UnexpectedToken(token))
|
||||
}
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_unit_struct<V>(self, name: &str, visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
match self.tokens.peek() {
|
||||
Some(&Token::UnitStruct(n)) => {
|
||||
self.tokens.next();
|
||||
if name == n {
|
||||
visitor.visit_unit()
|
||||
} else {
|
||||
Err(Error::InvalidName(n))
|
||||
}
|
||||
}
|
||||
Some(_) => self.deserialize(visitor),
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_newtype_struct<V>(self,
|
||||
name: &str,
|
||||
visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
match self.tokens.peek() {
|
||||
Some(&Token::StructNewType(n)) => {
|
||||
self.tokens.next();
|
||||
if name == n {
|
||||
visitor.visit_newtype_struct(self)
|
||||
} else {
|
||||
Err(Error::InvalidName(n))
|
||||
}
|
||||
}
|
||||
Some(_) => self.deserialize(visitor),
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_seq_fixed_size<V>(self,
|
||||
len: usize,
|
||||
visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
match self.tokens.peek() {
|
||||
Some(&Token::SeqArrayStart(_)) => {
|
||||
self.tokens.next();
|
||||
self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||
}
|
||||
Some(_) => self.deserialize(visitor),
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_tuple<V>(self,
|
||||
len: usize,
|
||||
visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
match self.tokens.peek() {
|
||||
Some(&Token::Unit) | Some(&Token::UnitStruct(_)) => {
|
||||
self.tokens.next();
|
||||
visitor.visit_unit()
|
||||
}
|
||||
Some(&Token::SeqStart(_)) => {
|
||||
self.tokens.next();
|
||||
self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||
}
|
||||
Some(&Token::SeqArrayStart(_)) => {
|
||||
self.tokens.next();
|
||||
self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||
}
|
||||
Some(&Token::TupleStart(_)) => {
|
||||
self.tokens.next();
|
||||
self.visit_seq(Some(len), Token::TupleSep, Token::TupleEnd, visitor)
|
||||
}
|
||||
Some(&Token::TupleStructStart(_, _)) => {
|
||||
self.tokens.next();
|
||||
self.visit_seq(Some(len), Token::TupleStructSep, Token::TupleStructEnd, visitor)
|
||||
}
|
||||
Some(_) => self.deserialize(visitor),
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_tuple_struct<V>(self,
|
||||
name: &str,
|
||||
len: usize,
|
||||
visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
match self.tokens.peek() {
|
||||
Some(&Token::Unit) => {
|
||||
self.tokens.next();
|
||||
visitor.visit_unit()
|
||||
}
|
||||
Some(&Token::UnitStruct(n)) => {
|
||||
self.tokens.next();
|
||||
if name == n {
|
||||
visitor.visit_unit()
|
||||
} else {
|
||||
Err(Error::InvalidName(n))
|
||||
}
|
||||
}
|
||||
Some(&Token::SeqStart(_)) => {
|
||||
self.tokens.next();
|
||||
self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||
}
|
||||
Some(&Token::SeqArrayStart(_)) => {
|
||||
self.tokens.next();
|
||||
self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||
}
|
||||
Some(&Token::TupleStart(_)) => {
|
||||
self.tokens.next();
|
||||
self.visit_seq(Some(len), Token::TupleSep, Token::TupleEnd, visitor)
|
||||
}
|
||||
Some(&Token::TupleStructStart(n, _)) => {
|
||||
self.tokens.next();
|
||||
if name == n {
|
||||
self.visit_seq(Some(len), Token::TupleStructSep, Token::TupleStructEnd, visitor)
|
||||
} else {
|
||||
Err(Error::InvalidName(n))
|
||||
}
|
||||
}
|
||||
Some(_) => self.deserialize(visitor),
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_struct<V>(self,
|
||||
name: &str,
|
||||
fields: &'static [&'static str],
|
||||
visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
match self.tokens.peek() {
|
||||
Some(&Token::StructStart(n, _)) => {
|
||||
self.tokens.next();
|
||||
if name == n {
|
||||
self.visit_map(Some(fields.len()), Token::StructSep, Token::StructEnd, visitor)
|
||||
} else {
|
||||
Err(Error::InvalidName(n))
|
||||
}
|
||||
}
|
||||
Some(&Token::MapStart(_)) => {
|
||||
self.tokens.next();
|
||||
self.visit_map(Some(fields.len()), Token::MapSep, Token::MapEnd, visitor)
|
||||
}
|
||||
Some(_) => self.deserialize(visitor),
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct DeserializerSeqVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
||||
de: &'a mut Deserializer<I>,
|
||||
len: Option<usize>,
|
||||
sep: Token<'static>,
|
||||
end: Token<'static>,
|
||||
}
|
||||
|
||||
impl<'a, I> SeqVisitor for DeserializerSeqVisitor<'a, I>
|
||||
where I: Iterator<Item=Token<'static>>,
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
|
||||
where T: DeserializeSeed,
|
||||
{
|
||||
if self.de.tokens.peek() == Some(&self.end) {
|
||||
return Ok(None);
|
||||
}
|
||||
match self.de.tokens.next() {
|
||||
Some(ref token) if *token == self.sep => {
|
||||
self.len = self.len.map(|len| len.saturating_sub(1));
|
||||
seed.deserialize(&mut *self.de).map(Some)
|
||||
}
|
||||
Some(other) => Err(Error::UnexpectedToken(other)),
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = self.len.unwrap_or(0);
|
||||
(len, self.len)
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct DeserializerMapVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
||||
de: &'a mut Deserializer<I>,
|
||||
len: Option<usize>,
|
||||
sep: Token<'static>,
|
||||
end: Token<'static>,
|
||||
}
|
||||
|
||||
impl<'a, I> MapVisitor for DeserializerMapVisitor<'a, I>
|
||||
where I: Iterator<Item=Token<'static>>,
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
|
||||
where K: DeserializeSeed,
|
||||
{
|
||||
if self.de.tokens.peek() == Some(&self.end) {
|
||||
return Ok(None);
|
||||
}
|
||||
match self.de.tokens.next() {
|
||||
Some(ref token) if *token == self.sep => {
|
||||
self.len = self.len.map(|len| len.saturating_sub(1));
|
||||
seed.deserialize(&mut *self.de).map(Some)
|
||||
}
|
||||
Some(other) => Err(Error::UnexpectedToken(other)),
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
|
||||
where V: DeserializeSeed,
|
||||
{
|
||||
seed.deserialize(&mut *self.de)
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = self.len.unwrap_or(0);
|
||||
(len, self.len)
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct DeserializerEnumVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
||||
de: &'a mut Deserializer<I>,
|
||||
}
|
||||
|
||||
impl<'a, I> EnumVisitor for DeserializerEnumVisitor<'a, I>
|
||||
where I: Iterator<Item=Token<'static>>,
|
||||
{
|
||||
type Error = Error;
|
||||
type Variant = Self;
|
||||
|
||||
fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self), Error>
|
||||
where V: DeserializeSeed,
|
||||
{
|
||||
match self.de.tokens.peek() {
|
||||
Some(&Token::EnumUnit(_, v))
|
||||
| Some(&Token::EnumNewType(_, v))
|
||||
| Some(&Token::EnumSeqStart(_, v, _))
|
||||
| Some(&Token::EnumMapStart(_, v, _)) => {
|
||||
let de = v.into_deserializer();
|
||||
let value = try!(seed.deserialize(de));
|
||||
Ok((value, self))
|
||||
}
|
||||
Some(_) => {
|
||||
let value = try!(seed.deserialize(&mut *self.de));
|
||||
Ok((value, self))
|
||||
}
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
|
||||
where I: Iterator<Item=Token<'static>>
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
fn visit_unit(self) -> Result<(), Error> {
|
||||
match self.de.tokens.peek() {
|
||||
Some(&Token::EnumUnit(_, _)) => {
|
||||
self.de.tokens.next();
|
||||
Ok(())
|
||||
}
|
||||
Some(_) => {
|
||||
Deserialize::deserialize(self.de)
|
||||
}
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
|
||||
where T: DeserializeSeed,
|
||||
{
|
||||
match self.de.tokens.peek() {
|
||||
Some(&Token::EnumNewType(_, _)) => {
|
||||
self.de.tokens.next();
|
||||
seed.deserialize(self.de)
|
||||
}
|
||||
Some(_) => {
|
||||
seed.deserialize(self.de)
|
||||
}
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_tuple<V>(self,
|
||||
len: usize,
|
||||
visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
match self.de.tokens.peek() {
|
||||
Some(&Token::EnumSeqStart(_, _, enum_len)) => {
|
||||
let token = self.de.tokens.next().unwrap();
|
||||
|
||||
if len == enum_len {
|
||||
self.de.visit_seq(Some(len), Token::EnumSeqSep, Token::EnumSeqEnd, visitor)
|
||||
} else {
|
||||
Err(Error::UnexpectedToken(token))
|
||||
}
|
||||
}
|
||||
Some(&Token::SeqStart(Some(enum_len))) => {
|
||||
let token = self.de.tokens.next().unwrap();
|
||||
|
||||
if len == enum_len {
|
||||
self.de.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||
} else {
|
||||
Err(Error::UnexpectedToken(token))
|
||||
}
|
||||
}
|
||||
Some(_) => {
|
||||
de::Deserializer::deserialize(self.de, visitor)
|
||||
}
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_struct<V>(self,
|
||||
fields: &'static [&'static str],
|
||||
visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
match self.de.tokens.peek() {
|
||||
Some(&Token::EnumMapStart(_, _, enum_len)) => {
|
||||
let token = self.de.tokens.next().unwrap();
|
||||
|
||||
if fields.len() == enum_len {
|
||||
self.de.visit_map(Some(fields.len()), Token::EnumMapSep, Token::EnumMapEnd, visitor)
|
||||
} else {
|
||||
Err(Error::UnexpectedToken(token))
|
||||
}
|
||||
}
|
||||
Some(&Token::MapStart(Some(enum_len))) => {
|
||||
let token = self.de.tokens.next().unwrap();
|
||||
|
||||
if fields.len() == enum_len {
|
||||
self.de.visit_map(Some(fields.len()), Token::MapSep, Token::MapEnd, visitor)
|
||||
} else {
|
||||
Err(Error::UnexpectedToken(token))
|
||||
}
|
||||
}
|
||||
Some(_) => {
|
||||
de::Deserializer::deserialize(self.de, visitor)
|
||||
}
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
use std::error;
|
||||
use std::fmt::{self, Display};
|
||||
|
||||
use serde::{ser, de};
|
||||
|
||||
use token::Token;
|
||||
|
||||
#[derive(Clone, PartialEq, Debug)]
|
||||
pub enum Error {
|
||||
Message(String),
|
||||
InvalidName(&'static str),
|
||||
UnexpectedToken(Token<'static>),
|
||||
EndOfTokens,
|
||||
}
|
||||
|
||||
impl ser::Error for Error {
|
||||
fn custom<T: Display>(msg: T) -> Error {
|
||||
Error::Message(msg.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl de::Error for Error {
|
||||
fn custom<T: Display>(msg: T) -> Error {
|
||||
Error::Message(msg.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
Error::Message(ref msg) => formatter.write_str(msg),
|
||||
Error::InvalidName(name) => write!(formatter, "invalid name `{}`", name),
|
||||
Error::UnexpectedToken(_) => formatter.write_str("unexpected token"),
|
||||
Error::EndOfTokens => formatter.write_str("end of tokens"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl error::Error for Error {
|
||||
fn description(&self) -> &str {
|
||||
match *self {
|
||||
Error::Message(ref msg) => msg,
|
||||
Error::InvalidName(_) => "invalid name",
|
||||
Error::UnexpectedToken(_) => "unexpected token",
|
||||
Error::EndOfTokens => "end of tokens",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#[macro_use]
|
||||
extern crate serde;
|
||||
|
||||
mod assert;
|
||||
pub use assert::{
|
||||
assert_tokens,
|
||||
assert_ser_tokens,
|
||||
assert_ser_tokens_error,
|
||||
assert_de_tokens,
|
||||
assert_de_tokens_error,
|
||||
};
|
||||
|
||||
mod ser;
|
||||
pub use ser::Serializer;
|
||||
|
||||
mod de;
|
||||
pub use de::Deserializer;
|
||||
|
||||
mod token;
|
||||
pub use token::Token;
|
||||
|
||||
mod error;
|
||||
pub use error::Error;
|
||||
@@ -0,0 +1,346 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use serde::{ser, Serialize};
|
||||
|
||||
use error::Error;
|
||||
use token::Token;
|
||||
|
||||
pub struct Serializer<'a, I>
|
||||
where I: Iterator<Item=&'a Token<'a>>,
|
||||
{
|
||||
tokens: I,
|
||||
phantom: PhantomData<&'a Token<'a>>,
|
||||
}
|
||||
|
||||
impl<'a, I> Serializer<'a, I>
|
||||
where I: Iterator<Item=&'a Token<'a>>,
|
||||
{
|
||||
pub fn new(tokens: I) -> Serializer<'a, I> {
|
||||
Serializer {
|
||||
tokens: tokens,
|
||||
phantom: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn next_token(&mut self) -> Option<&'a Token<'a>> {
|
||||
self.tokens.next()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
|
||||
where I: Iterator<Item=&'a Token<'a>>,
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
type SerializeSeq = Self;
|
||||
type SerializeTuple = Self;
|
||||
type SerializeTupleStruct = Self;
|
||||
type SerializeTupleVariant = Self;
|
||||
type SerializeMap = Self;
|
||||
type SerializeStruct = Self;
|
||||
type SerializeStructVariant = Self;
|
||||
|
||||
fn serialize_bool(self, v: bool) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::Bool(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_i8(self, v: i8) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::I8(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_i16(self, v: i16) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::I16(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_i32(self, v: i32) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::I32(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_i64(self, v: i64) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::I64(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_u8(self, v: u8) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::U8(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_u16(self, v: u16) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::U16(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_u32(self, v: u32) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::U32(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_u64(self, v: u64) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::U64(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_f32(self, v: f32) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::F32(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_f64(self, v: f64) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::F64(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_char(self, v: char) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::Char(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_str(self, v: &str) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::Str(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_bytes(self, value: &[u8]) -> Result<(), Self::Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::Bytes(value)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_unit(self) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::Unit));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_unit_struct(self, name: &str) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::UnitStruct(name)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_unit_variant(self,
|
||||
name: &str,
|
||||
_variant_index: usize,
|
||||
variant: &str) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::EnumUnit(name, variant)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_newtype_struct<T: ?Sized>(self,
|
||||
name: &'static str,
|
||||
value: &T) -> Result<(), Error>
|
||||
where T: Serialize,
|
||||
{
|
||||
assert_eq!(self.tokens.next(), Some(&Token::StructNewType(name)));
|
||||
value.serialize(self)
|
||||
}
|
||||
|
||||
fn serialize_newtype_variant<T: ?Sized>(self,
|
||||
name: &str,
|
||||
_variant_index: usize,
|
||||
variant: &str,
|
||||
value: &T) -> Result<(), Error>
|
||||
where T: Serialize,
|
||||
{
|
||||
assert_eq!(self.tokens.next(), Some(&Token::EnumNewType(name, variant)));
|
||||
value.serialize(self)
|
||||
}
|
||||
|
||||
fn serialize_none(self) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::Option(false)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_some<T: ?Sized>(self, value: &T) -> Result<(), Error>
|
||||
where T: Serialize,
|
||||
{
|
||||
assert_eq!(self.tokens.next(), Some(&Token::Option(true)));
|
||||
value.serialize(self)
|
||||
}
|
||||
|
||||
fn serialize_seq(self, len: Option<usize>) -> Result<Self, Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::SeqStart(len)));
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
fn serialize_seq_fixed_size(self, len: usize) -> Result<Self, Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::SeqArrayStart(len)));
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
fn serialize_tuple(self, len: usize) -> Result<Self, Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::TupleStart(len)));
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
fn serialize_tuple_struct(self, name: &'static str, len: usize) -> Result<Self, Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::TupleStructStart(name, len)));
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
fn serialize_tuple_variant(self,
|
||||
name: &str,
|
||||
_variant_index: usize,
|
||||
variant: &str,
|
||||
len: usize) -> Result<Self, Error>
|
||||
{
|
||||
assert_eq!(self.tokens.next(), Some(&Token::EnumSeqStart(name, variant, len)));
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
fn serialize_map(self, len: Option<usize>) -> Result<Self, Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::MapStart(len)));
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
fn serialize_struct(self, name: &str, len: usize) -> Result<Self, Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::StructStart(name, len)));
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
fn serialize_struct_variant(self,
|
||||
name: &str,
|
||||
_variant_index: usize,
|
||||
variant: &str,
|
||||
len: usize) -> Result<Self, Error>
|
||||
{
|
||||
assert_eq!(self.tokens.next(), Some(&Token::EnumMapStart(name, variant, len)));
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s, 'a, I> ser::SerializeSeq for &'s mut Serializer<'a, I>
|
||||
where I: Iterator<Item=&'a Token<'a>>,
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
|
||||
where T: Serialize
|
||||
{
|
||||
assert_eq!(self.tokens.next(), Some(&Token::SeqSep));
|
||||
value.serialize(&mut **self)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::SeqEnd));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s, 'a, I> ser::SerializeTuple for &'s mut Serializer<'a, I>
|
||||
where I: Iterator<Item=&'a Token<'a>>,
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
|
||||
where T: Serialize
|
||||
{
|
||||
assert_eq!(self.tokens.next(), Some(&Token::TupleSep));
|
||||
value.serialize(&mut **self)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::TupleEnd));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s, 'a, I> ser::SerializeTupleStruct for &'s mut Serializer<'a, I>
|
||||
where I: Iterator<Item=&'a Token<'a>>,
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
|
||||
where T: Serialize
|
||||
{
|
||||
assert_eq!(self.tokens.next(), Some(&Token::TupleStructSep));
|
||||
value.serialize(&mut **self)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::TupleStructEnd));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s, 'a, I> ser::SerializeTupleVariant for &'s mut Serializer<'a, I>
|
||||
where I: Iterator<Item=&'a Token<'a>>,
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
|
||||
where T: Serialize
|
||||
{
|
||||
assert_eq!(self.tokens.next(), Some(&Token::EnumSeqSep));
|
||||
value.serialize(&mut **self)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::EnumSeqEnd));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s, 'a, I> ser::SerializeMap for &'s mut Serializer<'a, I>
|
||||
where I: Iterator<Item=&'a Token<'a>>,
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error> where T: Serialize {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::MapSep));
|
||||
key.serialize(&mut **self)
|
||||
}
|
||||
|
||||
fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize {
|
||||
value.serialize(&mut **self)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<(), Self::Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::MapEnd));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s, 'a, I> ser::SerializeStruct for &'s mut Serializer<'a, I>
|
||||
where I: Iterator<Item=&'a Token<'a>>,
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> where T: Serialize {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::StructSep));
|
||||
try!(key.serialize(&mut **self));
|
||||
value.serialize(&mut **self)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<(), Self::Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::StructEnd));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s, 'a, I> ser::SerializeStructVariant for &'s mut Serializer<'a, I>
|
||||
where I: Iterator<Item=&'a Token<'a>>,
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> where T: Serialize {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::EnumMapSep));
|
||||
try!(key.serialize(&mut **self));
|
||||
value.serialize(&mut **self)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<(), Self::Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::EnumMapEnd));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
#[derive(Clone, PartialEq, Debug)]
|
||||
pub enum Token<'a> {
|
||||
Bool(bool),
|
||||
I8(i8),
|
||||
I16(i16),
|
||||
I32(i32),
|
||||
I64(i64),
|
||||
U8(u8),
|
||||
U16(u16),
|
||||
U32(u32),
|
||||
U64(u64),
|
||||
F32(f32),
|
||||
F64(f64),
|
||||
Char(char),
|
||||
Str(&'a str),
|
||||
String(String),
|
||||
Bytes(&'a [u8]),
|
||||
ByteBuf(Vec<u8>),
|
||||
|
||||
Option(bool),
|
||||
|
||||
Unit,
|
||||
UnitStruct(&'a str),
|
||||
|
||||
StructNewType(&'a str),
|
||||
|
||||
EnumStart(&'a str),
|
||||
EnumUnit(&'a str, &'a str),
|
||||
EnumNewType(&'a str, &'a str),
|
||||
|
||||
SeqStart(Option<usize>),
|
||||
SeqArrayStart(usize),
|
||||
SeqSep,
|
||||
SeqEnd,
|
||||
|
||||
TupleStart(usize),
|
||||
TupleSep,
|
||||
TupleEnd,
|
||||
|
||||
TupleStructStart(&'a str, usize),
|
||||
TupleStructSep,
|
||||
TupleStructEnd,
|
||||
|
||||
MapStart(Option<usize>),
|
||||
MapSep,
|
||||
MapEnd,
|
||||
|
||||
StructStart(&'a str, usize),
|
||||
StructSep,
|
||||
StructEnd,
|
||||
|
||||
EnumSeqStart(&'a str, &'a str, usize),
|
||||
EnumSeqSep,
|
||||
EnumSeqEnd,
|
||||
|
||||
EnumMapStart(&'a str, &'a str, usize),
|
||||
EnumMapSep,
|
||||
EnumMapEnd,
|
||||
}
|
||||
@@ -1,819 +0,0 @@
|
||||
use std::collections::{HashMap, BTreeMap};
|
||||
use std::hash::Hash;
|
||||
use std::marker::PhantomData;
|
||||
use std::num::FromPrimitive;
|
||||
use std::path;
|
||||
use std::str;
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub trait Error {
|
||||
fn syntax_error() -> Self;
|
||||
|
||||
fn end_of_stream_error() -> Self;
|
||||
|
||||
fn missing_field_error(&'static str) -> Self;
|
||||
}
|
||||
|
||||
pub trait Deserialize {
|
||||
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
|
||||
where D: Deserializer;
|
||||
}
|
||||
|
||||
pub trait Deserializer {
|
||||
type Error: Error;
|
||||
|
||||
fn visit<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
|
||||
/// The `visit_option` method allows a `Deserialize` type to inform the
|
||||
/// `Deserializer` that it's expecting an optional value. This allows
|
||||
/// deserializers that encode an optional value as a nullable value to
|
||||
/// convert the null value into a `None`, and a regular value as
|
||||
/// `Some(value)`.
|
||||
#[inline]
|
||||
fn visit_option<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
self.visit(visitor)
|
||||
}
|
||||
|
||||
/// The `visit_enum` method allows a `Deserialize` type to inform the
|
||||
/// `Deserializer` that it's expecting an enum value. This allows
|
||||
/// deserializers that provide a custom enumeration serialization to
|
||||
/// properly deserialize the type.
|
||||
#[inline]
|
||||
fn visit_enum<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
self.visit(visitor)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Visitor {
|
||||
type Value;
|
||||
|
||||
fn visit_bool<E>(&mut self, _v: bool) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
{
|
||||
Err(Error::syntax_error())
|
||||
}
|
||||
|
||||
fn visit_isize<E>(&mut self, v: isize) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
{
|
||||
self.visit_i64(v as i64)
|
||||
}
|
||||
|
||||
fn visit_i8<E>(&mut self, v: i8) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
{
|
||||
self.visit_i64(v as i64)
|
||||
}
|
||||
|
||||
fn visit_i16<E>(&mut self, v: i16) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
{
|
||||
self.visit_i64(v as i64)
|
||||
}
|
||||
|
||||
fn visit_i32<E>(&mut self, v: i32) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
{
|
||||
self.visit_i64(v as i64)
|
||||
}
|
||||
|
||||
fn visit_i64<E>(&mut self, _v: i64) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
{
|
||||
Err(Error::syntax_error())
|
||||
}
|
||||
|
||||
fn visit_usize<E>(&mut self, v: usize) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
{
|
||||
self.visit_u64(v as u64)
|
||||
}
|
||||
|
||||
fn visit_u8<E>(&mut self, v: u8) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
{
|
||||
self.visit_u64(v as u64)
|
||||
}
|
||||
|
||||
fn visit_u16<E>(&mut self, v: u16) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
{
|
||||
self.visit_u64(v as u64)
|
||||
}
|
||||
|
||||
fn visit_u32<E>(&mut self, v: u32) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
{
|
||||
self.visit_u64(v as u64)
|
||||
}
|
||||
|
||||
fn visit_u64<E>(&mut self, _v: u64) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
{
|
||||
Err(Error::syntax_error())
|
||||
}
|
||||
|
||||
fn visit_f32<E>(&mut self, v: f32) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
{
|
||||
self.visit_f64(v as f64)
|
||||
}
|
||||
|
||||
fn visit_f64<E>(&mut self, _v: f64) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
{
|
||||
Err(Error::syntax_error())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_char<E>(&mut self, v: char) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
{
|
||||
// The unwraps in here should be safe.
|
||||
let mut s = &mut [0; 4];
|
||||
let len = v.encode_utf8(s).unwrap();
|
||||
self.visit_str(str::from_utf8(&s[..len]).unwrap())
|
||||
}
|
||||
|
||||
fn visit_str<E>(&mut self, _v: &str) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
{
|
||||
Err(Error::syntax_error())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_string<E>(&mut self, v: String) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
{
|
||||
self.visit_str(&v)
|
||||
}
|
||||
|
||||
fn visit_unit<E>(&mut self) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
{
|
||||
Err(Error::syntax_error())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_named_unit<E>(&mut self, _name: &str) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
{
|
||||
self.visit_unit()
|
||||
}
|
||||
|
||||
fn visit_none<E>(&mut self) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
{
|
||||
Err(Error::syntax_error())
|
||||
}
|
||||
|
||||
fn visit_some<D>(&mut self, _deserializer: &mut D) -> Result<Self::Value, D::Error>
|
||||
where D: Deserializer,
|
||||
{
|
||||
Err(Error::syntax_error())
|
||||
}
|
||||
|
||||
fn visit_seq<V>(&mut self, _visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: SeqVisitor,
|
||||
{
|
||||
Err(Error::syntax_error())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_named_seq<V>(&mut self, _name: &str, visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: SeqVisitor,
|
||||
{
|
||||
self.visit_seq(visitor)
|
||||
}
|
||||
|
||||
fn visit_map<V>(&mut self, _visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: MapVisitor,
|
||||
{
|
||||
Err(Error::syntax_error())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_named_map<V>(&mut self, _name: &str, visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: MapVisitor,
|
||||
{
|
||||
self.visit_map(visitor)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_enum<V>(&mut self,
|
||||
_name: &str,
|
||||
_variant: &str,
|
||||
_visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: EnumVisitor,
|
||||
{
|
||||
Err(Error::syntax_error())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_variant<V>(&mut self, _name: &str, _visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: EnumVisitor,
|
||||
{
|
||||
Err(Error::syntax_error())
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub trait SeqVisitor {
|
||||
type Error: Error;
|
||||
|
||||
fn visit<T>(&mut self) -> Result<Option<T>, Self::Error>
|
||||
where T: Deserialize;
|
||||
|
||||
fn end(&mut self) -> Result<(), Self::Error>;
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(0, None)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, V> SeqVisitor for &'a mut V where V: SeqVisitor {
|
||||
type Error = V::Error;
|
||||
|
||||
#[inline]
|
||||
fn visit<T>(&mut self) -> Result<Option<T>, V::Error>
|
||||
where T: Deserialize
|
||||
{
|
||||
(**self).visit()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn end(&mut self) -> Result<(), V::Error> {
|
||||
(**self).end()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(**self).size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub trait MapVisitor {
|
||||
type Error: Error;
|
||||
|
||||
#[inline]
|
||||
fn visit<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error>
|
||||
where K: Deserialize,
|
||||
V: Deserialize,
|
||||
{
|
||||
match try!(self.visit_key()) {
|
||||
Some(key) => {
|
||||
let value = try!(self.visit_value());
|
||||
Ok(Some((key, value)))
|
||||
}
|
||||
None => Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_key<K>(&mut self) -> Result<Option<K>, Self::Error>
|
||||
where K: Deserialize;
|
||||
|
||||
fn visit_value<V>(&mut self) -> Result<V, Self::Error>
|
||||
where V: Deserialize;
|
||||
|
||||
fn end(&mut self) -> Result<(), Self::Error>;
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(0, None)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, V_> MapVisitor for &'a mut V_ where V_: MapVisitor {
|
||||
type Error = V_::Error;
|
||||
|
||||
#[inline]
|
||||
fn visit<K, V>(&mut self) -> Result<Option<(K, V)>, V_::Error>
|
||||
where K: Deserialize,
|
||||
V: Deserialize,
|
||||
{
|
||||
(**self).visit()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_key<K>(&mut self) -> Result<Option<K>, V_::Error>
|
||||
where K: Deserialize
|
||||
{
|
||||
(**self).visit_key()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_value<V>(&mut self) -> Result<V, V_::Error>
|
||||
where V: Deserialize
|
||||
{
|
||||
(**self).visit_value()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn end(&mut self) -> Result<(), V_::Error> {
|
||||
(**self).end()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(**self).size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub trait EnumVisitor {
|
||||
type Error: Error;
|
||||
|
||||
fn visit_unit(&mut self) -> Result<(), Self::Error> {
|
||||
Err(Error::syntax_error())
|
||||
}
|
||||
|
||||
fn visit_seq<V>(&mut self, _visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: EnumSeqVisitor,
|
||||
{
|
||||
Err(Error::syntax_error())
|
||||
}
|
||||
|
||||
fn visit_map<V>(&mut self, _visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: EnumMapVisitor,
|
||||
{
|
||||
Err(Error::syntax_error())
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub trait EnumSeqVisitor {
|
||||
type Value;
|
||||
|
||||
fn visit<V>(&mut self, visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: SeqVisitor;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub trait EnumMapVisitor {
|
||||
type Value;
|
||||
|
||||
fn visit<V>(&mut self, visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: MapVisitor;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct UnitVisitor;
|
||||
|
||||
impl Visitor for UnitVisitor {
|
||||
type Value = ();
|
||||
|
||||
fn visit_unit<E>(&mut self) -> Result<(), E>
|
||||
where E: Error,
|
||||
{
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_seq<V>(&mut self, mut visitor: V) -> Result<(), V::Error>
|
||||
where V: SeqVisitor,
|
||||
{
|
||||
visitor.end()
|
||||
}
|
||||
}
|
||||
|
||||
impl Deserialize for () {
|
||||
fn deserialize<D>(deserializer: &mut D) -> Result<(), D::Error>
|
||||
where D: Deserializer,
|
||||
{
|
||||
deserializer.visit(UnitVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct BoolVisitor;
|
||||
|
||||
impl Visitor for BoolVisitor {
|
||||
type Value = bool;
|
||||
|
||||
fn visit_bool<E>(&mut self, v: bool) -> Result<bool, E>
|
||||
where E: Error,
|
||||
{
|
||||
Ok(v)
|
||||
}
|
||||
}
|
||||
|
||||
impl Deserialize for bool {
|
||||
fn deserialize<D>(deserializer: &mut D) -> Result<bool, D::Error>
|
||||
where D: Deserializer,
|
||||
{
|
||||
deserializer.visit(BoolVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! impl_deserialize_num_method {
|
||||
($src_ty:ty, $method:ident, $from_method:ident) => {
|
||||
#[inline]
|
||||
fn $method<E>(&mut self, v: $src_ty) -> Result<T, E>
|
||||
where E: Error,
|
||||
{
|
||||
match FromPrimitive::$from_method(v) {
|
||||
Some(v) => Ok(v),
|
||||
None => Err(Error::syntax_error()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PrimitiveVisitor<T> {
|
||||
marker: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T> PrimitiveVisitor<T> {
|
||||
#[inline]
|
||||
pub fn new() -> Self {
|
||||
PrimitiveVisitor {
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<
|
||||
T: Deserialize + FromPrimitive
|
||||
> self::Visitor for PrimitiveVisitor<T> {
|
||||
type Value = T;
|
||||
|
||||
impl_deserialize_num_method!(isize, visit_isize, from_isize);
|
||||
impl_deserialize_num_method!(i8, visit_i8, from_i8);
|
||||
impl_deserialize_num_method!(i16, visit_i16, from_i16);
|
||||
impl_deserialize_num_method!(i32, visit_i32, from_i32);
|
||||
impl_deserialize_num_method!(i64, visit_i64, from_i64);
|
||||
impl_deserialize_num_method!(usize, visit_usize, from_usize);
|
||||
impl_deserialize_num_method!(u8, visit_u8, from_u8);
|
||||
impl_deserialize_num_method!(u16, visit_u16, from_u16);
|
||||
impl_deserialize_num_method!(u32, visit_u32, from_u32);
|
||||
impl_deserialize_num_method!(u64, visit_u64, from_u64);
|
||||
impl_deserialize_num_method!(f32, visit_f32, from_f32);
|
||||
impl_deserialize_num_method!(f64, visit_f64, from_f64);
|
||||
}
|
||||
|
||||
macro_rules! impl_deserialize_num {
|
||||
($ty:ty) => {
|
||||
impl Deserialize for $ty {
|
||||
#[inline]
|
||||
fn deserialize<D>(deserializer: &mut D) -> Result<$ty, D::Error>
|
||||
where D: Deserializer,
|
||||
{
|
||||
deserializer.visit(PrimitiveVisitor::new())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl_deserialize_num!(isize);
|
||||
impl_deserialize_num!(i8);
|
||||
impl_deserialize_num!(i16);
|
||||
impl_deserialize_num!(i32);
|
||||
impl_deserialize_num!(i64);
|
||||
impl_deserialize_num!(usize);
|
||||
impl_deserialize_num!(u8);
|
||||
impl_deserialize_num!(u16);
|
||||
impl_deserialize_num!(u32);
|
||||
impl_deserialize_num!(u64);
|
||||
impl_deserialize_num!(f32);
|
||||
impl_deserialize_num!(f64);
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct CharVisitor;
|
||||
|
||||
impl Visitor for CharVisitor {
|
||||
type Value = char;
|
||||
|
||||
#[inline]
|
||||
fn visit_char<E>(&mut self, v: char) -> Result<char, E>
|
||||
where E: Error,
|
||||
{
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_str<E>(&mut self, v: &str) -> Result<char, E>
|
||||
where E: Error,
|
||||
{
|
||||
let mut iter = v.chars();
|
||||
if let Some(v) = iter.next() {
|
||||
if iter.next().is_some() {
|
||||
Err(Error::syntax_error())
|
||||
} else {
|
||||
Ok(v)
|
||||
}
|
||||
} else {
|
||||
Err(Error::end_of_stream_error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Deserialize for char {
|
||||
#[inline]
|
||||
fn deserialize<D>(deserializer: &mut D) -> Result<char, D::Error>
|
||||
where D: Deserializer,
|
||||
{
|
||||
deserializer.visit(CharVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct StringVisitor;
|
||||
|
||||
impl Visitor for StringVisitor {
|
||||
type Value = String;
|
||||
|
||||
fn visit_str<E>(&mut self, v: &str) -> Result<String, E>
|
||||
where E: Error,
|
||||
{
|
||||
Ok(v.to_string())
|
||||
}
|
||||
|
||||
fn visit_string<E>(&mut self, v: String) -> Result<String, E>
|
||||
where E: Error,
|
||||
{
|
||||
Ok(v)
|
||||
}
|
||||
}
|
||||
|
||||
impl Deserialize for String {
|
||||
fn deserialize<D>(deserializer: &mut D) -> Result<String, D::Error>
|
||||
where D: Deserializer,
|
||||
{
|
||||
deserializer.visit(StringVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct OptionVisitor<T> {
|
||||
marker: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<
|
||||
T: Deserialize,
|
||||
> Visitor for OptionVisitor<T> {
|
||||
type Value = Option<T>;
|
||||
|
||||
#[inline]
|
||||
fn visit_none<E>(&mut self) -> Result<Option<T>, E>
|
||||
where E: Error,
|
||||
{
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_some<D>(&mut self, deserializer: &mut D) -> Result<Option<T>, D::Error>
|
||||
where D: Deserializer,
|
||||
{
|
||||
Ok(Some(try!(Deserialize::deserialize(deserializer))))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deserialize for Option<T> where T: Deserialize {
|
||||
fn deserialize<D>(deserializer: &mut D) -> Result<Option<T>, D::Error>
|
||||
where D: Deserializer,
|
||||
{
|
||||
deserializer.visit_option(OptionVisitor { marker: PhantomData })
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub struct VecVisitor<T> {
|
||||
marker: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T> VecVisitor<T> {
|
||||
pub fn new() -> Self {
|
||||
VecVisitor {
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Visitor for VecVisitor<T> where T: Deserialize {
|
||||
type Value = Vec<T>;
|
||||
|
||||
#[inline]
|
||||
fn visit_seq<V>(&mut self, mut visitor: V) -> Result<Vec<T>, V::Error>
|
||||
where V: SeqVisitor,
|
||||
{
|
||||
let (len, _) = visitor.size_hint();
|
||||
let mut values = Vec::with_capacity(len);
|
||||
|
||||
while let Some(value) = try!(visitor.visit()) {
|
||||
values.push(value);
|
||||
}
|
||||
|
||||
Ok(values)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Deserialize> Deserialize for Vec<T> {
|
||||
fn deserialize<D>(deserializer: &mut D) -> Result<Vec<T>, D::Error>
|
||||
where D: Deserializer,
|
||||
{
|
||||
deserializer.visit(VecVisitor::new())
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! tuple_impls {
|
||||
() => {};
|
||||
($($visitor:ident => ($($name:ident),+),)+) => {
|
||||
$(
|
||||
struct $visitor<$($name,)+> {
|
||||
marker: PhantomData<($($name,)+)>,
|
||||
}
|
||||
|
||||
impl<
|
||||
$($name: Deserialize,)+
|
||||
> Visitor for $visitor<$($name,)+> {
|
||||
type Value = ($($name,)+);
|
||||
|
||||
#[inline]
|
||||
#[allow(non_snake_case)]
|
||||
fn visit_seq<V>(&mut self, mut visitor: V) -> Result<($($name,)+), V::Error>
|
||||
where V: SeqVisitor,
|
||||
{
|
||||
$(
|
||||
let $name = match try!(visitor.visit()) {
|
||||
Some(value) => value,
|
||||
None => { return Err(Error::end_of_stream_error()); }
|
||||
};
|
||||
)+;
|
||||
|
||||
try!(visitor.end());
|
||||
|
||||
Ok(($($name,)+))
|
||||
}
|
||||
}
|
||||
|
||||
impl<
|
||||
$($name: Deserialize),+
|
||||
> Deserialize for ($($name,)+) {
|
||||
#[inline]
|
||||
fn deserialize<D>(deserializer: &mut D) -> Result<($($name,)+), D::Error>
|
||||
where D: Deserializer,
|
||||
{
|
||||
deserializer.visit($visitor { marker: PhantomData })
|
||||
}
|
||||
}
|
||||
)+
|
||||
}
|
||||
}
|
||||
|
||||
tuple_impls! {
|
||||
TupleVisitor1 => (T0),
|
||||
TupleVisitor2 => (T0, T1),
|
||||
TupleVisitor3 => (T0, T1, T2),
|
||||
TupleVisitor4 => (T0, T1, T2, T3),
|
||||
TupleVisitor5 => (T0, T1, T2, T3, T4),
|
||||
TupleVisitor6 => (T0, T1, T2, T3, T4, T5),
|
||||
TupleVisitor7 => (T0, T1, T2, T3, T4, T5, T6),
|
||||
TupleVisitor8 => (T0, T1, T2, T3, T4, T5, T6, T7),
|
||||
TupleVisitor9 => (T0, T1, T2, T3, T4, T5, T6, T7, T8),
|
||||
TupleVisitor10 => (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9),
|
||||
TupleVisitor11 => (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10),
|
||||
TupleVisitor12 => (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11),
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub struct HashMapVisitor<K, V> {
|
||||
marker: PhantomData<HashMap<K, V>>,
|
||||
}
|
||||
|
||||
impl<K, V> HashMapVisitor<K, V> {
|
||||
#[inline]
|
||||
pub fn new() -> Self {
|
||||
HashMapVisitor {
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<K, V> Visitor for HashMapVisitor<K, V>
|
||||
where K: Deserialize + Eq + Hash,
|
||||
V: Deserialize,
|
||||
{
|
||||
type Value = HashMap<K, V>;
|
||||
|
||||
#[inline]
|
||||
fn visit_map<V_>(&mut self, mut visitor: V_) -> Result<HashMap<K, V>, V_::Error>
|
||||
where V_: MapVisitor,
|
||||
{
|
||||
let (len, _) = visitor.size_hint();
|
||||
let mut values = HashMap::with_capacity(len);
|
||||
|
||||
while let Some((key, value)) = try!(visitor.visit()) {
|
||||
values.insert(key, value);
|
||||
}
|
||||
|
||||
Ok(values)
|
||||
}
|
||||
}
|
||||
|
||||
impl<K, V> Deserialize for HashMap<K, V>
|
||||
where K: Deserialize + Eq + Hash,
|
||||
V: Deserialize,
|
||||
{
|
||||
fn deserialize<D>(deserializer: &mut D) -> Result<HashMap<K, V>, D::Error>
|
||||
where D: Deserializer,
|
||||
{
|
||||
deserializer.visit(HashMapVisitor::new())
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub struct BTreeMapVisitor<K, V> {
|
||||
marker: PhantomData<BTreeMap<K, V>>,
|
||||
}
|
||||
|
||||
impl<K, V> BTreeMapVisitor<K, V> {
|
||||
#[inline]
|
||||
pub fn new() -> Self {
|
||||
BTreeMapVisitor {
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<K, V> Visitor for BTreeMapVisitor<K, V>
|
||||
where K: Deserialize + Ord,
|
||||
V: Deserialize
|
||||
{
|
||||
type Value = BTreeMap<K, V>;
|
||||
|
||||
#[inline]
|
||||
fn visit_map<Visitor>(&mut self, mut visitor: Visitor) -> Result<BTreeMap<K, V>, Visitor::Error>
|
||||
where Visitor: MapVisitor,
|
||||
{
|
||||
let mut values = BTreeMap::new();
|
||||
|
||||
while let Some((key, value)) = try!(visitor.visit()) {
|
||||
values.insert(key, value);
|
||||
}
|
||||
|
||||
Ok(values)
|
||||
}
|
||||
}
|
||||
|
||||
impl<
|
||||
K: Deserialize + Eq + Ord,
|
||||
V: Deserialize,
|
||||
> Deserialize for BTreeMap<K, V> {
|
||||
fn deserialize<D>(deserializer: &mut D) -> Result<BTreeMap<K, V>, D::Error>
|
||||
where D: Deserializer,
|
||||
{
|
||||
deserializer.visit(BTreeMapVisitor::new())
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct PathBufVisitor;
|
||||
|
||||
impl Visitor for PathBufVisitor {
|
||||
type Value = path::PathBuf;
|
||||
|
||||
fn visit_str<E>(&mut self, v: &str) -> Result<path::PathBuf, E>
|
||||
where E: Error,
|
||||
{
|
||||
Ok(path::PathBuf::new(&v))
|
||||
}
|
||||
|
||||
fn visit_string<E>(&mut self, v: String) -> Result<path::PathBuf, E>
|
||||
where E: Error,
|
||||
{
|
||||
self.visit_str(&v)
|
||||
}
|
||||
}
|
||||
|
||||
impl Deserialize for path::PathBuf {
|
||||
fn deserialize<D>(deserializer: &mut D) -> Result<path::PathBuf, D::Error>
|
||||
where D: Deserializer,
|
||||
{
|
||||
deserializer.visit(PathBufVisitor)
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
|
||||
// file at the top-level directory of this distribution and at
|
||||
// http://rust-lang.org/COPYRIGHT.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use ser::{self, Serialize};
|
||||
use json::value::{self, Value};
|
||||
|
||||
pub struct ArrayBuilder {
|
||||
array: Vec<Value>,
|
||||
}
|
||||
|
||||
impl ArrayBuilder {
|
||||
pub fn new() -> ArrayBuilder {
|
||||
ArrayBuilder { array: Vec::new() }
|
||||
}
|
||||
|
||||
pub fn unwrap(self) -> Value {
|
||||
Value::Array(self.array)
|
||||
}
|
||||
|
||||
pub fn push<T: ser::Serialize>(mut self, v: T) -> ArrayBuilder {
|
||||
self.array.push(value::to_value(&v));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn push_array<F>(mut self, f: F) -> ArrayBuilder where
|
||||
F: FnOnce(ArrayBuilder) -> ArrayBuilder
|
||||
{
|
||||
let builder = ArrayBuilder::new();
|
||||
self.array.push(f(builder).unwrap());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn push_object<F>(mut self, f: F) -> ArrayBuilder where
|
||||
F: FnOnce(ObjectBuilder) -> ObjectBuilder
|
||||
{
|
||||
let builder = ObjectBuilder::new();
|
||||
self.array.push(f(builder).unwrap());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ObjectBuilder {
|
||||
object: BTreeMap<String, Value>,
|
||||
}
|
||||
|
||||
impl ObjectBuilder {
|
||||
pub fn new() -> ObjectBuilder {
|
||||
ObjectBuilder { object: BTreeMap::new() }
|
||||
}
|
||||
|
||||
pub fn unwrap(self) -> Value {
|
||||
Value::Object(self.object)
|
||||
}
|
||||
|
||||
pub fn insert<V: ser::Serialize>(mut self, k: String, v: V) -> ObjectBuilder {
|
||||
self.object.insert(k, value::to_value(&v));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn insert_array<F>(mut self, key: String, f: F) -> ObjectBuilder where
|
||||
F: FnOnce(ArrayBuilder) -> ArrayBuilder
|
||||
{
|
||||
let builder = ArrayBuilder::new();
|
||||
self.object.insert(key, f(builder).unwrap());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn insert_object<F>(mut self, key: String, f: F) -> ObjectBuilder where
|
||||
F: FnOnce(ObjectBuilder) -> ObjectBuilder
|
||||
{
|
||||
let builder = ObjectBuilder::new();
|
||||
self.object.insert(key, f(builder).unwrap());
|
||||
self
|
||||
}
|
||||
}
|
||||
-636
@@ -1,636 +0,0 @@
|
||||
use std::char;
|
||||
use std::num::Float;
|
||||
use unicode::str::Utf16Item;
|
||||
use std::str;
|
||||
|
||||
use de;
|
||||
use super::error::{Error, ErrorCode};
|
||||
|
||||
pub struct Deserializer<Iter> {
|
||||
rdr: Iter,
|
||||
ch: Option<u8>,
|
||||
line: usize,
|
||||
col: usize,
|
||||
buf: Vec<u8>,
|
||||
}
|
||||
|
||||
impl<Iter> Deserializer<Iter>
|
||||
where Iter: Iterator<Item=u8>,
|
||||
{
|
||||
/// Creates the JSON parser.
|
||||
#[inline]
|
||||
pub fn new(rdr: Iter) -> Deserializer<Iter> {
|
||||
let mut p = Deserializer {
|
||||
rdr: rdr,
|
||||
ch: Some(b'\x00'),
|
||||
line: 1,
|
||||
col: 0,
|
||||
buf: Vec::with_capacity(128),
|
||||
};
|
||||
p.bump();
|
||||
return p;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn end(&mut self) -> Result<(), Error> {
|
||||
self.parse_whitespace();
|
||||
if self.eof() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(self.error(ErrorCode::TrailingCharacters))
|
||||
}
|
||||
}
|
||||
|
||||
fn eof(&self) -> bool { self.ch.is_none() }
|
||||
|
||||
fn ch_or_null(&self) -> u8 { self.ch.unwrap_or(b'\x00') }
|
||||
|
||||
fn bump(&mut self) {
|
||||
self.ch = self.rdr.next();
|
||||
|
||||
if self.ch_is(b'\n') {
|
||||
self.line += 1;
|
||||
self.col = 1;
|
||||
} else {
|
||||
self.col += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn next_char(&mut self) -> Option<u8> {
|
||||
self.bump();
|
||||
self.ch
|
||||
}
|
||||
|
||||
fn ch_is(&self, c: u8) -> bool {
|
||||
self.ch == Some(c)
|
||||
}
|
||||
|
||||
fn error(&mut self, reason: ErrorCode) -> Error {
|
||||
Error::SyntaxError(reason, self.line, self.col)
|
||||
}
|
||||
|
||||
fn parse_whitespace(&mut self) {
|
||||
while self.ch_is(b' ') ||
|
||||
self.ch_is(b'\n') ||
|
||||
self.ch_is(b'\t') ||
|
||||
self.ch_is(b'\r') { self.bump(); }
|
||||
}
|
||||
|
||||
fn parse_value<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
self.parse_whitespace();
|
||||
|
||||
if self.eof() {
|
||||
return Err(self.error(ErrorCode::EOFWhileParsingValue));
|
||||
}
|
||||
|
||||
match self.ch_or_null() {
|
||||
b'n' => {
|
||||
try!(self.parse_ident(b"ull"));
|
||||
visitor.visit_unit()
|
||||
}
|
||||
b't' => {
|
||||
try!(self.parse_ident(b"rue"));
|
||||
visitor.visit_bool(true)
|
||||
}
|
||||
b'f' => {
|
||||
try!(self.parse_ident(b"alse"));
|
||||
visitor.visit_bool(false)
|
||||
}
|
||||
b'0' ... b'9' | b'-' => self.parse_number(visitor),
|
||||
b'"' => {
|
||||
try!(self.parse_string());
|
||||
let s = str::from_utf8(&self.buf).unwrap();
|
||||
visitor.visit_str(s)
|
||||
}
|
||||
b'[' => {
|
||||
self.bump();
|
||||
visitor.visit_seq(SeqVisitor::new(self))
|
||||
}
|
||||
b'{' => {
|
||||
self.bump();
|
||||
visitor.visit_map(MapVisitor::new(self))
|
||||
}
|
||||
_ => {
|
||||
Err(self.error(ErrorCode::ExpectedSomeValue))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_ident(&mut self, ident: &[u8]) -> Result<(), Error> {
|
||||
if ident.iter().all(|c| Some(*c) == self.next_char()) {
|
||||
self.bump();
|
||||
Ok(())
|
||||
} else {
|
||||
Err(self.error(ErrorCode::ExpectedSomeIdent))
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_number<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
let mut neg = 1;
|
||||
|
||||
if self.ch_is(b'-') {
|
||||
self.bump();
|
||||
neg = -1;
|
||||
}
|
||||
|
||||
let res = try!(self.parse_integer());
|
||||
|
||||
if self.ch_is(b'.') || self.ch_is(b'e') || self.ch_is(b'E') {
|
||||
let neg = neg as f64;
|
||||
let mut res = res as f64;
|
||||
|
||||
if self.ch_is(b'.') {
|
||||
res = try!(self.parse_decimal(res));
|
||||
}
|
||||
|
||||
if self.ch_is(b'e') || self.ch_is(b'E') {
|
||||
res = try!(self.parse_exponent(res));
|
||||
}
|
||||
|
||||
visitor.visit_f64(neg * res)
|
||||
} else {
|
||||
visitor.visit_i64(neg * res)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_integer(&mut self) -> Result<i64, Error> {
|
||||
let mut res = 0;
|
||||
|
||||
match self.ch_or_null() {
|
||||
b'0' => {
|
||||
self.bump();
|
||||
|
||||
// There can be only one leading '0'.
|
||||
match self.ch_or_null() {
|
||||
b'0' ... b'9' => {
|
||||
return Err(self.error(ErrorCode::InvalidNumber));
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
},
|
||||
b'1' ... b'9' => {
|
||||
while !self.eof() {
|
||||
match self.ch_or_null() {
|
||||
c @ b'0' ... b'9' => {
|
||||
res *= 10;
|
||||
res += (c as i64) - (b'0' as i64);
|
||||
self.bump();
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => { return Err(self.error(ErrorCode::InvalidNumber)); }
|
||||
}
|
||||
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
fn parse_decimal(&mut self, res: f64) -> Result<f64, Error> {
|
||||
self.bump();
|
||||
|
||||
// Make sure a digit follows the decimal place.
|
||||
match self.ch_or_null() {
|
||||
b'0' ... b'9' => (),
|
||||
_ => { return Err(self.error(ErrorCode::InvalidNumber)); }
|
||||
}
|
||||
|
||||
let mut res = res;
|
||||
let mut dec = 1.0;
|
||||
while !self.eof() {
|
||||
match self.ch_or_null() {
|
||||
c @ b'0' ... b'9' => {
|
||||
dec /= 10.0;
|
||||
res += (((c as u64) - (b'0' as u64)) as f64) * dec;
|
||||
self.bump();
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
fn parse_exponent(&mut self, mut res: f64) -> Result<f64, Error> {
|
||||
self.bump();
|
||||
|
||||
let mut exp = 0;
|
||||
let mut neg_exp = false;
|
||||
|
||||
if self.ch_is(b'+') {
|
||||
self.bump();
|
||||
} else if self.ch_is(b'-') {
|
||||
self.bump();
|
||||
neg_exp = true;
|
||||
}
|
||||
|
||||
// Make sure a digit follows the exponent place.
|
||||
match self.ch_or_null() {
|
||||
b'0' ... b'9' => (),
|
||||
_ => { return Err(self.error(ErrorCode::InvalidNumber)); }
|
||||
}
|
||||
while !self.eof() {
|
||||
match self.ch_or_null() {
|
||||
c @ b'0' ... b'9' => {
|
||||
exp *= 10;
|
||||
exp += (c as i32) - (b'0' as i32);
|
||||
|
||||
self.bump();
|
||||
}
|
||||
_ => break
|
||||
}
|
||||
}
|
||||
|
||||
let exp: f64 = 10_f64.powi(exp);
|
||||
if neg_exp {
|
||||
res /= exp;
|
||||
} else {
|
||||
res *= exp;
|
||||
}
|
||||
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
fn decode_hex_escape(&mut self) -> Result<u16, Error> {
|
||||
let mut i = 0;
|
||||
let mut n = 0u16;
|
||||
while i < 4 && !self.eof() {
|
||||
self.bump();
|
||||
n = match self.ch_or_null() {
|
||||
c @ b'0' ... b'9' => n * 16_u16 + ((c as u16) - (b'0' as u16)),
|
||||
b'a' | b'A' => n * 16_u16 + 10_u16,
|
||||
b'b' | b'B' => n * 16_u16 + 11_u16,
|
||||
b'c' | b'C' => n * 16_u16 + 12_u16,
|
||||
b'd' | b'D' => n * 16_u16 + 13_u16,
|
||||
b'e' | b'E' => n * 16_u16 + 14_u16,
|
||||
b'f' | b'F' => n * 16_u16 + 15_u16,
|
||||
_ => { return Err(self.error(ErrorCode::InvalidEscape)); }
|
||||
};
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
// Error out if we didn't parse 4 digits.
|
||||
if i != 4 {
|
||||
return Err(self.error(ErrorCode::InvalidEscape));
|
||||
}
|
||||
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn parse_string(&mut self) -> Result<(), Error> {
|
||||
self.buf.clear();
|
||||
|
||||
let mut escape = false;
|
||||
|
||||
loop {
|
||||
let ch = match self.next_char() {
|
||||
Some(ch) => ch,
|
||||
None => { return Err(self.error(ErrorCode::EOFWhileParsingString)); }
|
||||
};
|
||||
|
||||
if escape {
|
||||
match ch {
|
||||
b'"' => self.buf.push(b'"'),
|
||||
b'\\' => self.buf.push(b'\\'),
|
||||
b'/' => self.buf.push(b'/'),
|
||||
b'b' => self.buf.push(b'\x08'),
|
||||
b'f' => self.buf.push(b'\x0c'),
|
||||
b'n' => self.buf.push(b'\n'),
|
||||
b'r' => self.buf.push(b'\r'),
|
||||
b't' => self.buf.push(b'\t'),
|
||||
b'u' => {
|
||||
let c = match try!(self.decode_hex_escape()) {
|
||||
0xDC00 ... 0xDFFF => {
|
||||
return Err(self.error(ErrorCode::LoneLeadingSurrogateInHexEscape));
|
||||
}
|
||||
|
||||
// Non-BMP characters are encoded as a sequence of
|
||||
// two hex escapes, representing UTF-16 surrogates.
|
||||
n1 @ 0xD800 ... 0xDBFF => {
|
||||
let c1 = self.next_char();
|
||||
let c2 = self.next_char();
|
||||
match (c1, c2) {
|
||||
(Some(b'\\'), Some(b'u')) => (),
|
||||
_ => {
|
||||
return Err(self.error(ErrorCode::UnexpectedEndOfHexEscape));
|
||||
}
|
||||
}
|
||||
|
||||
let buf = &[n1, try!(self.decode_hex_escape())];
|
||||
match ::unicode::str::utf16_items(buf).next() {
|
||||
Some(Utf16Item::ScalarValue(c)) => c,
|
||||
_ => {
|
||||
return Err(self.error(ErrorCode::LoneLeadingSurrogateInHexEscape));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
n => match char::from_u32(n as u32) {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
return Err(self.error(ErrorCode::InvalidUnicodeCodePoint));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let buf = &mut [0; 4];
|
||||
let len = c.encode_utf8(buf).unwrap_or(0);
|
||||
self.buf.extend(buf[..len].iter().map(|b| *b));
|
||||
}
|
||||
_ => {
|
||||
return Err(self.error(ErrorCode::InvalidEscape));
|
||||
}
|
||||
}
|
||||
escape = false;
|
||||
} else {
|
||||
match ch {
|
||||
b'"' => {
|
||||
self.bump();
|
||||
return Ok(());
|
||||
}
|
||||
b'\\' => {
|
||||
escape = true;
|
||||
}
|
||||
ch => {
|
||||
self.buf.push(ch);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_object_colon(&mut self) -> Result<(), Error> {
|
||||
self.parse_whitespace();
|
||||
|
||||
if self.ch_is(b':') {
|
||||
self.bump();
|
||||
Ok(())
|
||||
} else if self.eof() {
|
||||
Err(self.error(ErrorCode::EOFWhileParsingObject))
|
||||
} else {
|
||||
Err(self.error(ErrorCode::ExpectedColon))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Iter> de::Deserializer for Deserializer<Iter>
|
||||
where Iter: Iterator<Item=u8>,
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn visit<V>(&mut self, visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
self.parse_value(visitor)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_option<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
self.parse_whitespace();
|
||||
|
||||
if self.eof() {
|
||||
return Err(self.error(ErrorCode::EOFWhileParsingValue));
|
||||
}
|
||||
|
||||
if self.ch_is(b'n') {
|
||||
try!(self.parse_ident(b"ull"));
|
||||
visitor.visit_none()
|
||||
} else {
|
||||
visitor.visit_some(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_enum<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
self.parse_whitespace();
|
||||
|
||||
if self.ch_is(b'{') {
|
||||
self.bump();
|
||||
self.parse_whitespace();
|
||||
|
||||
try!(self.parse_string());
|
||||
try!(self.parse_object_colon());
|
||||
|
||||
let variant = str::from_utf8(&self.buf).unwrap().to_string();
|
||||
|
||||
let value = try!(visitor.visit_variant(&variant, EnumVisitor {
|
||||
de: self,
|
||||
}));
|
||||
|
||||
self.parse_whitespace();
|
||||
|
||||
if self.ch_is(b'}') {
|
||||
self.bump();
|
||||
Ok(value)
|
||||
} else {
|
||||
return Err(self.error(ErrorCode::ExpectedSomeValue));
|
||||
}
|
||||
} else {
|
||||
Err(self.error(ErrorCode::ExpectedSomeValue))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct SeqVisitor<'a, Iter: 'a> {
|
||||
de: &'a mut Deserializer<Iter>,
|
||||
first: bool,
|
||||
}
|
||||
|
||||
impl<'a, Iter> SeqVisitor<'a, Iter> {
|
||||
fn new(de: &'a mut Deserializer<Iter>) -> Self {
|
||||
SeqVisitor {
|
||||
de: de,
|
||||
first: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Iter> de::SeqVisitor for SeqVisitor<'a, Iter>
|
||||
where Iter: Iterator<Item=u8>
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
fn visit<T>(&mut self) -> Result<Option<T>, Error>
|
||||
where T: de::Deserialize,
|
||||
{
|
||||
self.de.parse_whitespace();
|
||||
|
||||
if self.de.ch_is(b']') {
|
||||
self.de.bump();
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
if self.first {
|
||||
self.first = false;
|
||||
} else {
|
||||
if self.de.ch_is(b',') {
|
||||
self.de.bump();
|
||||
} else if self.de.eof() {
|
||||
return Err(self.de.error(ErrorCode::EOFWhileParsingList));
|
||||
} else {
|
||||
return Err(self.de.error(ErrorCode::ExpectedListCommaOrEnd));
|
||||
}
|
||||
}
|
||||
|
||||
let value = try!(de::Deserialize::deserialize(self.de));
|
||||
Ok(Some(value))
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
self.de.parse_whitespace();
|
||||
|
||||
if self.de.ch_is(b']') {
|
||||
self.de.bump();
|
||||
Ok(())
|
||||
} else if self.de.eof() {
|
||||
Err(self.de.error(ErrorCode::EOFWhileParsingList))
|
||||
} else {
|
||||
Err(self.de.error(ErrorCode::TrailingCharacters))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct MapVisitor<'a, Iter: 'a> {
|
||||
de: &'a mut Deserializer<Iter>,
|
||||
first: bool,
|
||||
}
|
||||
|
||||
impl<'a, Iter> MapVisitor<'a, Iter> {
|
||||
fn new(de: &'a mut Deserializer<Iter>) -> Self {
|
||||
MapVisitor {
|
||||
de: de,
|
||||
first: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Iter> de::MapVisitor for MapVisitor<'a, Iter>
|
||||
where Iter: Iterator<Item=u8>
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
|
||||
where K: de::Deserialize,
|
||||
{
|
||||
self.de.parse_whitespace();
|
||||
|
||||
if self.de.ch_is(b'}') {
|
||||
self.de.bump();
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
if self.first {
|
||||
self.first = false;
|
||||
} else {
|
||||
if self.de.ch_is(b',') {
|
||||
self.de.bump();
|
||||
self.de.parse_whitespace();
|
||||
} else if self.de.eof() {
|
||||
return Err(self.de.error(ErrorCode::EOFWhileParsingObject));
|
||||
} else {
|
||||
return Err(self.de.error(ErrorCode::ExpectedObjectCommaOrEnd));
|
||||
}
|
||||
}
|
||||
|
||||
if self.de.eof() {
|
||||
return Err(self.de.error(ErrorCode::EOFWhileParsingValue));
|
||||
}
|
||||
|
||||
if !self.de.ch_is(b'"') {
|
||||
return Err(self.de.error(ErrorCode::KeyMustBeAString));
|
||||
}
|
||||
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
|
||||
}
|
||||
|
||||
fn visit_value<V>(&mut self) -> Result<V, Error>
|
||||
where V: de::Deserialize,
|
||||
{
|
||||
try!(self.de.parse_object_colon());
|
||||
|
||||
Ok(try!(de::Deserialize::deserialize(self.de)))
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
self.de.parse_whitespace();
|
||||
|
||||
if self.de.ch_is(b']') {
|
||||
self.de.bump();
|
||||
Ok(())
|
||||
} else if self.de.eof() {
|
||||
Err(self.de.error(ErrorCode::EOFWhileParsingList))
|
||||
} else {
|
||||
Err(self.de.error(ErrorCode::TrailingCharacters))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct EnumVisitor<'a, Iter: 'a> {
|
||||
de: &'a mut Deserializer<Iter>,
|
||||
}
|
||||
|
||||
impl<'a, Iter> de::EnumVisitor for EnumVisitor<'a, Iter>
|
||||
where Iter: Iterator<Item=u8>,
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
fn visit_unit(&mut self) -> Result<(), Error> {
|
||||
de::Deserialize::deserialize(self.de)
|
||||
}
|
||||
|
||||
fn visit_seq<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::EnumSeqVisitor,
|
||||
{
|
||||
self.de.parse_whitespace();
|
||||
|
||||
if self.de.ch_is(b'[') {
|
||||
self.de.bump();
|
||||
visitor.visit(SeqVisitor::new(self.de))
|
||||
} else {
|
||||
Err(self.de.error(ErrorCode::ExpectedSomeValue))
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_map<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::EnumMapVisitor,
|
||||
{
|
||||
self.de.parse_whitespace();
|
||||
|
||||
if self.de.ch_is(b'{') {
|
||||
self.de.bump();
|
||||
visitor.visit(MapVisitor::new(self.de))
|
||||
} else {
|
||||
Err(self.de.error(ErrorCode::ExpectedSomeValue))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes a json value from an `Iterator<u8>`.
|
||||
pub fn from_iter<I, T>(iter: I) -> Result<T, Error>
|
||||
where I: Iterator<Item=u8>,
|
||||
T: de::Deserialize
|
||||
{
|
||||
let mut de = Deserializer::new(iter);
|
||||
let value = try!(de::Deserialize::deserialize(&mut de));
|
||||
|
||||
// Make sure the whole stream has been consumed.
|
||||
try!(de.end());
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// Decodes a json value from a string
|
||||
pub fn from_str<'a, T>(s: &'a str) -> Result<T, Error>
|
||||
where T: de::Deserialize
|
||||
{
|
||||
from_iter(s.bytes())
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
use std::error;
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
|
||||
use de;
|
||||
|
||||
/// The errors that can arise while parsing a JSON stream.
|
||||
#[derive(Copy, Clone, PartialEq)]
|
||||
pub enum ErrorCode {
|
||||
EOFWhileParsingList,
|
||||
EOFWhileParsingObject,
|
||||
EOFWhileParsingString,
|
||||
EOFWhileParsingValue,
|
||||
ExpectedColon,
|
||||
ExpectedConversion,
|
||||
ExpectedEnumEnd,
|
||||
ExpectedEnumEndToken,
|
||||
ExpectedEnumMapStart,
|
||||
ExpectedEnumToken,
|
||||
ExpectedEnumVariantString,
|
||||
ExpectedListCommaOrEnd,
|
||||
ExpectedName,
|
||||
ExpectedObjectCommaOrEnd,
|
||||
ExpectedSomeIdent,
|
||||
ExpectedSomeValue,
|
||||
InvalidEscape,
|
||||
InvalidNumber,
|
||||
InvalidUnicodeCodePoint,
|
||||
KeyMustBeAString,
|
||||
LoneLeadingSurrogateInHexEscape,
|
||||
MissingField(&'static str),
|
||||
NotFourDigit,
|
||||
NotUtf8,
|
||||
TrailingCharacters,
|
||||
UnexpectedEndOfHexEscape,
|
||||
UnknownVariant,
|
||||
UnrecognizedHex,
|
||||
}
|
||||
|
||||
impl fmt::Debug for ErrorCode {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
use std::fmt::Debug;
|
||||
|
||||
match *self {
|
||||
//ErrorCode::ConversionError(ref token) => write!(f, "failed to convert {}", token),
|
||||
ErrorCode::EOFWhileParsingList => "EOF While parsing list".fmt(f),
|
||||
ErrorCode::EOFWhileParsingObject => "EOF While parsing object".fmt(f),
|
||||
ErrorCode::EOFWhileParsingString => "EOF While parsing string".fmt(f),
|
||||
ErrorCode::EOFWhileParsingValue => "EOF While parsing value".fmt(f),
|
||||
ErrorCode::ExpectedColon => "expected `:`".fmt(f),
|
||||
ErrorCode::ExpectedConversion => "expected conversion".fmt(f),
|
||||
ErrorCode::ExpectedEnumEnd => "expected enum end".fmt(f),
|
||||
ErrorCode::ExpectedEnumEndToken => "expected enum map end".fmt(f),
|
||||
ErrorCode::ExpectedEnumMapStart => "expected enum map start".fmt(f),
|
||||
ErrorCode::ExpectedEnumToken => "expected enum token".fmt(f),
|
||||
ErrorCode::ExpectedEnumVariantString => "expected variant".fmt(f),
|
||||
ErrorCode::ExpectedListCommaOrEnd => "expected `,` or `]`".fmt(f),
|
||||
ErrorCode::ExpectedName => "expected name".fmt(f),
|
||||
ErrorCode::ExpectedObjectCommaOrEnd => "expected `,` or `}`".fmt(f),
|
||||
ErrorCode::ExpectedSomeIdent => "expected ident".fmt(f),
|
||||
ErrorCode::ExpectedSomeValue => "expected value".fmt(f),
|
||||
//ErrorCode::ExpectedTokens(ref token, tokens) => write!(f, "expected {}, found {}", tokens, token),
|
||||
ErrorCode::InvalidEscape => "invalid escape".fmt(f),
|
||||
ErrorCode::InvalidNumber => "invalid number".fmt(f),
|
||||
ErrorCode::InvalidUnicodeCodePoint => "invalid unicode code point".fmt(f),
|
||||
ErrorCode::KeyMustBeAString => "key must be a string".fmt(f),
|
||||
ErrorCode::LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape".fmt(f),
|
||||
ErrorCode::MissingField(ref field) => write!(f, "missing field \"{}\"", field),
|
||||
ErrorCode::NotFourDigit => "invalid \\u escape (not four digits)".fmt(f),
|
||||
ErrorCode::NotUtf8 => "contents not utf-8".fmt(f),
|
||||
ErrorCode::TrailingCharacters => "trailing characters".fmt(f),
|
||||
ErrorCode::UnexpectedEndOfHexEscape => "unexpected end of hex escape".fmt(f),
|
||||
//ErrorCode::UnexpectedName(ref name) => write!(f, "unexpected name {}", name),
|
||||
ErrorCode::UnknownVariant => "unknown variant".fmt(f),
|
||||
ErrorCode::UnrecognizedHex => "invalid \\u escape (unrecognized hex)".fmt(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Debug)]
|
||||
pub enum Error {
|
||||
/// msg, line, col
|
||||
SyntaxError(ErrorCode, usize, usize),
|
||||
IoError(io::Error),
|
||||
/*
|
||||
ExpectedError(String, String),
|
||||
*/
|
||||
MissingFieldError(&'static str),
|
||||
/*
|
||||
UnknownVariantError(String),
|
||||
*/
|
||||
}
|
||||
|
||||
impl error::Error for Error {
|
||||
fn description(&self) -> &str {
|
||||
match *self {
|
||||
Error::SyntaxError(..) => "syntax error",
|
||||
Error::IoError(ref error) => error.description(),
|
||||
/*
|
||||
Error::ExpectedError(ref expected, _) => &expected,
|
||||
*/
|
||||
Error::MissingFieldError(_) => "missing field",
|
||||
/*
|
||||
Error::UnknownVariantError(_) => "unknown variant",
|
||||
*/
|
||||
}
|
||||
}
|
||||
|
||||
fn cause(&self) -> Option<&error::Error> {
|
||||
match *self {
|
||||
Error::IoError(ref error) => Some(error),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
Error::SyntaxError(ref code, line, col) => {
|
||||
write!(fmt, "{:?} at line {} column {}", code, line, col)
|
||||
}
|
||||
Error::IoError(ref error) => fmt::Display::fmt(error, fmt),
|
||||
/*
|
||||
Error::ExpectedError(ref expected, ref found) => {
|
||||
Some(format!("expected {}, found {}", expected, found))
|
||||
}
|
||||
*/
|
||||
Error::MissingFieldError(ref field) => {
|
||||
write!(fmt, "missing field {}", field)
|
||||
}
|
||||
/*
|
||||
Error::UnknownVariantError(ref variant) => {
|
||||
Some(format!("unknown variant {}", variant))
|
||||
}
|
||||
*/
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl error::FromError<io::Error> for Error {
|
||||
fn from_error(error: io::Error) -> Error {
|
||||
Error::IoError(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl de::Error for Error {
|
||||
fn syntax_error() -> Error {
|
||||
Error::SyntaxError(ErrorCode::ExpectedSomeValue, 0, 0)
|
||||
}
|
||||
|
||||
fn end_of_stream_error() -> Error {
|
||||
Error::SyntaxError(ErrorCode::EOFWhileParsingValue, 0, 0)
|
||||
}
|
||||
|
||||
fn missing_field_error(field: &'static str) -> Error {
|
||||
Error::MissingFieldError(field)
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
pub use self::de::{Deserializer, from_str};
|
||||
pub use self::error::{Error, ErrorCode};
|
||||
pub use self::ser::{
|
||||
Serializer,
|
||||
to_writer,
|
||||
to_writer_pretty,
|
||||
to_vec,
|
||||
to_vec_pretty,
|
||||
to_string,
|
||||
to_string_pretty,
|
||||
escape_str,
|
||||
};
|
||||
pub use self::value::{Value, to_value, from_value};
|
||||
|
||||
pub mod builder;
|
||||
pub mod de;
|
||||
pub mod error;
|
||||
pub mod ser;
|
||||
pub mod value;
|
||||
-457
@@ -1,457 +0,0 @@
|
||||
use std::{f32, f64};
|
||||
use std::io;
|
||||
use std::num::{Float, FpCategory};
|
||||
use std::string::FromUtf8Error;
|
||||
|
||||
use ser;
|
||||
|
||||
/// A structure for implementing serialization to JSON.
|
||||
pub struct Serializer<W> {
|
||||
writer: W,
|
||||
format: Format,
|
||||
current_indent: usize,
|
||||
indent: usize,
|
||||
}
|
||||
|
||||
#[derive(Copy, PartialEq)]
|
||||
enum Format {
|
||||
Compact,
|
||||
Pretty,
|
||||
}
|
||||
|
||||
impl<W: io::Write> Serializer<W> {
|
||||
/// Creates a new JSON visitr whose output will be written to the writer
|
||||
/// specified.
|
||||
#[inline]
|
||||
pub fn new(writer: W) -> Serializer<W> {
|
||||
Serializer {
|
||||
writer: writer,
|
||||
format: Format::Compact,
|
||||
current_indent: 0,
|
||||
indent: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new JSON visitr whose output will be written to the writer
|
||||
/// specified.
|
||||
#[inline]
|
||||
pub fn new_pretty(writer: W) -> Serializer<W> {
|
||||
Serializer {
|
||||
writer: writer,
|
||||
format: Format::Pretty,
|
||||
current_indent: 0,
|
||||
indent: 2,
|
||||
}
|
||||
}
|
||||
|
||||
/// Unwrap the `Writer` from the `Serializer`.
|
||||
#[inline]
|
||||
pub fn into_inner(self) -> W {
|
||||
self.writer
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: io::Write> ser::Serializer for Serializer<W> {
|
||||
type Value = ();
|
||||
type Error = io::Error;
|
||||
|
||||
#[inline]
|
||||
fn visit<T>(&mut self, value: &T) -> io::Result<()>
|
||||
where T: ser::Serialize,
|
||||
{
|
||||
value.visit(&mut Visitor {
|
||||
writer: &mut self.writer,
|
||||
format: self.format,
|
||||
current_indent: self.current_indent,
|
||||
indent: self.indent,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct Visitor<'a, W: 'a> {
|
||||
writer: &'a mut W,
|
||||
format: Format,
|
||||
current_indent: usize,
|
||||
indent: usize,
|
||||
}
|
||||
|
||||
impl<'a, W> Visitor<'a, W> where W: io::Write, {
|
||||
fn serialize_sep(&mut self, first: bool) -> io::Result<()> {
|
||||
match self.format {
|
||||
Format::Compact => {
|
||||
if first {
|
||||
Ok(())
|
||||
} else {
|
||||
self.writer.write_all(b",")
|
||||
}
|
||||
}
|
||||
Format::Pretty => {
|
||||
if first {
|
||||
self.current_indent += self.indent;
|
||||
try!(self.writer.write_all(b"\n"));
|
||||
} else {
|
||||
try!(self.writer.write_all(b",\n"));
|
||||
}
|
||||
|
||||
spaces(&mut self.writer, self.current_indent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_colon(&mut self) -> io::Result<()> {
|
||||
match self.format {
|
||||
Format::Compact => self.writer.write_all(b":"),
|
||||
Format::Pretty => self.writer.write_all(b": "),
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_end(&mut self, current_indent: usize, s: &[u8]) -> io::Result<()> {
|
||||
if self.format == Format::Pretty && current_indent != self.current_indent {
|
||||
self.current_indent -= self.indent;
|
||||
try!(self.writer.write(b"\n"));
|
||||
try!(spaces(&mut self.writer, self.current_indent));
|
||||
}
|
||||
|
||||
self.writer.write_all(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, W> ser::Visitor for Visitor<'a, W> where W: io::Write, {
|
||||
type Value = ();
|
||||
type Error = io::Error;
|
||||
|
||||
#[inline]
|
||||
fn visit_bool(&mut self, value: bool) -> io::Result<()> {
|
||||
if value {
|
||||
self.writer.write_all(b"true")
|
||||
} else {
|
||||
self.writer.write_all(b"false")
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_isize(&mut self, value: isize) -> io::Result<()> {
|
||||
write!(self.writer, "{}", value)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_i8(&mut self, value: i8) -> io::Result<()> {
|
||||
write!(self.writer, "{}", value)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_i16(&mut self, value: i16) -> io::Result<()> {
|
||||
write!(self.writer, "{}", value)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_i32(&mut self, value: i32) -> io::Result<()> {
|
||||
write!(self.writer, "{}", value)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_i64(&mut self, value: i64) -> io::Result<()> {
|
||||
write!(self.writer, "{}", value)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_usize(&mut self, value: usize) -> io::Result<()> {
|
||||
write!(self.writer, "{}", value)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_u8(&mut self, value: u8) -> io::Result<()> {
|
||||
write!(self.writer, "{}", value)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_u16(&mut self, value: u16) -> io::Result<()> {
|
||||
write!(self.writer, "{}", value)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_u32(&mut self, value: u32) -> io::Result<()> {
|
||||
write!(self.writer, "{}", value)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_u64(&mut self, value: u64) -> io::Result<()> {
|
||||
write!(self.writer, "{}", value)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_f32(&mut self, value: f32) -> io::Result<()> {
|
||||
fmt_f32_or_null(self.writer, value)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_f64(&mut self, value: f64) -> io::Result<()> {
|
||||
fmt_f64_or_null(self.writer, value)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_char(&mut self, value: char) -> io::Result<()> {
|
||||
escape_char(self.writer, value)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_str(&mut self, value: &str) -> io::Result<()> {
|
||||
escape_str(self.writer, value)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_none(&mut self) -> io::Result<()> {
|
||||
self.visit_unit()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_some<V>(&mut self, value: V) -> io::Result<()>
|
||||
where V: ser::Serialize
|
||||
{
|
||||
value.visit(self)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_unit(&mut self) -> io::Result<()> {
|
||||
self.writer.write_all(b"null")
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_enum_unit(&mut self, _name: &str, variant: &str) -> io::Result<()> {
|
||||
let current_indent = self.current_indent;
|
||||
|
||||
try!(self.writer.write_all(b"{"));
|
||||
try!(self.serialize_sep(true));
|
||||
try!(self.visit_str(variant));
|
||||
try!(self.serialize_colon());
|
||||
try!(self.writer.write_all(b"[]"));
|
||||
self.serialize_end(current_indent, b"}")
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_seq<V>(&mut self, mut visitor: V) -> io::Result<()>
|
||||
where V: ser::SeqVisitor,
|
||||
{
|
||||
let current_indent = self.current_indent;
|
||||
|
||||
try!(self.writer.write_all(b"["));
|
||||
|
||||
while let Some(()) = try!(visitor.visit(self)) { }
|
||||
|
||||
self.serialize_end(current_indent, b"]")
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_enum_seq<V>(&mut self, _name: &str, variant: &str, visitor: V) -> io::Result<()>
|
||||
where V: ser::SeqVisitor,
|
||||
{
|
||||
let current_indent = self.current_indent;
|
||||
|
||||
try!(self.writer.write_all(b"{"));
|
||||
try!(self.serialize_sep(true));
|
||||
try!(self.visit_str(variant));
|
||||
try!(self.serialize_colon());
|
||||
try!(self.visit_seq(visitor));
|
||||
self.serialize_end(current_indent, b"}")
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_seq_elt<T>(&mut self, first: bool, value: T) -> io::Result<()>
|
||||
where T: ser::Serialize,
|
||||
{
|
||||
try!(self.serialize_sep(first));
|
||||
|
||||
value.visit(self)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_map<V>(&mut self, mut visitor: V) -> io::Result<()>
|
||||
where V: ser::MapVisitor,
|
||||
{
|
||||
let current_indent = self.current_indent;
|
||||
|
||||
try!(self.writer.write_all(b"{"));
|
||||
|
||||
while let Some(()) = try!(visitor.visit(self)) { }
|
||||
|
||||
self.serialize_end(current_indent, b"}")
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_enum_map<V>(&mut self, _name: &str, variant: &str, visitor: V) -> io::Result<()>
|
||||
where V: ser::MapVisitor,
|
||||
{
|
||||
let current_indent = self.current_indent;
|
||||
|
||||
try!(self.writer.write_all(b"{"));
|
||||
try!(self.serialize_sep(true));
|
||||
try!(self.visit_str(variant));
|
||||
try!(self.serialize_colon());
|
||||
try!(self.visit_map(visitor));
|
||||
self.serialize_end(current_indent, b"}")
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_map_elt<K, V>(&mut self, first: bool, key: K, value: V) -> io::Result<()>
|
||||
where K: ser::Serialize,
|
||||
V: ser::Serialize,
|
||||
{
|
||||
try!(self.serialize_sep(first));
|
||||
try!(key.visit(self));
|
||||
try!(self.serialize_colon());
|
||||
value.visit(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn escape_bytes<W>(wr: &mut W, bytes: &[u8]) -> io::Result<()>
|
||||
where W: io::Write
|
||||
{
|
||||
try!(wr.write_all(b"\""));
|
||||
|
||||
let mut start = 0;
|
||||
|
||||
for (i, byte) in bytes.iter().enumerate() {
|
||||
let escaped = match *byte {
|
||||
b'"' => b"\\\"",
|
||||
b'\\' => b"\\\\",
|
||||
b'\x08' => b"\\b",
|
||||
b'\x0c' => b"\\f",
|
||||
b'\n' => b"\\n",
|
||||
b'\r' => b"\\r",
|
||||
b'\t' => b"\\t",
|
||||
_ => { continue; }
|
||||
};
|
||||
|
||||
if start < i {
|
||||
try!(wr.write_all(&bytes[start..i]));
|
||||
}
|
||||
|
||||
try!(wr.write_all(escaped));
|
||||
|
||||
start = i + 1;
|
||||
}
|
||||
|
||||
if start != bytes.len() {
|
||||
try!(wr.write_all(&bytes[start..]));
|
||||
}
|
||||
|
||||
try!(wr.write_all(b"\""));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn escape_str<W>(wr: &mut W, value: &str) -> io::Result<()>
|
||||
where W: io::Write
|
||||
{
|
||||
escape_bytes(wr, value.as_bytes())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn escape_char<W>(wr: &mut W, value: char) -> io::Result<()>
|
||||
where W: io::Write
|
||||
{
|
||||
let buf = &mut [0; 4];
|
||||
value.encode_utf8(buf);
|
||||
escape_bytes(wr, buf)
|
||||
}
|
||||
|
||||
fn fmt_f32_or_null<W>(wr: &mut W, value: f32) -> io::Result<()>
|
||||
where W: io::Write
|
||||
{
|
||||
match value.classify() {
|
||||
FpCategory::Nan | FpCategory::Infinite => wr.write_all(b"null"),
|
||||
_ => wr.write_all(f32::to_str_digits(value, 6).as_bytes()),
|
||||
}
|
||||
}
|
||||
|
||||
fn fmt_f64_or_null<W>(wr: &mut W, value: f64) -> io::Result<()>
|
||||
where W: io::Write
|
||||
{
|
||||
match value.classify() {
|
||||
FpCategory::Nan | FpCategory::Infinite => wr.write_all(b"null"),
|
||||
_ => wr.write_all(f64::to_str_digits(value, 6).as_bytes()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode the specified struct into a json `[u8]` writer.
|
||||
#[inline]
|
||||
pub fn to_writer<W, T>(writer: &mut W, value: &T) -> io::Result<()>
|
||||
where W: io::Write,
|
||||
T: ser::Serialize,
|
||||
{
|
||||
let mut ser = Serializer::new(writer);
|
||||
try!(ser::Serializer::visit(&mut ser, value));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encode the specified struct into a json `[u8]` writer.
|
||||
#[inline]
|
||||
pub fn to_writer_pretty<W, T>(writer: &mut W, value: &T) -> io::Result<()>
|
||||
where W: io::Write,
|
||||
T: ser::Serialize,
|
||||
{
|
||||
let mut ser = Serializer::new_pretty(writer);
|
||||
try!(ser::Serializer::visit(&mut ser, value));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encode the specified struct into a json `[u8]` buffer.
|
||||
#[inline]
|
||||
pub fn to_vec<T>(value: &T) -> Vec<u8>
|
||||
where T: ser::Serialize,
|
||||
{
|
||||
// We are writing to a Vec, which doesn't fail. So we can ignore
|
||||
// the error.
|
||||
let mut writer = Vec::with_capacity(128);
|
||||
to_writer(&mut writer, value).unwrap();
|
||||
writer
|
||||
}
|
||||
|
||||
/// Encode the specified struct into a json `[u8]` buffer.
|
||||
#[inline]
|
||||
pub fn to_vec_pretty<T>(value: &T) -> Vec<u8>
|
||||
where T: ser::Serialize,
|
||||
{
|
||||
// We are writing to a Vec, which doesn't fail. So we can ignore
|
||||
// the error.
|
||||
let mut writer = Vec::with_capacity(128);
|
||||
to_writer_pretty(&mut writer, value).unwrap();
|
||||
writer
|
||||
}
|
||||
|
||||
/// Encode the specified struct into a json `String` buffer.
|
||||
#[inline]
|
||||
pub fn to_string<T>(value: &T) -> Result<String, FromUtf8Error>
|
||||
where T: ser::Serialize
|
||||
{
|
||||
let vec = to_vec(value);
|
||||
String::from_utf8(vec)
|
||||
}
|
||||
|
||||
/// Encode the specified struct into a json `String` buffer.
|
||||
#[inline]
|
||||
pub fn to_string_pretty<T>(value: &T) -> Result<String, FromUtf8Error>
|
||||
where T: ser::Serialize
|
||||
{
|
||||
let vec = to_vec_pretty(value);
|
||||
String::from_utf8(vec)
|
||||
}
|
||||
|
||||
fn spaces<W>(wr: &mut W, mut n: usize) -> io::Result<()>
|
||||
where W: io::Write,
|
||||
{
|
||||
const LEN: usize = 16;
|
||||
const BUF: &'static [u8; LEN] = &[b' '; 16];
|
||||
|
||||
while n >= LEN {
|
||||
try!(wr.write_all(BUF));
|
||||
n -= LEN;
|
||||
}
|
||||
|
||||
if n > 0 {
|
||||
wr.write_all(&BUF[..n])
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,604 +0,0 @@
|
||||
use std::collections::{BTreeMap, btree_map};
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
use std::str;
|
||||
use std::vec;
|
||||
|
||||
use de;
|
||||
use ser;
|
||||
use super::error::Error;
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub enum Value {
|
||||
Null,
|
||||
Bool(bool),
|
||||
I64(i64),
|
||||
F64(f64),
|
||||
String(String),
|
||||
Array(Vec<Value>),
|
||||
Object(BTreeMap<String, Value>),
|
||||
}
|
||||
|
||||
impl ser::Serialize for Value {
|
||||
#[inline]
|
||||
fn visit<V>(&self, visitor: &mut V) -> Result<V::Value, V::Error>
|
||||
where V: ser::Visitor,
|
||||
{
|
||||
match *self {
|
||||
Value::Null => visitor.visit_unit(),
|
||||
Value::Bool(v) => visitor.visit_bool(v),
|
||||
Value::I64(v) => visitor.visit_i64(v),
|
||||
Value::F64(v) => visitor.visit_f64(v),
|
||||
Value::String(ref v) => visitor.visit_str(&v),
|
||||
Value::Array(ref v) => v.visit(visitor),
|
||||
Value::Object(ref v) => v.visit(visitor),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl de::Deserialize for Value {
|
||||
#[inline]
|
||||
fn deserialize<D>(deserializer: &mut D) -> Result<Value, D::Error>
|
||||
where D: de::Deserializer,
|
||||
{
|
||||
struct ValueVisitor;
|
||||
|
||||
impl de::Visitor for ValueVisitor {
|
||||
type Value = Value;
|
||||
|
||||
#[inline]
|
||||
fn visit_bool<E>(&mut self, value: bool) -> Result<Value, E> {
|
||||
Ok(Value::Bool(value))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_i64<E>(&mut self, value: i64) -> Result<Value, E> {
|
||||
Ok(Value::I64(value))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_f64<E>(&mut self, value: f64) -> Result<Value, E> {
|
||||
Ok(Value::F64(value))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_str<E>(&mut self, value: &str) -> Result<Value, E>
|
||||
where E: de::Error,
|
||||
{
|
||||
self.visit_string(value.to_string())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_string<E>(&mut self, value: String) -> Result<Value, E> {
|
||||
Ok(Value::String(value))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_none<E>(&mut self) -> Result<Value, E> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_some<D>(&mut self, deserializer: &mut D) -> Result<Value, D::Error>
|
||||
where D: de::Deserializer,
|
||||
{
|
||||
de::Deserialize::deserialize(deserializer)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_unit<E>(&mut self) -> Result<Value, E> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_seq<V>(&mut self, visitor: V) -> Result<Value, V::Error>
|
||||
where V: de::SeqVisitor,
|
||||
{
|
||||
let values = try!(de::VecVisitor::new().visit_seq(visitor));
|
||||
Ok(Value::Array(values))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_map<V>(&mut self, visitor: V) -> Result<Value, V::Error>
|
||||
where V: de::MapVisitor,
|
||||
{
|
||||
let values = try!(de::BTreeMapVisitor::new().visit_map(visitor));
|
||||
Ok(Value::Object(values))
|
||||
}
|
||||
}
|
||||
|
||||
deserializer.visit(ValueVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
struct WriterFormatter<'a, 'b: 'a> {
|
||||
inner: &'a mut fmt::Formatter<'b>,
|
||||
}
|
||||
|
||||
impl<'a, 'b> io::Write for WriterFormatter<'a, 'b> {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
match self.inner.write_str(str::from_utf8(buf).unwrap()) {
|
||||
Ok(_) => Ok(buf.len()),
|
||||
Err(_) => Err(io::Error::last_os_error()),
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Value {
|
||||
/// Serializes a json value into a string
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
let mut wr = WriterFormatter { inner: f };
|
||||
super::ser::to_writer(&mut wr, self).map_err(|_| fmt::Error)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum State {
|
||||
Value(Value),
|
||||
Array(Vec<Value>),
|
||||
Object(BTreeMap<String, Value>),
|
||||
}
|
||||
|
||||
pub struct Serializer {
|
||||
state: Vec<State>,
|
||||
}
|
||||
|
||||
impl Serializer {
|
||||
pub fn new() -> Serializer {
|
||||
Serializer {
|
||||
state: Vec::with_capacity(4),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unwrap(mut self) -> Value {
|
||||
match self.state.pop().unwrap() {
|
||||
State::Value(value) => value,
|
||||
state => panic!("expected value, found {:?}", state),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ser::Serializer for Serializer {
|
||||
type Value = ();
|
||||
type Error = ();
|
||||
|
||||
#[inline]
|
||||
fn visit<T>(&mut self, value: &T) -> Result<(), ()>
|
||||
where T: ser::Serialize,
|
||||
{
|
||||
try!(value.visit(self));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl ser::Visitor for Serializer {
|
||||
type Value = ();
|
||||
type Error = ();
|
||||
|
||||
#[inline]
|
||||
fn visit_bool(&mut self, value: bool) -> Result<(), ()> {
|
||||
self.state.push(State::Value(Value::Bool(value)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_i64(&mut self, value: i64) -> Result<(), ()> {
|
||||
self.state.push(State::Value(Value::I64(value)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_u64(&mut self, value: u64) -> Result<(), ()> {
|
||||
self.state.push(State::Value(Value::I64(value as i64)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_f64(&mut self, value: f64) -> Result<(), ()> {
|
||||
self.state.push(State::Value(Value::F64(value as f64)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_char(&mut self, value: char) -> Result<(), ()> {
|
||||
self.state.push(State::Value(Value::String(value.to_string())));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_str(&mut self, value: &str) -> Result<(), ()> {
|
||||
self.state.push(State::Value(Value::String(value.to_string())));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_none(&mut self) -> Result<(), ()> {
|
||||
self.visit_unit()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_some<V>(&mut self, value: V) -> Result<(), ()>
|
||||
where V: ser::Serialize,
|
||||
{
|
||||
value.visit(self)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_unit(&mut self) -> Result<(), ()> {
|
||||
self.state.push(State::Value(Value::Null));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_enum_unit(&mut self, _name: &str, variant: &str) -> Result<(), ()> {
|
||||
let mut values = BTreeMap::new();
|
||||
values.insert(variant.to_string(), Value::Array(vec![]));
|
||||
|
||||
self.state.push(State::Value(Value::Object(values)));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_seq<V>(&mut self, mut visitor: V) -> Result<(), ()>
|
||||
where V: ser::SeqVisitor,
|
||||
{
|
||||
let len = match visitor.size_hint() {
|
||||
(_, Some(len)) => len,
|
||||
(len, None) => len,
|
||||
};
|
||||
|
||||
let values = Vec::with_capacity(len);
|
||||
|
||||
self.state.push(State::Array(values));
|
||||
|
||||
while let Some(()) = try!(visitor.visit(self)) { }
|
||||
|
||||
let values = match self.state.pop().unwrap() {
|
||||
State::Array(values) => values,
|
||||
state => panic!("Expected array, found {:?}", state),
|
||||
};
|
||||
|
||||
self.state.push(State::Value(Value::Array(values)));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_enum_seq<V>(&mut self, _name: &str, variant: &str, visitor: V) -> Result<(), ()>
|
||||
where V: ser::SeqVisitor,
|
||||
{
|
||||
try!(self.visit_seq(visitor));
|
||||
|
||||
let value = match self.state.pop().unwrap() {
|
||||
State::Value(value) => value,
|
||||
state => panic!("expected value, found {:?}", state),
|
||||
};
|
||||
|
||||
let mut object = BTreeMap::new();
|
||||
|
||||
object.insert(variant.to_string(), value);
|
||||
|
||||
self.state.push(State::Value(Value::Object(object)));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_seq_elt<T>(&mut self, _first: bool, value: T) -> Result<(), ()>
|
||||
where T: ser::Serialize,
|
||||
{
|
||||
try!(value.visit(self));
|
||||
|
||||
let value = match self.state.pop().unwrap() {
|
||||
State::Value(value) => value,
|
||||
state => panic!("expected value, found {:?}", state),
|
||||
};
|
||||
|
||||
match *self.state.last_mut().unwrap() {
|
||||
State::Array(ref mut values) => { values.push(value); }
|
||||
ref state => panic!("expected array, found {:?}", state),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_map<V>(&mut self, mut visitor: V) -> Result<(), ()>
|
||||
where V: ser::MapVisitor,
|
||||
{
|
||||
let values = BTreeMap::new();
|
||||
|
||||
self.state.push(State::Object(values));
|
||||
|
||||
while let Some(()) = try!(visitor.visit(self)) { }
|
||||
|
||||
let values = match self.state.pop().unwrap() {
|
||||
State::Object(values) => values,
|
||||
state => panic!("expected object, found {:?}", state),
|
||||
};
|
||||
|
||||
self.state.push(State::Value(Value::Object(values)));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_enum_map<V>(&mut self, _name: &str, variant: &str, visitor: V) -> Result<(), ()>
|
||||
where V: ser::MapVisitor,
|
||||
{
|
||||
try!(self.visit_map(visitor));
|
||||
|
||||
let value = match self.state.pop().unwrap() {
|
||||
State::Value(value) => value,
|
||||
state => panic!("expected value, found {:?}", state),
|
||||
};
|
||||
|
||||
let mut object = BTreeMap::new();
|
||||
|
||||
object.insert(variant.to_string(), value);
|
||||
|
||||
self.state.push(State::Value(Value::Object(object)));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_map_elt<K, V>(&mut self, _first: bool, key: K, value: V) -> Result<(), ()>
|
||||
where K: ser::Serialize,
|
||||
V: ser::Serialize,
|
||||
{
|
||||
try!(key.visit(self));
|
||||
|
||||
let key = match self.state.pop().unwrap() {
|
||||
State::Value(Value::String(value)) => value,
|
||||
state => panic!("expected key, found {:?}", state),
|
||||
};
|
||||
|
||||
try!(value.visit(self));
|
||||
|
||||
let value = match self.state.pop().unwrap() {
|
||||
State::Value(value) => value,
|
||||
state => panic!("expected value, found {:?}", state),
|
||||
};
|
||||
|
||||
match *self.state.last_mut().unwrap() {
|
||||
State::Object(ref mut values) => { values.insert(key, value); }
|
||||
ref state => panic!("expected object, found {:?}", state),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Deserializer {
|
||||
value: Option<Value>,
|
||||
}
|
||||
|
||||
impl Deserializer {
|
||||
/// Creates a new deserializer instance for deserializing the specified JSON value.
|
||||
pub fn new(value: Value) -> Deserializer {
|
||||
Deserializer {
|
||||
value: Some(value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl de::Deserializer for Deserializer {
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn visit<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
let value = match self.value.take() {
|
||||
Some(value) => value,
|
||||
None => { return Err(de::Error::end_of_stream_error()); }
|
||||
};
|
||||
|
||||
match value {
|
||||
Value::Null => visitor.visit_unit(),
|
||||
Value::Bool(v) => visitor.visit_bool(v),
|
||||
Value::I64(v) => visitor.visit_i64(v),
|
||||
Value::F64(v) => visitor.visit_f64(v),
|
||||
Value::String(v) => visitor.visit_string(v),
|
||||
Value::Array(v) => {
|
||||
let len = v.len();
|
||||
visitor.visit_seq(SeqDeserializer {
|
||||
de: self,
|
||||
iter: v.into_iter(),
|
||||
len: len,
|
||||
})
|
||||
}
|
||||
Value::Object(v) => {
|
||||
let len = v.len();
|
||||
visitor.visit_map(MapDeserializer {
|
||||
de: self,
|
||||
iter: v.into_iter(),
|
||||
value: None,
|
||||
len: len,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_option<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
match self.value {
|
||||
Some(Value::Null) => visitor.visit_none(),
|
||||
Some(_) => visitor.visit_some(self),
|
||||
None => Err(de::Error::end_of_stream_error()),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_enum<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
let value = match self.value.take() {
|
||||
Some(Value::Object(value)) => value,
|
||||
Some(_) => { return Err(de::Error::syntax_error()); }
|
||||
None => { return Err(de::Error::end_of_stream_error()); }
|
||||
};
|
||||
|
||||
let mut iter = value.into_iter();
|
||||
|
||||
let value = match iter.next() {
|
||||
Some((variant, Value::Array(fields))) => {
|
||||
let len = fields.len();
|
||||
try!(visitor.visit_variant(&variant, SeqDeserializer {
|
||||
de: self,
|
||||
iter: fields.into_iter(),
|
||||
len: len,
|
||||
}))
|
||||
}
|
||||
Some((variant, Value::Object(fields))) => {
|
||||
let len = fields.len();
|
||||
try!(visitor.visit_variant(&variant, MapDeserializer {
|
||||
de: self,
|
||||
iter: fields.into_iter(),
|
||||
value: None,
|
||||
len: len,
|
||||
}))
|
||||
}
|
||||
Some(_) => { return Err(de::Error::syntax_error()); }
|
||||
None => { return Err(de::Error::syntax_error()); }
|
||||
};
|
||||
|
||||
match iter.next() {
|
||||
Some(_) => Err(de::Error::syntax_error()),
|
||||
None => Ok(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct SeqDeserializer<'a> {
|
||||
de: &'a mut Deserializer,
|
||||
iter: vec::IntoIter<Value>,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl<'a> de::SeqVisitor for SeqDeserializer<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit<T>(&mut self) -> Result<Option<T>, Error>
|
||||
where T: de::Deserialize
|
||||
{
|
||||
match self.iter.next() {
|
||||
Some(value) => {
|
||||
self.len -= 1;
|
||||
self.de.value = Some(value);
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
|
||||
}
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
if self.len == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(de::Error::end_of_stream_error())
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(self.len, Some(self.len))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> de::EnumVisitor for SeqDeserializer<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_unit(&mut self) -> Result<(), Error> {
|
||||
if self.len == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(de::Error::syntax_error())
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_seq<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::EnumSeqVisitor,
|
||||
{
|
||||
visitor.visit(self)
|
||||
}
|
||||
}
|
||||
|
||||
struct MapDeserializer<'a> {
|
||||
de: &'a mut Deserializer,
|
||||
iter: btree_map::IntoIter<String, Value>,
|
||||
value: Option<Value>,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl<'a> de::MapVisitor for MapDeserializer<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_key<T>(&mut self) -> Result<Option<T>, Error>
|
||||
where T: de::Deserialize
|
||||
{
|
||||
match self.iter.next() {
|
||||
Some((key, value)) => {
|
||||
self.len -= 1;
|
||||
self.value = Some(value);
|
||||
self.de.value = Some(Value::String(key));
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
|
||||
}
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_value<T>(&mut self) -> Result<T, Error>
|
||||
where T: de::Deserialize
|
||||
{
|
||||
let value = self.value.take().unwrap();
|
||||
self.de.value = Some(value);
|
||||
Ok(try!(de::Deserialize::deserialize(self.de)))
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
if self.len == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(de::Error::end_of_stream_error())
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(self.len, Some(self.len))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> de::EnumVisitor for MapDeserializer<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_map<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::EnumMapVisitor,
|
||||
{
|
||||
visitor.visit(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Shortcut function to encode a `T` into a JSON `Value`
|
||||
pub fn to_value<T>(value: &T) -> Value
|
||||
where T: ser::Serialize
|
||||
{
|
||||
let mut ser = Serializer::new();
|
||||
ser::Serializer::visit(&mut ser, value).ok().unwrap();
|
||||
ser.unwrap()
|
||||
}
|
||||
|
||||
/// Shortcut function to decode a JSON `Value` into a `T`
|
||||
pub fn from_value<T>(value: Value) -> Result<T, Error>
|
||||
where T: de::Deserialize
|
||||
{
|
||||
let mut de = Deserializer::new(value);
|
||||
de::Deserialize::deserialize(&mut de)
|
||||
}
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
#![feature(core, io, path, std_misc, unicode)]
|
||||
|
||||
extern crate unicode;
|
||||
|
||||
pub use ser::{Serialize, Serializer};
|
||||
pub use de::{Deserialize, Deserializer, Error};
|
||||
|
||||
pub mod ser;
|
||||
pub mod de;
|
||||
pub mod json;
|
||||
-660
@@ -1,660 +0,0 @@
|
||||
use std::collections::hash_state::HashState;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::hash::Hash;
|
||||
use std::path;
|
||||
use std::rc::Rc;
|
||||
use std::str;
|
||||
use std::sync::Arc;
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub trait Serialize {
|
||||
fn visit<V>(&self, visitor: &mut V) -> Result<V::Value, V::Error>
|
||||
where V: Visitor;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub trait Serializer {
|
||||
type Value;
|
||||
type Error;
|
||||
|
||||
fn visit<T>(&mut self, value: &T) -> Result<Self::Value, Self::Error>
|
||||
where T: Serialize;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub trait Visitor {
|
||||
type Value;
|
||||
type Error;
|
||||
|
||||
fn visit_bool(&mut self, v: bool) -> Result<Self::Value, Self::Error>;
|
||||
|
||||
#[inline]
|
||||
fn visit_isize(&mut self, v: isize) -> Result<Self::Value, Self::Error> {
|
||||
self.visit_i64(v as i64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_i8(&mut self, v: i8) -> Result<Self::Value, Self::Error> {
|
||||
self.visit_i64(v as i64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_i16(&mut self, v: i16) -> Result<Self::Value, Self::Error> {
|
||||
self.visit_i64(v as i64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_i32(&mut self, v: i32) -> Result<Self::Value, Self::Error> {
|
||||
self.visit_i64(v as i64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_i64(&mut self, v: i64) -> Result<Self::Value, Self::Error>;
|
||||
|
||||
#[inline]
|
||||
fn visit_usize(&mut self, v: usize) -> Result<Self::Value, Self::Error> {
|
||||
self.visit_u64(v as u64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_u8(&mut self, v: u8) -> Result<Self::Value, Self::Error> {
|
||||
self.visit_u64(v as u64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_u16(&mut self, v: u16) -> Result<Self::Value, Self::Error> {
|
||||
self.visit_u64(v as u64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_u32(&mut self, v: u32) -> Result<Self::Value, Self::Error> {
|
||||
self.visit_u64(v as u64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_u64(&mut self, v: u64) -> Result<Self::Value, Self::Error>;
|
||||
|
||||
#[inline]
|
||||
fn visit_f32(&mut self, v: f32) -> Result<Self::Value, Self::Error> {
|
||||
self.visit_f64(v as f64)
|
||||
}
|
||||
|
||||
fn visit_f64(&mut self, v: f64) -> Result<Self::Value, Self::Error>;
|
||||
|
||||
#[inline]
|
||||
fn visit_char(&mut self, v: char) -> Result<Self::Value, Self::Error> {
|
||||
// The unwraps in here should be safe.
|
||||
let mut s = &mut [0; 4];
|
||||
let len = v.encode_utf8(s).unwrap();
|
||||
self.visit_str(str::from_utf8(&s[..len]).unwrap())
|
||||
}
|
||||
|
||||
fn visit_str(&mut self, value: &str) -> Result<Self::Value, Self::Error>;
|
||||
|
||||
fn visit_unit(&mut self) -> Result<Self::Value, Self::Error>;
|
||||
|
||||
#[inline]
|
||||
fn visit_named_unit(&mut self, _name: &str) -> Result<Self::Value, Self::Error> {
|
||||
self.visit_unit()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_enum_unit(&mut self,
|
||||
_name: &str,
|
||||
_variant: &str) -> Result<Self::Value, Self::Error> {
|
||||
self.visit_unit()
|
||||
}
|
||||
|
||||
fn visit_none(&mut self) -> Result<Self::Value, Self::Error>;
|
||||
|
||||
fn visit_some<V>(&mut self, value: V) -> Result<Self::Value, Self::Error>
|
||||
where V: Serialize;
|
||||
|
||||
fn visit_seq<V>(&mut self, visitor: V) -> Result<Self::Value, Self::Error>
|
||||
where V: SeqVisitor;
|
||||
|
||||
#[inline]
|
||||
fn visit_named_seq<V>(&mut self,
|
||||
_name: &'static str,
|
||||
visitor: V) -> Result<Self::Value, Self::Error>
|
||||
where V: SeqVisitor,
|
||||
{
|
||||
self.visit_seq(visitor)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_enum_seq<V>(&mut self,
|
||||
_name: &'static str,
|
||||
_variant: &'static str,
|
||||
visitor: V) -> Result<Self::Value, Self::Error>
|
||||
where V: SeqVisitor,
|
||||
{
|
||||
self.visit_seq(visitor)
|
||||
}
|
||||
|
||||
fn visit_seq_elt<T>(&mut self,
|
||||
first: bool,
|
||||
value: T) -> Result<Self::Value, Self::Error>
|
||||
where T: Serialize;
|
||||
|
||||
fn visit_map<V>(&mut self, visitor: V) -> Result<Self::Value, Self::Error>
|
||||
where V: MapVisitor;
|
||||
|
||||
#[inline]
|
||||
fn visit_named_map<V>(&mut self,
|
||||
_name: &'static str,
|
||||
visitor: V) -> Result<Self::Value, Self::Error>
|
||||
where V: MapVisitor,
|
||||
{
|
||||
self.visit_map(visitor)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_enum_map<V>(&mut self,
|
||||
_name: &'static str,
|
||||
_variant: &'static str,
|
||||
visitor: V) -> Result<Self::Value, Self::Error>
|
||||
where V: MapVisitor,
|
||||
{
|
||||
self.visit_map(visitor)
|
||||
}
|
||||
|
||||
fn visit_map_elt<K, V>(&mut self,
|
||||
first: bool,
|
||||
key: K,
|
||||
value: V) -> Result<Self::Value, Self::Error>
|
||||
where K: Serialize,
|
||||
V: Serialize;
|
||||
}
|
||||
|
||||
pub trait SeqVisitor {
|
||||
fn visit<V>(&mut self, visitor: &mut V) -> Result<Option<V::Value>, V::Error>
|
||||
where V: Visitor;
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(0, None)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait MapVisitor {
|
||||
fn visit<V>(&mut self, visitor: &mut V) -> Result<Option<V::Value>, V::Error>
|
||||
where V: Visitor;
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(0, None)
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! impl_visit {
|
||||
($ty:ty, $method:ident) => {
|
||||
impl Serialize for $ty {
|
||||
#[inline]
|
||||
fn visit<V>(&self, visitor: &mut V) -> Result<V::Value, V::Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
visitor.$method(*self)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl_visit!(bool, visit_bool);
|
||||
impl_visit!(isize, visit_isize);
|
||||
impl_visit!(i8, visit_i8);
|
||||
impl_visit!(i16, visit_i16);
|
||||
impl_visit!(i32, visit_i32);
|
||||
impl_visit!(i64, visit_i64);
|
||||
impl_visit!(usize, visit_usize);
|
||||
impl_visit!(u8, visit_u8);
|
||||
impl_visit!(u16, visit_u16);
|
||||
impl_visit!(u32, visit_u32);
|
||||
impl_visit!(u64, visit_u64);
|
||||
impl_visit!(f32, visit_f32);
|
||||
impl_visit!(f64, visit_f64);
|
||||
impl_visit!(char, visit_char);
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<'a> Serialize for &'a str {
|
||||
#[inline]
|
||||
fn visit<V>(&self, visitor: &mut V) -> Result<V::Value, V::Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
visitor.visit_str(*self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for String {
|
||||
#[inline]
|
||||
fn visit<V>(&self, visitor: &mut V) -> Result<V::Value, V::Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
(&self[..]).visit(visitor)
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<T> Serialize for Option<T> where T: Serialize {
|
||||
#[inline]
|
||||
fn visit<V>(&self, visitor: &mut V) -> Result<V::Value, V::Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
match *self {
|
||||
Some(ref value) => visitor.visit_some(value),
|
||||
None => visitor.visit_none(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub struct SeqIteratorVisitor<Iter> {
|
||||
iter: Iter,
|
||||
first: bool,
|
||||
}
|
||||
|
||||
impl<T, Iter> SeqIteratorVisitor<Iter>
|
||||
where Iter: Iterator<Item=T>
|
||||
{
|
||||
#[inline]
|
||||
pub fn new(iter: Iter) -> SeqIteratorVisitor<Iter> {
|
||||
SeqIteratorVisitor {
|
||||
iter: iter,
|
||||
first: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Iter> SeqVisitor for SeqIteratorVisitor<Iter>
|
||||
where T: Serialize,
|
||||
Iter: Iterator<Item=T>,
|
||||
{
|
||||
#[inline]
|
||||
fn visit<V>(&mut self, visitor: &mut V) -> Result<Option<V::Value>, V::Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
let first = self.first;
|
||||
self.first = false;
|
||||
|
||||
match self.iter.next() {
|
||||
Some(value) => {
|
||||
let value = try!(visitor.visit_seq_elt(first, value));
|
||||
Ok(Some(value))
|
||||
}
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
self.iter.size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<'a, T> Serialize for &'a [T]
|
||||
where T: Serialize,
|
||||
{
|
||||
#[inline]
|
||||
fn visit<V>(&self, visitor: &mut V) -> Result<V::Value, V::Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
visitor.visit_seq(SeqIteratorVisitor::new(self.iter()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Serialize for Vec<T> where T: Serialize {
|
||||
#[inline]
|
||||
fn visit<V>(&self, visitor: &mut V) -> Result<V::Value, V::Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
(&self[..]).visit(visitor)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Serialize for BTreeSet<T> where T: Serialize {
|
||||
#[inline]
|
||||
fn visit<V>(&self, visitor: &mut V) -> Result<V::Value, V::Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
visitor.visit_seq(SeqIteratorVisitor::new(self.iter()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S> Serialize for HashSet<T, S>
|
||||
where T: Serialize + Eq + Hash,
|
||||
S: HashState,
|
||||
{
|
||||
#[inline]
|
||||
fn visit<V: Visitor>(&self, visitor: &mut V) -> Result<V::Value, V::Error> {
|
||||
visitor.visit_seq(SeqIteratorVisitor::new(self.iter()))
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl Serialize for () {
|
||||
#[inline]
|
||||
fn visit<V>(&self, visitor: &mut V) -> Result<V::Value, V::Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
visitor.visit_unit()
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// FIXME(rust #19630) Remove this work-around
|
||||
macro_rules! e {
|
||||
($e:expr) => { $e }
|
||||
}
|
||||
|
||||
macro_rules! tuple_impls {
|
||||
($(
|
||||
$TupleVisitor:ident ($len:expr, $($T:ident),+) {
|
||||
$($state:pat => $idx:tt,)+
|
||||
}
|
||||
)+) => {
|
||||
$(
|
||||
pub struct $TupleVisitor<'a, $($T: 'a),+> {
|
||||
tuple: &'a ($($T,)+),
|
||||
state: u8,
|
||||
first: bool,
|
||||
}
|
||||
|
||||
impl<'a, $($T: 'a),+> $TupleVisitor<'a, $($T),+> {
|
||||
pub fn new(tuple: &'a ($($T,)+)) -> $TupleVisitor<'a, $($T),+> {
|
||||
$TupleVisitor {
|
||||
tuple: tuple,
|
||||
state: 0,
|
||||
first: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, $($T),+> SeqVisitor for $TupleVisitor<'a, $($T),+>
|
||||
where $($T: Serialize),+
|
||||
{
|
||||
fn visit<V>(&mut self, visitor: &mut V) -> Result<Option<V::Value>, V::Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
let first = self.first;
|
||||
self.first = false;
|
||||
|
||||
match self.state {
|
||||
$(
|
||||
$state => {
|
||||
self.state += 1;
|
||||
Ok(Some(try!(visitor.visit_seq_elt(first, &e!(self.tuple.$idx)))))
|
||||
}
|
||||
)+
|
||||
_ => {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
($len, Some($len))
|
||||
}
|
||||
}
|
||||
|
||||
impl<$($T),+> Serialize for ($($T,)+)
|
||||
where $($T: Serialize),+
|
||||
{
|
||||
#[inline]
|
||||
fn visit<V: Visitor>(&self, visitor: &mut V) -> Result<V::Value, V::Error> {
|
||||
visitor.visit_seq($TupleVisitor::new(self))
|
||||
}
|
||||
}
|
||||
)+
|
||||
}
|
||||
}
|
||||
|
||||
tuple_impls! {
|
||||
TupleVisitor1 (1, T0) {
|
||||
0 => 0,
|
||||
}
|
||||
TupleVisitor2 (2, T0, T1) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
}
|
||||
TupleVisitor3 (3, T0, T1, T2) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
}
|
||||
TupleVisitor4 (4, T0, T1, T2, T3) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
}
|
||||
TupleVisitor5 (5, T0, T1, T2, T3, T4) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
}
|
||||
TupleVisitor6 (6, T0, T1, T2, T3, T4, T5) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
}
|
||||
TupleVisitor7 (7, T0, T1, T2, T3, T4, T5, T6) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
}
|
||||
TupleVisitor8 (8, T0, T1, T2, T3, T4, T5, T6, T7) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
}
|
||||
TupleVisitor9 (9, T0, T1, T2, T3, T4, T5, T6, T7, T8) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
8 => 8,
|
||||
}
|
||||
TupleVisitor10 (10, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
8 => 8,
|
||||
9 => 9,
|
||||
}
|
||||
TupleVisitor11 (11, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
8 => 8,
|
||||
9 => 9,
|
||||
10 => 10,
|
||||
}
|
||||
TupleVisitor12 (12, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
8 => 8,
|
||||
9 => 9,
|
||||
10 => 10,
|
||||
11 => 11,
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub struct MapIteratorVisitor<Iter> {
|
||||
iter: Iter,
|
||||
first: bool,
|
||||
}
|
||||
|
||||
impl<K, V, Iter> MapIteratorVisitor<Iter>
|
||||
where Iter: Iterator<Item=(K, V)>
|
||||
{
|
||||
#[inline]
|
||||
pub fn new(iter: Iter) -> MapIteratorVisitor<Iter> {
|
||||
MapIteratorVisitor {
|
||||
iter: iter,
|
||||
first: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<K, V, I> MapVisitor for MapIteratorVisitor<I>
|
||||
where K: Serialize,
|
||||
V: Serialize,
|
||||
I: Iterator<Item=(K, V)>,
|
||||
{
|
||||
#[inline]
|
||||
fn visit<V_>(&mut self, visitor: &mut V_) -> Result<Option<V_::Value>, V_::Error>
|
||||
where V_: Visitor,
|
||||
{
|
||||
let first = self.first;
|
||||
self.first = false;
|
||||
|
||||
match self.iter.next() {
|
||||
Some((key, value)) => {
|
||||
let value = try!(visitor.visit_map_elt(first, key, value));
|
||||
Ok(Some(value))
|
||||
}
|
||||
None => Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
self.iter.size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<K, V> Serialize for BTreeMap<K, V>
|
||||
where K: Serialize + Ord,
|
||||
V: Serialize,
|
||||
{
|
||||
#[inline]
|
||||
fn visit<V_: Visitor>(&self, visitor: &mut V_) -> Result<V_::Value, V_::Error> {
|
||||
visitor.visit_map(MapIteratorVisitor::new(self.iter()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<K, V, S> Serialize for HashMap<K, V, S>
|
||||
where K: Serialize + Eq + Hash,
|
||||
V: Serialize,
|
||||
S: HashState,
|
||||
{
|
||||
#[inline]
|
||||
fn visit<V_: Visitor>(&self, visitor: &mut V_) -> Result<V_::Value, V_::Error> {
|
||||
visitor.visit_map(MapIteratorVisitor::new(self.iter()))
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<'a, T> Serialize for &'a T where T: Serialize {
|
||||
#[inline]
|
||||
fn visit<V>(&self, visitor: &mut V) -> Result<V::Value, V::Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
(**self).visit(visitor)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> Serialize for &'a mut T where T: Serialize {
|
||||
#[inline]
|
||||
fn visit<V>(&self, visitor: &mut V) -> Result<V::Value, V::Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
(**self).visit(visitor)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Serialize for Box<T> where T: Serialize {
|
||||
#[inline]
|
||||
fn visit<V>(&self, visitor: &mut V) -> Result<V::Value, V::Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
(**self).visit(visitor)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Serialize for Rc<T> where T: Serialize, {
|
||||
#[inline]
|
||||
fn visit<V>(&self, visitor: &mut V) -> Result<V::Value, V::Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
(**self).visit(visitor)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Serialize for Arc<T> where T: Serialize, {
|
||||
#[inline]
|
||||
fn visit<V>(&self, visitor: &mut V) -> Result<V::Value, V::Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
(**self).visit(visitor)
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl Serialize for path::Path {
|
||||
fn visit<V>(&self, visitor: &mut V) -> Result<V::Value, V::Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
self.to_str().unwrap().visit(visitor)
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for path::PathBuf {
|
||||
fn visit<V>(&self, visitor: &mut V) -> Result<V::Value, V::Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
self.to_str().unwrap().visit(visitor)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
[package]
|
||||
name = "serde_test_suite"
|
||||
version = "0.0.0"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "A generic serialization/deserialization framework"
|
||||
homepage = "https://serde.rs"
|
||||
repository = "https://github.com/serde-rs/serde"
|
||||
documentation = "https://docs.serde.rs/serde/"
|
||||
readme = "README.md"
|
||||
keywords = ["serialization"]
|
||||
publish = false
|
||||
|
||||
[features]
|
||||
unstable-testing = [
|
||||
"compiletest_rs",
|
||||
"serde/unstable-testing",
|
||||
]
|
||||
|
||||
[dev-dependencies]
|
||||
fnv = "1.0"
|
||||
rustc-serialize = "0.3.16"
|
||||
serde = { path = "../serde" }
|
||||
serde_derive = { path = "../serde_derive" }
|
||||
serde_test = { path = "../serde_test" }
|
||||
|
||||
[dependencies]
|
||||
compiletest_rs = { version = "0.2", optional = true }
|
||||
|
||||
[[test]]
|
||||
name = "test"
|
||||
path = "tests/test.rs"
|
||||
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "serde_test_suite_deps"
|
||||
version = "0.0.0"
|
||||
authors = ["David Tolnay <dtolnay@gmail.com>"]
|
||||
publish = false
|
||||
|
||||
[workspace]
|
||||
|
||||
[dependencies]
|
||||
serde = { path = "../../serde" }
|
||||
serde_derive = { path = "../../serde_derive" }
|
||||
@@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "serde_derive_tests_no_std"
|
||||
version = "0.0.0"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
serde = { path = "../../serde", default-features = false }
|
||||
serde_derive = { path = "../../serde_derive" }
|
||||
@@ -0,0 +1,52 @@
|
||||
#![feature(lang_items, start, libc)]
|
||||
#![no_std]
|
||||
|
||||
extern crate libc;
|
||||
|
||||
#[start]
|
||||
fn start(_argc: isize, _argv: *const *const u8) -> isize {
|
||||
0
|
||||
}
|
||||
|
||||
#[lang = "eh_personality"]
|
||||
#[no_mangle]
|
||||
pub extern fn rust_eh_personality() {}
|
||||
|
||||
#[lang = "eh_unwind_resume"]
|
||||
#[no_mangle]
|
||||
pub extern fn rust_eh_unwind_resume() {}
|
||||
|
||||
#[lang = "panic_fmt"]
|
||||
#[no_mangle]
|
||||
pub extern fn rust_begin_panic(_msg: core::fmt::Arguments,
|
||||
_file: &'static str,
|
||||
_line: u32) -> ! {
|
||||
unsafe {
|
||||
libc::abort()
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Unit;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Newtype(u8);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Tuple(u8, u8);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Struct { f: u8 }
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Enum {
|
||||
Unit,
|
||||
Newtype(u8),
|
||||
Tuple(u8, u8),
|
||||
Struct { f: u8 },
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
struct S {
|
||||
#[serde(rename="x", serialize="y")] //~^^ HELP: unknown serde field attribute `serialize`
|
||||
x: (),
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,11 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
struct S {
|
||||
#[serde(rename="x")]
|
||||
#[serde(rename(deserialize="y"))] //~^^^ HELP: duplicate serde attribute `rename`
|
||||
x: (),
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,10 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
struct S {
|
||||
#[serde(rename(serialize="x"), rename(serialize="y"))] //~^^ HELP: duplicate serde attribute `rename`
|
||||
x: (),
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,11 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
struct S {
|
||||
#[serde(rename(serialize="x"))]
|
||||
#[serde(rename="y")] //~^^^ HELP: duplicate serde attribute `rename`
|
||||
x: (),
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,10 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
struct S {
|
||||
#[serde(rename(serialize="x", serialize="y"))] //~^^ HELP: duplicate serde attribute `rename`
|
||||
x: (),
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,11 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
struct S {
|
||||
#[serde(rename(serialize="x"))]
|
||||
#[serde(rename(serialize="y"))] //~^^^ HELP: duplicate serde attribute `rename`
|
||||
x: (),
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,10 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
#[serde(tag = "type")] //~^ HELP: #[serde(tag = "...")] cannot be used with tuple variants
|
||||
enum E {
|
||||
Tuple(u8, u8),
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,8 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
#[serde(tag = "type")] //~^ HELP: #[serde(tag = "...")] can only be used on enums
|
||||
struct S;
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,12 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
#[serde(untagged)]
|
||||
#[serde(tag = "type")] //~^^ HELP: enum cannot be both untagged and internally tagged
|
||||
enum E {
|
||||
A(u8),
|
||||
B(String),
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,8 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
#[serde(untagged)] //~^ HELP: #[serde(untagged)] can only be used on enums
|
||||
struct S;
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,9 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize, Deserialize)] //~ ERROR: proc-macro derive panicked
|
||||
struct Test<'a> {
|
||||
s: &'a str, //~^^ HELP: Serde does not support deserializing fields of type &str
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,10 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
#[serde(abc="xyz")] //~^ HELP: unknown serde container attribute `abc`
|
||||
struct A {
|
||||
x: u32,
|
||||
}
|
||||
|
||||
fn main() { }
|
||||
@@ -0,0 +1,10 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
struct C {
|
||||
#[serde(abc="xyz")] //~^^ HELP: unknown serde field attribute `abc`
|
||||
x: u32,
|
||||
}
|
||||
|
||||
fn main() { }
|
||||
@@ -0,0 +1,10 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
enum E {
|
||||
#[serde(abc="xyz")] //~^^ HELP: unknown serde variant attribute `abc`
|
||||
V,
|
||||
}
|
||||
|
||||
fn main() { }
|
||||
@@ -0,0 +1,26 @@
|
||||
extern crate compiletest_rs as compiletest;
|
||||
|
||||
use std::env;
|
||||
|
||||
fn run_mode(mode: &'static str) {
|
||||
let mut config = compiletest::default_config();
|
||||
|
||||
config.mode = mode.parse().expect("invalid mode");
|
||||
config.target_rustcflags = Some("-L deps/target/debug/deps".to_owned());
|
||||
if let Ok(name) = env::var("TESTNAME") {
|
||||
config.filter = Some(name);
|
||||
}
|
||||
config.src_base = format!("tests/{}", mode).into();
|
||||
|
||||
compiletest::run_tests(&config);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compile_fail() {
|
||||
run_mode("compile-fail");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_pass() {
|
||||
run_mode("run-pass");
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
macro_rules! btreeset {
|
||||
() => {
|
||||
BTreeSet::new()
|
||||
};
|
||||
($($value:expr),+) => {
|
||||
{
|
||||
let mut set = BTreeSet::new();
|
||||
$(set.insert($value);)+
|
||||
set
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! btreemap {
|
||||
() => {
|
||||
BTreeMap::new()
|
||||
};
|
||||
($($key:expr => $value:expr),+) => {
|
||||
{
|
||||
let mut map = BTreeMap::new();
|
||||
$(map.insert($key, $value);)+
|
||||
map
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! hashset {
|
||||
() => {
|
||||
HashSet::new()
|
||||
};
|
||||
($($value:expr),+) => {
|
||||
{
|
||||
let mut set = HashSet::new();
|
||||
$(set.insert($value);)+
|
||||
set
|
||||
}
|
||||
};
|
||||
($hasher:ident @ $($value:expr),+) => {
|
||||
{
|
||||
use std::hash::BuildHasherDefault;
|
||||
let mut set = HashSet::with_hasher(BuildHasherDefault::<$hasher>::default());
|
||||
$(set.insert($value);)+
|
||||
set
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! hashmap {
|
||||
() => {
|
||||
HashMap::new()
|
||||
};
|
||||
($($key:expr => $value:expr),+) => {
|
||||
{
|
||||
let mut map = HashMap::new();
|
||||
$(map.insert($key, $value);)+
|
||||
map
|
||||
}
|
||||
};
|
||||
($hasher:ident @ $($key:expr => $value:expr),+) => {
|
||||
{
|
||||
use std::hash::BuildHasherDefault;
|
||||
let mut map = HashMap::with_hasher(BuildHasherDefault::<$hasher>::default());
|
||||
$(map.insert($key, $value);)+
|
||||
map
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
#![deny(identity_op)]
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
// The derived implementation uses 0+1 to add up the number of fields
|
||||
// serialized, which Clippy warns about. If the expansion info is registered
|
||||
// correctly, the Clippy lint is not triggered.
|
||||
#[derive(Serialize)]
|
||||
struct A { b: u8 }
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,23 @@
|
||||
#![cfg_attr(feature = "unstable-testing", feature(test, non_ascii_idents))]
|
||||
|
||||
#[cfg(feature = "unstable-testing")]
|
||||
extern crate test;
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
extern crate serde;
|
||||
extern crate serde_test;
|
||||
|
||||
#[macro_use]
|
||||
mod macros;
|
||||
|
||||
mod test_annotations;
|
||||
mod test_bytes;
|
||||
mod test_de;
|
||||
mod test_gen;
|
||||
mod test_macros;
|
||||
mod test_ser;
|
||||
|
||||
#[cfg(feature = "unstable-testing")]
|
||||
mod compiletest;
|
||||
@@ -0,0 +1,976 @@
|
||||
extern crate serde;
|
||||
use self::serde::{Serialize, Serializer, Deserialize, Deserializer};
|
||||
|
||||
extern crate serde_test;
|
||||
use self::serde_test::{
|
||||
Error,
|
||||
Token,
|
||||
assert_tokens,
|
||||
assert_ser_tokens,
|
||||
assert_de_tokens,
|
||||
assert_de_tokens_error
|
||||
};
|
||||
|
||||
trait MyDefault: Sized {
|
||||
fn my_default() -> Self;
|
||||
}
|
||||
|
||||
trait ShouldSkip: Sized {
|
||||
fn should_skip(&self) -> bool;
|
||||
}
|
||||
|
||||
trait SerializeWith: Sized {
|
||||
fn serialize_with<S>(&self, ser: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer;
|
||||
}
|
||||
|
||||
trait DeserializeWith: Sized {
|
||||
fn deserialize_with<D>(de: D) -> Result<Self, D::Error>
|
||||
where D: Deserializer;
|
||||
}
|
||||
|
||||
impl MyDefault for i32 {
|
||||
fn my_default() -> Self { 123 }
|
||||
}
|
||||
|
||||
impl ShouldSkip for i32 {
|
||||
fn should_skip(&self) -> bool { *self == 123 }
|
||||
}
|
||||
|
||||
impl SerializeWith for i32 {
|
||||
fn serialize_with<S>(&self, ser: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
if *self == 123 {
|
||||
true.serialize(ser)
|
||||
} else {
|
||||
false.serialize(ser)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DeserializeWith for i32 {
|
||||
fn deserialize_with<D>(de: D) -> Result<Self, D::Error>
|
||||
where D: Deserializer
|
||||
{
|
||||
if try!(Deserialize::deserialize(de)) {
|
||||
Ok(123)
|
||||
} else {
|
||||
Ok(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct DefaultStruct<A, B, C, D, E>
|
||||
where C: MyDefault,
|
||||
E: MyDefault,
|
||||
{
|
||||
a1: A,
|
||||
#[serde(default)]
|
||||
a2: B,
|
||||
#[serde(default="MyDefault::my_default")]
|
||||
a3: C,
|
||||
#[serde(skip_deserializing)]
|
||||
a4: D,
|
||||
#[serde(skip_deserializing, default="MyDefault::my_default")]
|
||||
a5: E,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_struct() {
|
||||
assert_de_tokens(
|
||||
&DefaultStruct { a1: 1, a2: 2, a3: 3, a4: 0, a5: 123 },
|
||||
&[
|
||||
Token::StructStart("DefaultStruct", 3),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a1"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a2"),
|
||||
Token::I32(2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a3"),
|
||||
Token::I32(3),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a4"),
|
||||
Token::I32(4),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a5"),
|
||||
Token::I32(5),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_de_tokens(
|
||||
&DefaultStruct { a1: 1, a2: 0, a3: 123, a4: 0, a5: 123 },
|
||||
&[
|
||||
Token::StructStart("DefaultStruct", 1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a1"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
enum DefaultEnum<A, B, C, D, E>
|
||||
where C: MyDefault,
|
||||
E: MyDefault
|
||||
{
|
||||
Struct {
|
||||
a1: A,
|
||||
#[serde(default)]
|
||||
a2: B,
|
||||
#[serde(default="MyDefault::my_default")]
|
||||
a3: C,
|
||||
#[serde(skip_deserializing)]
|
||||
a4: D,
|
||||
#[serde(skip_deserializing, default="MyDefault::my_default")]
|
||||
a5: E,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_enum() {
|
||||
assert_de_tokens(
|
||||
&DefaultEnum::Struct { a1: 1, a2: 2, a3: 3, a4: 0, a5: 123 },
|
||||
&[
|
||||
Token::EnumMapStart("DefaultEnum", "Struct", 3),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a1"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a2"),
|
||||
Token::I32(2),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a3"),
|
||||
Token::I32(3),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a4"),
|
||||
Token::I32(4),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a5"),
|
||||
Token::I32(5),
|
||||
|
||||
Token::EnumMapEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_de_tokens(
|
||||
&DefaultEnum::Struct { a1: 1, a2: 0, a3: 123, a4: 0, a5: 123 },
|
||||
&[
|
||||
Token::EnumMapStart("DefaultEnum", "Struct", 3),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a1"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::EnumMapEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
// Does not implement std::default::Default.
|
||||
#[derive(Debug, PartialEq, Deserialize)]
|
||||
struct NoStdDefault(i8);
|
||||
|
||||
impl MyDefault for NoStdDefault {
|
||||
fn my_default() -> Self {
|
||||
NoStdDefault(123)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Deserialize)]
|
||||
struct ContainsNoStdDefault<A: MyDefault> {
|
||||
#[serde(default="MyDefault::my_default")]
|
||||
a: A,
|
||||
}
|
||||
|
||||
// Tests that a struct field does not need to implement std::default::Default if
|
||||
// it is annotated with `default=...`.
|
||||
#[test]
|
||||
fn test_no_std_default() {
|
||||
assert_de_tokens(
|
||||
&ContainsNoStdDefault { a: NoStdDefault(123) },
|
||||
&[
|
||||
Token::StructStart("ContainsNoStdDefault", 1),
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_de_tokens(
|
||||
&ContainsNoStdDefault { a: NoStdDefault(8) },
|
||||
&[
|
||||
Token::StructStart("ContainsNoStdDefault", 1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
Token::StructNewType("NoStdDefault"),
|
||||
Token::I8(8),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
// Does not implement Deserialize.
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct NotDeserializeStruct(i8);
|
||||
|
||||
impl Default for NotDeserializeStruct {
|
||||
fn default() -> Self {
|
||||
NotDeserializeStruct(123)
|
||||
}
|
||||
}
|
||||
|
||||
impl DeserializeWith for NotDeserializeStruct {
|
||||
fn deserialize_with<D>(_: D) -> Result<Self, D::Error>
|
||||
where D: Deserializer
|
||||
{
|
||||
panic!()
|
||||
}
|
||||
}
|
||||
|
||||
// Does not implement Deserialize.
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum NotDeserializeEnum { Trouble }
|
||||
|
||||
impl MyDefault for NotDeserializeEnum {
|
||||
fn my_default() -> Self {
|
||||
NotDeserializeEnum::Trouble
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Deserialize)]
|
||||
struct ContainsNotDeserialize<A, B, C: DeserializeWith, E: MyDefault> {
|
||||
#[serde(skip_deserializing)]
|
||||
a: A,
|
||||
#[serde(skip_deserializing, default)]
|
||||
b: B,
|
||||
#[serde(deserialize_with="DeserializeWith::deserialize_with", default)]
|
||||
c: C,
|
||||
#[serde(skip_deserializing, default="MyDefault::my_default")]
|
||||
e: E,
|
||||
}
|
||||
|
||||
// Tests that a struct field does not need to implement Deserialize if it is
|
||||
// annotated with skip_deserializing, whether using the std Default or a
|
||||
// custom default.
|
||||
#[test]
|
||||
fn test_elt_not_deserialize() {
|
||||
assert_de_tokens(
|
||||
&ContainsNotDeserialize {
|
||||
a: NotDeserializeStruct(123),
|
||||
b: NotDeserializeStruct(123),
|
||||
c: NotDeserializeStruct(123),
|
||||
e: NotDeserializeEnum::Trouble,
|
||||
},
|
||||
&[
|
||||
Token::StructStart("ContainsNotDeserialize", 3),
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct DenyUnknown {
|
||||
a1: i32,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ignore_unknown() {
|
||||
// 'Default' allows unknown. Basic smoke test of ignore...
|
||||
assert_de_tokens(
|
||||
&DefaultStruct { a1: 1, a2: 2, a3: 3, a4: 0, a5: 123 },
|
||||
&[
|
||||
Token::StructStart("DefaultStruct", 5),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("whoops1"),
|
||||
Token::I32(2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a1"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("whoops2"),
|
||||
Token::SeqStart(Some(1)),
|
||||
Token::SeqSep,
|
||||
Token::I32(2),
|
||||
Token::SeqEnd,
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a2"),
|
||||
Token::I32(2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("whoops3"),
|
||||
Token::I32(2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a3"),
|
||||
Token::I32(3),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_de_tokens_error::<DenyUnknown>(
|
||||
&[
|
||||
Token::StructStart("DenyUnknown", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a1"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("whoops"),
|
||||
],
|
||||
Error::Message("unknown field `whoops`, expected `a1`".to_owned())
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename="Superhero")]
|
||||
struct RenameStruct {
|
||||
a1: i32,
|
||||
#[serde(rename="a3")]
|
||||
a2: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename(serialize="SuperheroSer", deserialize="SuperheroDe"))]
|
||||
struct RenameStructSerializeDeserialize {
|
||||
a1: i32,
|
||||
#[serde(rename(serialize="a4", deserialize="a5"))]
|
||||
a2: i32,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rename_struct() {
|
||||
assert_tokens(
|
||||
&RenameStruct { a1: 1, a2: 2 },
|
||||
&[
|
||||
Token::StructStart("Superhero", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a1"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a3"),
|
||||
Token::I32(2),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_ser_tokens(
|
||||
&RenameStructSerializeDeserialize { a1: 1, a2: 2 },
|
||||
&[
|
||||
Token::StructStart("SuperheroSer", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a1"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a4"),
|
||||
Token::I32(2),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_de_tokens(
|
||||
&RenameStructSerializeDeserialize { a1: 1, a2: 2 },
|
||||
&[
|
||||
Token::StructStart("SuperheroDe", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a1"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a5"),
|
||||
Token::I32(2),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename="Superhero")]
|
||||
enum RenameEnum {
|
||||
#[serde(rename="bruce_wayne")]
|
||||
Batman,
|
||||
#[serde(rename="clark_kent")]
|
||||
Superman(i8),
|
||||
#[serde(rename="diana_prince")]
|
||||
WonderWoman(i8, i8),
|
||||
#[serde(rename="barry_allan")]
|
||||
Flash {
|
||||
#[serde(rename="b")]
|
||||
a: i32,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Deserialize, Serialize)]
|
||||
#[serde(rename(serialize="SuperheroSer", deserialize="SuperheroDe"))]
|
||||
enum RenameEnumSerializeDeserialize<A> {
|
||||
#[serde(rename(serialize="dick_grayson", deserialize="jason_todd"))]
|
||||
Robin {
|
||||
a: i8,
|
||||
#[serde(rename(serialize="c"))]
|
||||
#[serde(rename(deserialize="d"))]
|
||||
b: A,
|
||||
},
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rename_enum() {
|
||||
assert_tokens(
|
||||
&RenameEnum::Batman,
|
||||
&[
|
||||
Token::EnumUnit("Superhero", "bruce_wayne"),
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&RenameEnum::Superman(0),
|
||||
&[
|
||||
Token::EnumNewType("Superhero", "clark_kent"),
|
||||
Token::I8(0),
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&RenameEnum::WonderWoman(0, 1),
|
||||
&[
|
||||
Token::EnumSeqStart("Superhero", "diana_prince", 2),
|
||||
|
||||
Token::EnumSeqSep,
|
||||
Token::I8(0),
|
||||
|
||||
Token::EnumSeqSep,
|
||||
Token::I8(1),
|
||||
|
||||
Token::EnumSeqEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&RenameEnum::Flash { a: 1 },
|
||||
&[
|
||||
Token::EnumMapStart("Superhero", "barry_allan", 1),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("b"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::EnumMapEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_ser_tokens(
|
||||
&RenameEnumSerializeDeserialize::Robin {
|
||||
a: 0,
|
||||
b: String::new(),
|
||||
},
|
||||
&[
|
||||
Token::EnumMapStart("SuperheroSer", "dick_grayson", 2),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a"),
|
||||
Token::I8(0),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("c"),
|
||||
Token::Str(""),
|
||||
|
||||
Token::EnumMapEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_de_tokens(
|
||||
&RenameEnumSerializeDeserialize::Robin {
|
||||
a: 0,
|
||||
b: String::new(),
|
||||
},
|
||||
&[
|
||||
Token::EnumMapStart("SuperheroDe", "jason_todd", 2),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a"),
|
||||
Token::I8(0),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("d"),
|
||||
Token::Str(""),
|
||||
|
||||
Token::EnumMapEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize)]
|
||||
struct SkipSerializingStruct<'a, B, C> where C: ShouldSkip {
|
||||
a: &'a i8,
|
||||
#[serde(skip_serializing)]
|
||||
b: B,
|
||||
#[serde(skip_serializing_if="ShouldSkip::should_skip")]
|
||||
c: C,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_skip_serializing_struct() {
|
||||
let a = 1;
|
||||
assert_ser_tokens(
|
||||
&SkipSerializingStruct {
|
||||
a: &a,
|
||||
b: 2,
|
||||
c: 3,
|
||||
},
|
||||
&[
|
||||
Token::StructStart("SkipSerializingStruct", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
Token::I8(1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("c"),
|
||||
Token::I32(3),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_ser_tokens(
|
||||
&SkipSerializingStruct {
|
||||
a: &a,
|
||||
b: 2,
|
||||
c: 123,
|
||||
},
|
||||
&[
|
||||
Token::StructStart("SkipSerializingStruct", 1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
Token::I8(1),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize)]
|
||||
enum SkipSerializingEnum<'a, B, C> where C: ShouldSkip {
|
||||
Struct {
|
||||
a: &'a i8,
|
||||
#[serde(skip_serializing)]
|
||||
_b: B,
|
||||
#[serde(skip_serializing_if="ShouldSkip::should_skip")]
|
||||
c: C,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_skip_serializing_enum() {
|
||||
let a = 1;
|
||||
assert_ser_tokens(
|
||||
&SkipSerializingEnum::Struct {
|
||||
a: &a,
|
||||
_b: 2,
|
||||
c: 3,
|
||||
},
|
||||
&[
|
||||
Token::EnumMapStart("SkipSerializingEnum", "Struct", 2),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a"),
|
||||
Token::I8(1),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("c"),
|
||||
Token::I32(3),
|
||||
|
||||
Token::EnumMapEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_ser_tokens(
|
||||
&SkipSerializingEnum::Struct {
|
||||
a: &a,
|
||||
_b: 2,
|
||||
c: 123,
|
||||
},
|
||||
&[
|
||||
Token::EnumMapStart("SkipSerializingEnum", "Struct", 1),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a"),
|
||||
Token::I8(1),
|
||||
|
||||
Token::EnumMapEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct NotSerializeStruct(i8);
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum NotSerializeEnum { Trouble }
|
||||
|
||||
impl SerializeWith for NotSerializeEnum {
|
||||
fn serialize_with<S>(&self, ser: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
"trouble".serialize(ser)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize)]
|
||||
struct ContainsNotSerialize<'a, B, C, D> where B: 'a, D: SerializeWith {
|
||||
a: &'a Option<i8>,
|
||||
#[serde(skip_serializing)]
|
||||
b: &'a B,
|
||||
#[serde(skip_serializing)]
|
||||
c: Option<C>,
|
||||
#[serde(serialize_with="SerializeWith::serialize_with")]
|
||||
d: D,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_elt_not_serialize() {
|
||||
let a = 1;
|
||||
assert_ser_tokens(
|
||||
&ContainsNotSerialize {
|
||||
a: &Some(a),
|
||||
b: &NotSerializeStruct(2),
|
||||
c: Some(NotSerializeEnum::Trouble),
|
||||
d: NotSerializeEnum::Trouble,
|
||||
},
|
||||
&[
|
||||
Token::StructStart("ContainsNotSerialize", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
Token::Option(true),
|
||||
Token::I8(1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("d"),
|
||||
Token::Str("trouble"),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize)]
|
||||
struct SerializeWithStruct<'a, B> where B: SerializeWith {
|
||||
a: &'a i8,
|
||||
#[serde(serialize_with="SerializeWith::serialize_with")]
|
||||
b: B,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_serialize_with_struct() {
|
||||
let a = 1;
|
||||
assert_ser_tokens(
|
||||
&SerializeWithStruct {
|
||||
a: &a,
|
||||
b: 2,
|
||||
},
|
||||
&[
|
||||
Token::StructStart("SerializeWithStruct", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
Token::I8(1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("b"),
|
||||
Token::Bool(false),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_ser_tokens(
|
||||
&SerializeWithStruct {
|
||||
a: &a,
|
||||
b: 123,
|
||||
},
|
||||
&[
|
||||
Token::StructStart("SerializeWithStruct", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
Token::I8(1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("b"),
|
||||
Token::Bool(true),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize)]
|
||||
enum SerializeWithEnum<'a, B> where B: SerializeWith {
|
||||
Struct {
|
||||
a: &'a i8,
|
||||
#[serde(serialize_with="SerializeWith::serialize_with")]
|
||||
b: B,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_serialize_with_enum() {
|
||||
let a = 1;
|
||||
assert_ser_tokens(
|
||||
&SerializeWithEnum::Struct {
|
||||
a: &a,
|
||||
b: 2,
|
||||
},
|
||||
&[
|
||||
Token::EnumMapStart("SerializeWithEnum", "Struct", 2),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a"),
|
||||
Token::I8(1),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("b"),
|
||||
Token::Bool(false),
|
||||
|
||||
Token::EnumMapEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_ser_tokens(
|
||||
&SerializeWithEnum::Struct {
|
||||
a: &a,
|
||||
b: 123,
|
||||
},
|
||||
&[
|
||||
Token::EnumMapStart("SerializeWithEnum", "Struct", 2),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a"),
|
||||
Token::I8(1),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("b"),
|
||||
Token::Bool(true),
|
||||
|
||||
Token::EnumMapEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Deserialize)]
|
||||
struct DeserializeWithStruct<B> where B: DeserializeWith {
|
||||
a: i8,
|
||||
#[serde(deserialize_with="DeserializeWith::deserialize_with")]
|
||||
b: B,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deserialize_with_struct() {
|
||||
assert_de_tokens(
|
||||
&DeserializeWithStruct {
|
||||
a: 1,
|
||||
b: 2,
|
||||
},
|
||||
&[
|
||||
Token::StructStart("DeserializeWithStruct", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
Token::I8(1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("b"),
|
||||
Token::Bool(false),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_de_tokens(
|
||||
&DeserializeWithStruct {
|
||||
a: 1,
|
||||
b: 123,
|
||||
},
|
||||
&[
|
||||
Token::StructStart("DeserializeWithStruct", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
Token::I8(1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("b"),
|
||||
Token::Bool(true),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Deserialize)]
|
||||
enum DeserializeWithEnum<B> where B: DeserializeWith {
|
||||
Struct {
|
||||
a: i8,
|
||||
#[serde(deserialize_with="DeserializeWith::deserialize_with")]
|
||||
b: B,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deserialize_with_enum() {
|
||||
assert_de_tokens(
|
||||
&DeserializeWithEnum::Struct {
|
||||
a: 1,
|
||||
b: 2,
|
||||
},
|
||||
&[
|
||||
Token::EnumMapStart("DeserializeWithEnum", "Struct", 2),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a"),
|
||||
Token::I8(1),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("b"),
|
||||
Token::Bool(false),
|
||||
|
||||
Token::EnumMapEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_de_tokens(
|
||||
&DeserializeWithEnum::Struct {
|
||||
a: 1,
|
||||
b: 123,
|
||||
},
|
||||
&[
|
||||
Token::EnumMapStart("DeserializeWithEnum", "Struct", 2),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a"),
|
||||
Token::I8(1),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("b"),
|
||||
Token::Bool(true),
|
||||
|
||||
Token::EnumMapEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_missing_renamed_field_struct() {
|
||||
assert_de_tokens_error::<RenameStruct>(
|
||||
&[
|
||||
Token::StructStart("Superhero", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a1"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::StructEnd,
|
||||
],
|
||||
Error::Message("missing field `a3`".to_owned()),
|
||||
);
|
||||
|
||||
assert_de_tokens_error::<RenameStructSerializeDeserialize>(
|
||||
&[
|
||||
Token::StructStart("SuperheroDe", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a1"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::StructEnd,
|
||||
],
|
||||
Error::Message("missing field `a5`".to_owned()),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_missing_renamed_field_enum() {
|
||||
assert_de_tokens_error::<RenameEnum>(
|
||||
&[
|
||||
Token::EnumMapStart("Superhero", "barry_allan", 1),
|
||||
|
||||
Token::EnumMapEnd,
|
||||
],
|
||||
Error::Message("missing field `b`".to_owned()),
|
||||
);
|
||||
|
||||
assert_de_tokens_error::<RenameEnumSerializeDeserialize<i8>>(
|
||||
&[
|
||||
Token::EnumMapStart("SuperheroDe", "jason_todd", 2),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a"),
|
||||
Token::I8(0),
|
||||
|
||||
Token::EnumMapEnd,
|
||||
],
|
||||
Error::Message("missing field `d`".to_owned()),
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Deserialize)]
|
||||
enum InvalidLengthEnum {
|
||||
A(i32, i32, i32),
|
||||
B(#[serde(skip_deserializing)] i32, i32, i32),
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_length_enum() {
|
||||
assert_de_tokens_error::<InvalidLengthEnum>(
|
||||
&[
|
||||
Token::EnumSeqStart("InvalidLengthEnum", "A", 3),
|
||||
Token::EnumSeqSep,
|
||||
Token::I32(1),
|
||||
Token::EnumSeqEnd,
|
||||
],
|
||||
Error::Message("invalid length 1, expected tuple of 3 elements".to_owned()),
|
||||
);
|
||||
assert_de_tokens_error::<InvalidLengthEnum>(
|
||||
&[
|
||||
Token::EnumSeqStart("InvalidLengthEnum", "B", 3),
|
||||
Token::EnumSeqSep,
|
||||
Token::I32(1),
|
||||
Token::EnumSeqEnd,
|
||||
],
|
||||
Error::Message("invalid length 1, expected tuple of 2 elements".to_owned()),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
use serde::bytes::{ByteBuf, Bytes};
|
||||
use serde_test::{assert_tokens, assert_ser_tokens, assert_de_tokens, Token};
|
||||
|
||||
#[test]
|
||||
fn test_bytes() {
|
||||
let empty = Bytes::new(&[]);
|
||||
assert_ser_tokens(&empty, &[Token::Bytes(b"")]);
|
||||
|
||||
let buf = vec![65, 66, 67];
|
||||
let bytes = Bytes::new(&buf);
|
||||
assert_ser_tokens(&bytes, &[Token::Bytes(b"ABC")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_byte_buf() {
|
||||
let empty = ByteBuf::new();
|
||||
assert_tokens(&empty, &[Token::Bytes(b"")]);
|
||||
assert_de_tokens(&empty, &[Token::ByteBuf(Vec::new())]);
|
||||
assert_de_tokens(&empty, &[Token::Str("")]);
|
||||
assert_de_tokens(&empty, &[Token::String(String::new())]);
|
||||
assert_de_tokens(&empty, &[
|
||||
Token::SeqStart(None),
|
||||
Token::SeqEnd,
|
||||
]);
|
||||
assert_de_tokens(&empty, &[
|
||||
Token::SeqStart(Some(0)),
|
||||
Token::SeqEnd,
|
||||
]);
|
||||
|
||||
let buf = ByteBuf::from(vec![65, 66, 67]);
|
||||
assert_tokens(&buf, &[Token::Bytes(b"ABC")]);
|
||||
assert_de_tokens(&buf, &[Token::ByteBuf(vec![65, 66, 67])]);
|
||||
assert_de_tokens(&buf, &[Token::Str("ABC")]);
|
||||
assert_de_tokens(&buf, &[Token::String("ABC".to_owned())]);
|
||||
assert_de_tokens(&buf, &[
|
||||
Token::SeqStart(None),
|
||||
Token::SeqSep,
|
||||
Token::U8(65),
|
||||
Token::SeqSep,
|
||||
Token::U8(66),
|
||||
Token::SeqSep,
|
||||
Token::U8(67),
|
||||
Token::SeqEnd,
|
||||
]);
|
||||
assert_de_tokens(&buf, &[
|
||||
Token::SeqStart(Some(3)),
|
||||
Token::SeqSep,
|
||||
Token::U8(65),
|
||||
Token::SeqSep,
|
||||
Token::U8(66),
|
||||
Token::SeqSep,
|
||||
Token::U8(67),
|
||||
Token::SeqEnd,
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,957 @@
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::net;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
extern crate fnv;
|
||||
use self::fnv::FnvHasher;
|
||||
|
||||
extern crate serde_test;
|
||||
use self::serde_test::{
|
||||
Error,
|
||||
Token,
|
||||
assert_de_tokens,
|
||||
assert_de_tokens_error,
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Debug, Deserialize)]
|
||||
struct UnitStruct;
|
||||
|
||||
#[derive(PartialEq, Debug, Deserialize)]
|
||||
struct TupleStruct(i32, i32, i32);
|
||||
|
||||
#[derive(PartialEq, Debug, Deserialize)]
|
||||
struct Struct {
|
||||
a: i32,
|
||||
b: i32,
|
||||
#[serde(skip_deserializing)]
|
||||
c: i32,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct StructDenyUnknown {
|
||||
a: i32,
|
||||
#[serde(skip_deserializing)]
|
||||
b: i32,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug, Deserialize)]
|
||||
struct StructSkipAll {
|
||||
#[serde(skip_deserializing)]
|
||||
a: i32,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct StructSkipAllDenyUnknown {
|
||||
#[serde(skip_deserializing)]
|
||||
a: i32,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug, Deserialize)]
|
||||
enum Enum {
|
||||
#[allow(dead_code)]
|
||||
#[serde(skip_deserializing)]
|
||||
Skipped,
|
||||
Unit,
|
||||
Simple(i32),
|
||||
Seq(i32, i32, i32),
|
||||
Map { a: i32, b: i32, c: i32 },
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug, Deserialize)]
|
||||
enum EnumSkipAll {
|
||||
#[allow(dead_code)]
|
||||
#[serde(skip_deserializing)]
|
||||
Skipped,
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! declare_test {
|
||||
($name:ident { $($value:expr => $tokens:expr,)+ }) => {
|
||||
#[test]
|
||||
fn $name() {
|
||||
$(
|
||||
// Test ser/de roundtripping
|
||||
assert_de_tokens(&$value, $tokens);
|
||||
|
||||
// Test that the tokens are ignorable
|
||||
assert_de_tokens_ignore($tokens);
|
||||
)+
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! declare_tests {
|
||||
($($name:ident { $($value:expr => $tokens:expr,)+ })+) => {
|
||||
$(
|
||||
declare_test!($name { $($value => $tokens,)+ });
|
||||
)+
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! declare_error_tests {
|
||||
($($name:ident<$target:ty> { $tokens:expr, $expected:expr, })+) => {
|
||||
$(
|
||||
#[test]
|
||||
fn $name() {
|
||||
assert_de_tokens_error::<$target>($tokens, $expected);
|
||||
}
|
||||
)+
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_de_tokens_ignore(ignorable_tokens: &[Token<'static>]) {
|
||||
#[derive(PartialEq, Debug, Deserialize)]
|
||||
struct IgnoreBase {
|
||||
a: i32,
|
||||
}
|
||||
|
||||
let expected = IgnoreBase{a: 1};
|
||||
|
||||
// Embed the tokens to be ignored in the normal token
|
||||
// stream for an IgnoreBase type
|
||||
let concated_tokens : Vec<Token<'static>> = vec![
|
||||
Token::MapStart(Some(2)),
|
||||
Token::MapSep,
|
||||
Token::Str("a"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::MapSep,
|
||||
Token::Str("ignored")
|
||||
]
|
||||
.into_iter()
|
||||
.chain(ignorable_tokens.to_vec().into_iter())
|
||||
.chain(vec![
|
||||
Token::MapEnd,
|
||||
].into_iter())
|
||||
.collect();
|
||||
|
||||
let mut de = serde_test::Deserializer::new(concated_tokens.into_iter());
|
||||
let v: Result<IgnoreBase, Error> = Deserialize::deserialize(&mut de);
|
||||
|
||||
// We run this test on every token stream for convenience, but
|
||||
// some token streams don't make sense embedded as a map value,
|
||||
// so we ignore those. SyntaxError is the real sign of trouble.
|
||||
if let Err(Error::UnexpectedToken(_)) = v {
|
||||
return;
|
||||
}
|
||||
|
||||
assert_eq!(v.as_ref(), Ok(&expected));
|
||||
assert_eq!(de.next_token(), None);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
declare_tests! {
|
||||
test_bool {
|
||||
true => &[Token::Bool(true)],
|
||||
false => &[Token::Bool(false)],
|
||||
}
|
||||
test_isize {
|
||||
0isize => &[Token::I8(0)],
|
||||
0isize => &[Token::I16(0)],
|
||||
0isize => &[Token::I32(0)],
|
||||
0isize => &[Token::I64(0)],
|
||||
0isize => &[Token::U8(0)],
|
||||
0isize => &[Token::U16(0)],
|
||||
0isize => &[Token::U32(0)],
|
||||
0isize => &[Token::U64(0)],
|
||||
0isize => &[Token::F32(0.)],
|
||||
0isize => &[Token::F64(0.)],
|
||||
}
|
||||
test_ints {
|
||||
0i8 => &[Token::I8(0)],
|
||||
0i16 => &[Token::I16(0)],
|
||||
0i32 => &[Token::I32(0)],
|
||||
0i64 => &[Token::I64(0)],
|
||||
}
|
||||
test_uints {
|
||||
0u8 => &[Token::U8(0)],
|
||||
0u16 => &[Token::U16(0)],
|
||||
0u32 => &[Token::U32(0)],
|
||||
0u64 => &[Token::U64(0)],
|
||||
}
|
||||
test_floats {
|
||||
0f32 => &[Token::F32(0.)],
|
||||
0f64 => &[Token::F64(0.)],
|
||||
}
|
||||
test_char {
|
||||
'a' => &[Token::Char('a')],
|
||||
'a' => &[Token::Str("a")],
|
||||
'a' => &[Token::String("a".to_owned())],
|
||||
}
|
||||
test_string {
|
||||
"abc".to_owned() => &[Token::Str("abc")],
|
||||
"abc".to_owned() => &[Token::String("abc".to_owned())],
|
||||
"a".to_owned() => &[Token::Char('a')],
|
||||
}
|
||||
test_option {
|
||||
None::<i32> => &[Token::Unit],
|
||||
None::<i32> => &[Token::Option(false)],
|
||||
Some(1) => &[Token::I32(1)],
|
||||
Some(1) => &[
|
||||
Token::Option(true),
|
||||
Token::I32(1),
|
||||
],
|
||||
}
|
||||
test_result {
|
||||
Ok::<i32, i32>(0) => &[
|
||||
Token::EnumStart("Result"),
|
||||
Token::Str("Ok"),
|
||||
Token::I32(0),
|
||||
],
|
||||
Err::<i32, i32>(1) => &[
|
||||
Token::EnumStart("Result"),
|
||||
Token::Str("Err"),
|
||||
Token::I32(1),
|
||||
],
|
||||
}
|
||||
test_unit {
|
||||
() => &[Token::Unit],
|
||||
() => &[
|
||||
Token::SeqStart(Some(0)),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
() => &[
|
||||
Token::SeqStart(None),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
() => &[
|
||||
Token::TupleStructStart("Anything", 0),
|
||||
Token::TupleStructEnd,
|
||||
],
|
||||
}
|
||||
test_unit_struct {
|
||||
UnitStruct => &[Token::Unit],
|
||||
UnitStruct => &[
|
||||
Token::UnitStruct("UnitStruct"),
|
||||
],
|
||||
UnitStruct => &[
|
||||
Token::SeqStart(Some(0)),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
UnitStruct => &[
|
||||
Token::SeqStart(None),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_unit_string {
|
||||
String::new() => &[Token::Unit],
|
||||
}
|
||||
test_tuple_struct {
|
||||
TupleStruct(1, 2, 3) => &[
|
||||
Token::SeqStart(Some(3)),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
TupleStruct(1, 2, 3) => &[
|
||||
Token::SeqStart(None),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
TupleStruct(1, 2, 3) => &[
|
||||
Token::TupleStructStart("TupleStruct", 3),
|
||||
Token::TupleStructSep,
|
||||
Token::I32(1),
|
||||
|
||||
Token::TupleStructSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::TupleStructSep,
|
||||
Token::I32(3),
|
||||
Token::TupleStructEnd,
|
||||
],
|
||||
TupleStruct(1, 2, 3) => &[
|
||||
Token::TupleStructStart("TupleStruct", 3),
|
||||
Token::TupleStructSep,
|
||||
Token::I32(1),
|
||||
|
||||
Token::TupleStructSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::TupleStructSep,
|
||||
Token::I32(3),
|
||||
Token::TupleStructEnd,
|
||||
],
|
||||
}
|
||||
test_btreeset {
|
||||
BTreeSet::<isize>::new() => &[
|
||||
Token::Unit,
|
||||
],
|
||||
BTreeSet::<isize>::new() => &[
|
||||
Token::SeqStart(Some(0)),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
btreeset![btreeset![], btreeset![1], btreeset![2, 3]] => &[
|
||||
Token::SeqStart(Some(3)),
|
||||
Token::SeqSep,
|
||||
Token::SeqStart(Some(0)),
|
||||
Token::SeqEnd,
|
||||
|
||||
Token::SeqSep,
|
||||
Token::SeqStart(Some(1)),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
Token::SeqEnd,
|
||||
|
||||
Token::SeqSep,
|
||||
Token::SeqStart(Some(2)),
|
||||
Token::SeqSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
Token::SeqEnd,
|
||||
],
|
||||
BTreeSet::<isize>::new() => &[
|
||||
Token::UnitStruct("Anything"),
|
||||
],
|
||||
BTreeSet::<isize>::new() => &[
|
||||
Token::TupleStructStart("Anything", 0),
|
||||
Token::TupleStructEnd,
|
||||
],
|
||||
}
|
||||
test_hashset {
|
||||
HashSet::<isize>::new() => &[
|
||||
Token::Unit,
|
||||
],
|
||||
HashSet::<isize>::new() => &[
|
||||
Token::SeqStart(Some(0)),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
hashset![1, 2, 3] => &[
|
||||
Token::SeqStart(Some(3)),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
HashSet::<isize>::new() => &[
|
||||
Token::UnitStruct("Anything"),
|
||||
],
|
||||
HashSet::<isize>::new() => &[
|
||||
Token::TupleStructStart("Anything", 0),
|
||||
Token::TupleStructEnd,
|
||||
],
|
||||
hashset![FnvHasher @ 1, 2, 3] => &[
|
||||
Token::SeqStart(Some(3)),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_vec {
|
||||
Vec::<isize>::new() => &[
|
||||
Token::Unit,
|
||||
],
|
||||
Vec::<isize>::new() => &[
|
||||
Token::SeqStart(Some(0)),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
vec![vec![], vec![1], vec![2, 3]] => &[
|
||||
Token::SeqStart(Some(3)),
|
||||
Token::SeqSep,
|
||||
Token::SeqStart(Some(0)),
|
||||
Token::SeqEnd,
|
||||
|
||||
Token::SeqSep,
|
||||
Token::SeqStart(Some(1)),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
Token::SeqEnd,
|
||||
|
||||
Token::SeqSep,
|
||||
Token::SeqStart(Some(2)),
|
||||
Token::SeqSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
Token::SeqEnd,
|
||||
],
|
||||
Vec::<isize>::new() => &[
|
||||
Token::UnitStruct("Anything"),
|
||||
],
|
||||
Vec::<isize>::new() => &[
|
||||
Token::TupleStructStart("Anything", 0),
|
||||
Token::TupleStructEnd,
|
||||
],
|
||||
}
|
||||
test_array {
|
||||
[0; 0] => &[
|
||||
Token::Unit,
|
||||
],
|
||||
[0; 0] => &[
|
||||
Token::SeqStart(Some(0)),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
[0; 0] => &[
|
||||
Token::SeqArrayStart(0),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
([0; 0], [1], [2, 3]) => &[
|
||||
Token::SeqStart(Some(3)),
|
||||
Token::SeqSep,
|
||||
Token::SeqStart(Some(0)),
|
||||
Token::SeqEnd,
|
||||
|
||||
Token::SeqSep,
|
||||
Token::SeqStart(Some(1)),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
Token::SeqEnd,
|
||||
|
||||
Token::SeqSep,
|
||||
Token::SeqStart(Some(2)),
|
||||
Token::SeqSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
Token::SeqEnd,
|
||||
],
|
||||
([0; 0], [1], [2, 3]) => &[
|
||||
Token::SeqArrayStart(3),
|
||||
Token::SeqSep,
|
||||
Token::SeqArrayStart(0),
|
||||
Token::SeqEnd,
|
||||
|
||||
Token::SeqSep,
|
||||
Token::SeqArrayStart(1),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
Token::SeqEnd,
|
||||
|
||||
Token::SeqSep,
|
||||
Token::SeqArrayStart(2),
|
||||
Token::SeqSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
Token::SeqEnd,
|
||||
],
|
||||
[0; 0] => &[
|
||||
Token::UnitStruct("Anything"),
|
||||
],
|
||||
[0; 0] => &[
|
||||
Token::TupleStructStart("Anything", 0),
|
||||
Token::TupleStructEnd,
|
||||
],
|
||||
}
|
||||
test_tuple {
|
||||
(1,) => &[
|
||||
Token::SeqStart(Some(1)),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
(1, 2, 3) => &[
|
||||
Token::SeqStart(Some(3)),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
(1,) => &[
|
||||
Token::TupleStart(1),
|
||||
Token::TupleSep,
|
||||
Token::I32(1),
|
||||
Token::TupleEnd,
|
||||
],
|
||||
(1, 2, 3) => &[
|
||||
Token::TupleStart(3),
|
||||
Token::TupleSep,
|
||||
Token::I32(1),
|
||||
|
||||
Token::TupleSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::TupleSep,
|
||||
Token::I32(3),
|
||||
Token::TupleEnd,
|
||||
],
|
||||
}
|
||||
test_btreemap {
|
||||
BTreeMap::<isize, isize>::new() => &[
|
||||
Token::Unit,
|
||||
],
|
||||
BTreeMap::<isize, isize>::new() => &[
|
||||
Token::MapStart(Some(0)),
|
||||
Token::MapEnd,
|
||||
],
|
||||
btreemap![1 => 2] => &[
|
||||
Token::MapStart(Some(1)),
|
||||
Token::MapSep,
|
||||
Token::I32(1),
|
||||
Token::I32(2),
|
||||
Token::MapEnd,
|
||||
],
|
||||
btreemap![1 => 2, 3 => 4] => &[
|
||||
Token::MapStart(Some(2)),
|
||||
Token::MapSep,
|
||||
Token::I32(1),
|
||||
Token::I32(2),
|
||||
|
||||
Token::MapSep,
|
||||
Token::I32(3),
|
||||
Token::I32(4),
|
||||
Token::MapEnd,
|
||||
],
|
||||
btreemap![1 => btreemap![], 2 => btreemap![3 => 4, 5 => 6]] => &[
|
||||
Token::MapStart(Some(2)),
|
||||
Token::MapSep,
|
||||
Token::I32(1),
|
||||
Token::MapStart(Some(0)),
|
||||
Token::MapEnd,
|
||||
|
||||
Token::MapSep,
|
||||
Token::I32(2),
|
||||
Token::MapStart(Some(2)),
|
||||
Token::MapSep,
|
||||
Token::I32(3),
|
||||
Token::I32(4),
|
||||
|
||||
Token::MapSep,
|
||||
Token::I32(5),
|
||||
Token::I32(6),
|
||||
Token::MapEnd,
|
||||
Token::MapEnd,
|
||||
],
|
||||
BTreeMap::<isize, isize>::new() => &[
|
||||
Token::UnitStruct("Anything"),
|
||||
],
|
||||
BTreeMap::<isize, isize>::new() => &[
|
||||
Token::StructStart("Anything", 0),
|
||||
Token::StructEnd,
|
||||
],
|
||||
}
|
||||
test_hashmap {
|
||||
HashMap::<isize, isize>::new() => &[
|
||||
Token::Unit,
|
||||
],
|
||||
HashMap::<isize, isize>::new() => &[
|
||||
Token::MapStart(Some(0)),
|
||||
Token::MapEnd,
|
||||
],
|
||||
hashmap![1 => 2] => &[
|
||||
Token::MapStart(Some(1)),
|
||||
Token::MapSep,
|
||||
Token::I32(1),
|
||||
Token::I32(2),
|
||||
Token::MapEnd,
|
||||
],
|
||||
hashmap![1 => 2, 3 => 4] => &[
|
||||
Token::MapStart(Some(2)),
|
||||
Token::MapSep,
|
||||
Token::I32(1),
|
||||
Token::I32(2),
|
||||
|
||||
Token::MapSep,
|
||||
Token::I32(3),
|
||||
Token::I32(4),
|
||||
Token::MapEnd,
|
||||
],
|
||||
hashmap![1 => hashmap![], 2 => hashmap![3 => 4, 5 => 6]] => &[
|
||||
Token::MapStart(Some(2)),
|
||||
Token::MapSep,
|
||||
Token::I32(1),
|
||||
Token::MapStart(Some(0)),
|
||||
Token::MapEnd,
|
||||
|
||||
Token::MapSep,
|
||||
Token::I32(2),
|
||||
Token::MapStart(Some(2)),
|
||||
Token::MapSep,
|
||||
Token::I32(3),
|
||||
Token::I32(4),
|
||||
|
||||
Token::MapSep,
|
||||
Token::I32(5),
|
||||
Token::I32(6),
|
||||
Token::MapEnd,
|
||||
Token::MapEnd,
|
||||
],
|
||||
HashMap::<isize, isize>::new() => &[
|
||||
Token::UnitStruct("Anything"),
|
||||
],
|
||||
HashMap::<isize, isize>::new() => &[
|
||||
Token::StructStart("Anything", 0),
|
||||
Token::StructEnd,
|
||||
],
|
||||
hashmap![FnvHasher @ 1 => 2, 3 => 4] => &[
|
||||
Token::MapStart(Some(2)),
|
||||
Token::MapSep,
|
||||
Token::I32(1),
|
||||
Token::I32(2),
|
||||
|
||||
Token::MapSep,
|
||||
Token::I32(3),
|
||||
Token::I32(4),
|
||||
Token::MapEnd,
|
||||
],
|
||||
}
|
||||
test_struct {
|
||||
Struct { a: 1, b: 2, c: 0 } => &[
|
||||
Token::MapStart(Some(3)),
|
||||
Token::MapSep,
|
||||
Token::Str("a"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::MapSep,
|
||||
Token::Str("b"),
|
||||
Token::I32(2),
|
||||
Token::MapEnd,
|
||||
],
|
||||
Struct { a: 1, b: 2, c: 0 } => &[
|
||||
Token::StructStart("Struct", 3),
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("b"),
|
||||
Token::I32(2),
|
||||
Token::StructEnd,
|
||||
],
|
||||
Struct { a: 1, b: 2, c: 0 } => &[
|
||||
Token::SeqStart(Some(3)),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(2),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_struct_with_skip {
|
||||
Struct { a: 1, b: 2, c: 0 } => &[
|
||||
Token::MapStart(Some(3)),
|
||||
Token::MapSep,
|
||||
Token::Str("a"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::MapSep,
|
||||
Token::Str("b"),
|
||||
Token::I32(2),
|
||||
|
||||
Token::MapSep,
|
||||
Token::Str("c"),
|
||||
Token::I32(3),
|
||||
|
||||
Token::MapSep,
|
||||
Token::Str("d"),
|
||||
Token::I32(4),
|
||||
Token::MapEnd,
|
||||
],
|
||||
Struct { a: 1, b: 2, c: 0 } => &[
|
||||
Token::StructStart("Struct", 3),
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("b"),
|
||||
Token::I32(2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("c"),
|
||||
Token::I32(3),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("d"),
|
||||
Token::I32(4),
|
||||
Token::StructEnd,
|
||||
],
|
||||
}
|
||||
test_struct_skip_all {
|
||||
StructSkipAll { a: 0 } => &[
|
||||
Token::StructStart("StructSkipAll", 0),
|
||||
Token::StructEnd,
|
||||
],
|
||||
StructSkipAll { a: 0 } => &[
|
||||
Token::StructStart("StructSkipAll", 1),
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("b"),
|
||||
Token::I32(2),
|
||||
Token::StructEnd,
|
||||
],
|
||||
}
|
||||
test_struct_skip_all_deny_unknown {
|
||||
StructSkipAllDenyUnknown { a: 0 } => &[
|
||||
Token::StructStart("StructSkipAllDenyUnknown", 0),
|
||||
Token::StructEnd,
|
||||
],
|
||||
}
|
||||
test_enum_unit {
|
||||
Enum::Unit => &[
|
||||
Token::EnumUnit("Enum", "Unit"),
|
||||
],
|
||||
}
|
||||
test_enum_simple {
|
||||
Enum::Simple(1) => &[
|
||||
Token::EnumNewType("Enum", "Simple"),
|
||||
Token::I32(1),
|
||||
],
|
||||
}
|
||||
test_enum_seq {
|
||||
Enum::Seq(1, 2, 3) => &[
|
||||
Token::EnumSeqStart("Enum", "Seq", 3),
|
||||
Token::EnumSeqSep,
|
||||
Token::I32(1),
|
||||
|
||||
Token::EnumSeqSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::EnumSeqSep,
|
||||
Token::I32(3),
|
||||
Token::EnumSeqEnd,
|
||||
],
|
||||
}
|
||||
test_enum_map {
|
||||
Enum::Map { a: 1, b: 2, c: 3 } => &[
|
||||
Token::EnumMapStart("Enum", "Map", 3),
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("b"),
|
||||
Token::I32(2),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("c"),
|
||||
Token::I32(3),
|
||||
Token::EnumMapEnd,
|
||||
],
|
||||
}
|
||||
test_enum_unit_usize {
|
||||
Enum::Unit => &[
|
||||
Token::EnumStart("Enum"),
|
||||
Token::U32(0),
|
||||
Token::Unit,
|
||||
],
|
||||
}
|
||||
test_enum_unit_bytes {
|
||||
Enum::Unit => &[
|
||||
Token::EnumStart("Enum"),
|
||||
Token::Bytes(b"Unit"),
|
||||
Token::Unit,
|
||||
],
|
||||
}
|
||||
test_box {
|
||||
Box::new(0i32) => &[Token::I32(0)],
|
||||
}
|
||||
test_boxed_slice {
|
||||
Box::new([0, 1, 2]) => &[
|
||||
Token::SeqStart(Some(3)),
|
||||
Token::SeqSep,
|
||||
Token::I32(0),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
Token::SeqSep,
|
||||
Token::I32(2),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_duration {
|
||||
Duration::new(1, 2) => &[
|
||||
Token::StructStart("Duration", 2),
|
||||
Token::StructSep,
|
||||
Token::Str("secs"),
|
||||
Token::U64(1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("nanos"),
|
||||
Token::U32(2),
|
||||
Token::StructEnd,
|
||||
],
|
||||
Duration::new(1, 2) => &[
|
||||
Token::SeqStart(Some(2)),
|
||||
Token::SeqSep,
|
||||
Token::I64(1),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I64(2),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_net_ipv4addr {
|
||||
"1.2.3.4".parse::<net::Ipv4Addr>().unwrap() => &[Token::Str("1.2.3.4")],
|
||||
}
|
||||
test_net_ipv6addr {
|
||||
"::1".parse::<net::Ipv6Addr>().unwrap() => &[Token::Str("::1")],
|
||||
}
|
||||
test_net_socketaddr {
|
||||
"1.2.3.4:1234".parse::<net::SocketAddr>().unwrap() => &[Token::Str("1.2.3.4:1234")],
|
||||
"1.2.3.4:1234".parse::<net::SocketAddrV4>().unwrap() => &[Token::Str("1.2.3.4:1234")],
|
||||
"[::1]:1234".parse::<net::SocketAddrV6>().unwrap() => &[Token::Str("[::1]:1234")],
|
||||
}
|
||||
test_path_buf {
|
||||
PathBuf::from("/usr/local/lib") => &[
|
||||
Token::String("/usr/local/lib".to_owned()),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[test]
|
||||
fn test_net_ipaddr() {
|
||||
assert_de_tokens(
|
||||
"1.2.3.4".parse::<net::IpAddr>().unwrap(),
|
||||
&[Token::Str("1.2.3.4")],
|
||||
);
|
||||
}
|
||||
|
||||
declare_error_tests! {
|
||||
test_unknown_field<StructDenyUnknown> {
|
||||
&[
|
||||
Token::StructStart("StructDenyUnknown", 2),
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
Token::I32(0),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("d"),
|
||||
],
|
||||
Error::Message("unknown field `d`, expected `a`".to_owned()),
|
||||
}
|
||||
test_skipped_field_is_unknown<StructDenyUnknown> {
|
||||
&[
|
||||
Token::StructStart("StructDenyUnknown", 2),
|
||||
Token::StructSep,
|
||||
Token::Str("b"),
|
||||
],
|
||||
Error::Message("unknown field `b`, expected `a`".to_owned()),
|
||||
}
|
||||
test_skip_all_deny_unknown<StructSkipAllDenyUnknown> {
|
||||
&[
|
||||
Token::StructStart("StructSkipAllDenyUnknown", 1),
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
],
|
||||
Error::Message("unknown field `a`, there are no fields".to_owned()),
|
||||
}
|
||||
test_unknown_variant<Enum> {
|
||||
&[
|
||||
Token::EnumUnit("Enum", "Foo"),
|
||||
],
|
||||
Error::Message("unknown variant `Foo`, expected one of `Unit`, `Simple`, `Seq`, `Map`".to_owned()),
|
||||
}
|
||||
test_enum_skipped_variant<Enum> {
|
||||
&[
|
||||
Token::EnumUnit("Enum", "Skipped"),
|
||||
],
|
||||
Error::Message("unknown variant `Skipped`, expected one of `Unit`, `Simple`, `Seq`, `Map`".to_owned()),
|
||||
}
|
||||
test_enum_skip_all<EnumSkipAll> {
|
||||
&[
|
||||
Token::EnumUnit("EnumSkipAll", "Skipped"),
|
||||
],
|
||||
Error::Message("unknown variant `Skipped`, there are no variants".to_owned()),
|
||||
}
|
||||
test_struct_seq_too_long<Struct> {
|
||||
&[
|
||||
Token::SeqStart(Some(4)),
|
||||
Token::SeqSep, Token::I32(1),
|
||||
Token::SeqSep, Token::I32(2),
|
||||
Token::SeqSep, Token::I32(3),
|
||||
],
|
||||
Error::UnexpectedToken(Token::SeqSep),
|
||||
}
|
||||
test_duplicate_field_struct<Struct> {
|
||||
&[
|
||||
Token::MapStart(Some(3)),
|
||||
Token::MapSep,
|
||||
Token::Str("a"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::MapSep,
|
||||
Token::Str("a"),
|
||||
],
|
||||
Error::Message("duplicate field `a`".to_owned()),
|
||||
}
|
||||
test_duplicate_field_enum<Enum> {
|
||||
&[
|
||||
Token::EnumMapStart("Enum", "Map", 3),
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a"),
|
||||
],
|
||||
Error::Message("duplicate field `a`".to_owned()),
|
||||
}
|
||||
test_enum_out_of_range<Enum> {
|
||||
&[
|
||||
Token::EnumStart("Enum"),
|
||||
Token::U32(4),
|
||||
Token::Unit,
|
||||
],
|
||||
Error::Message("invalid value: integer `4`, expected variant index 0 <= i < 4".into()),
|
||||
}
|
||||
test_short_tuple<(u8, u8, u8)> {
|
||||
&[
|
||||
Token::TupleStart(1),
|
||||
Token::TupleSep,
|
||||
Token::U8(1),
|
||||
Token::TupleEnd,
|
||||
],
|
||||
Error::Message("invalid length 1, expected a tuple of size 3".into()),
|
||||
}
|
||||
test_short_array<[u8; 3]> {
|
||||
&[
|
||||
Token::SeqStart(Some(1)),
|
||||
Token::SeqSep,
|
||||
Token::U8(1),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
Error::Message("invalid length 1, expected an array of length 3".into()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
// These just test that serde_codegen is able to produce code that compiles
|
||||
// successfully when there are a variety of generics and non-(de)serializable
|
||||
// types involved.
|
||||
|
||||
extern crate serde;
|
||||
use self::serde::ser::{Serialize, Serializer};
|
||||
use self::serde::de::{Deserialize, Deserializer};
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::marker::PhantomData;
|
||||
use std::result::Result as StdResult;
|
||||
|
||||
// Try to trip up the generated code if it fails to use fully qualified paths.
|
||||
#[allow(dead_code)]
|
||||
struct Result;
|
||||
#[allow(dead_code)]
|
||||
struct Ok;
|
||||
#[allow(dead_code)]
|
||||
struct Err;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[test]
|
||||
fn test_gen() {
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct With<T> {
|
||||
t: T,
|
||||
#[serde(serialize_with="ser_x", deserialize_with="de_x")]
|
||||
x: X,
|
||||
}
|
||||
assert::<With<i32>>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct WithRef<'a, T: 'a> {
|
||||
#[serde(skip_deserializing)]
|
||||
t: Option<&'a T>,
|
||||
#[serde(serialize_with="ser_x", deserialize_with="de_x")]
|
||||
x: X,
|
||||
}
|
||||
assert::<WithRef<i32>>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct PhantomX {
|
||||
x: PhantomData<X>,
|
||||
}
|
||||
assert::<PhantomX>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct PhantomT<T> {
|
||||
t: PhantomData<T>,
|
||||
}
|
||||
assert::<PhantomT<X>>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Bounds<T: Serialize + Deserialize> {
|
||||
t: T,
|
||||
option: Option<T>,
|
||||
boxed: Box<T>,
|
||||
option_boxed: Option<Box<T>>,
|
||||
}
|
||||
assert::<Bounds<i32>>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct NoBounds<T> {
|
||||
t: T,
|
||||
option: Option<T>,
|
||||
boxed: Box<T>,
|
||||
option_boxed: Option<Box<T>>,
|
||||
}
|
||||
assert::<NoBounds<i32>>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum EnumWith<T> {
|
||||
Unit,
|
||||
Newtype(
|
||||
#[serde(serialize_with="ser_x", deserialize_with="de_x")]
|
||||
X),
|
||||
Tuple(
|
||||
T,
|
||||
#[serde(serialize_with="ser_x", deserialize_with="de_x")]
|
||||
X),
|
||||
Struct {
|
||||
t: T,
|
||||
#[serde(serialize_with="ser_x", deserialize_with="de_x")]
|
||||
x: X },
|
||||
}
|
||||
assert::<EnumWith<i32>>();
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct MultipleRef<'a, 'b, 'c, T> where T: 'c, 'c: 'b, 'b: 'a {
|
||||
t: T,
|
||||
rrrt: &'a &'b &'c T,
|
||||
}
|
||||
assert_ser::<MultipleRef<i32>>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Newtype(
|
||||
#[serde(serialize_with="ser_x", deserialize_with="de_x")]
|
||||
X
|
||||
);
|
||||
assert::<Newtype>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Tuple<T>(
|
||||
T,
|
||||
#[serde(serialize_with="ser_x", deserialize_with="de_x")]
|
||||
X,
|
||||
);
|
||||
assert::<Tuple<i32>>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum TreeNode<D> {
|
||||
Split {
|
||||
left: Box<TreeNode<D>>,
|
||||
right: Box<TreeNode<D>>,
|
||||
},
|
||||
Leaf {
|
||||
data: D,
|
||||
},
|
||||
}
|
||||
assert::<TreeNode<i32>>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct ListNode<D> {
|
||||
data: D,
|
||||
next: Box<ListNode<D>>,
|
||||
}
|
||||
assert::<ListNode<i32>>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct RecursiveA {
|
||||
b: Box<RecursiveB>,
|
||||
}
|
||||
assert::<RecursiveA>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum RecursiveB {
|
||||
A(RecursiveA),
|
||||
}
|
||||
assert::<RecursiveB>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct RecursiveGenericA<T> {
|
||||
t: T,
|
||||
b: Box<RecursiveGenericB<T>>,
|
||||
}
|
||||
assert::<RecursiveGenericA<i32>>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum RecursiveGenericB<T> {
|
||||
T(T),
|
||||
A(RecursiveGenericA<T>),
|
||||
}
|
||||
assert::<RecursiveGenericB<i32>>();
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct OptionStatic<'a> {
|
||||
a: Option<&'a str>,
|
||||
b: Option<&'static str>,
|
||||
}
|
||||
assert_ser::<OptionStatic>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(bound="D: SerializeWith + DeserializeWith")]
|
||||
struct WithTraits1<D, E> {
|
||||
#[serde(serialize_with="SerializeWith::serialize_with",
|
||||
deserialize_with="DeserializeWith::deserialize_with")]
|
||||
d: D,
|
||||
#[serde(serialize_with="SerializeWith::serialize_with",
|
||||
deserialize_with="DeserializeWith::deserialize_with",
|
||||
bound="E: SerializeWith + DeserializeWith")]
|
||||
e: E,
|
||||
}
|
||||
assert::<WithTraits1<X, X>>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(bound(serialize="D: SerializeWith",
|
||||
deserialize="D: DeserializeWith"))]
|
||||
struct WithTraits2<D, E> {
|
||||
#[serde(serialize_with="SerializeWith::serialize_with",
|
||||
deserialize_with="DeserializeWith::deserialize_with")]
|
||||
d: D,
|
||||
#[serde(serialize_with="SerializeWith::serialize_with",
|
||||
bound(serialize="E: SerializeWith"))]
|
||||
#[serde(deserialize_with="DeserializeWith::deserialize_with",
|
||||
bound(deserialize="E: DeserializeWith"))]
|
||||
e: E,
|
||||
}
|
||||
assert::<WithTraits2<X, X>>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct CowStr<'a>(Cow<'a, str>);
|
||||
assert::<CowStr>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(bound(deserialize = "T::Owned: Deserialize"))]
|
||||
struct CowT<'a, T: ?Sized + 'a + ToOwned>(Cow<'a, T>);
|
||||
assert::<CowT<str>>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct EmptyStruct {}
|
||||
assert::<EmptyStruct>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum EmptyEnumVariant {
|
||||
EmptyStruct {},
|
||||
}
|
||||
assert::<EmptyEnumVariant>();
|
||||
|
||||
#[cfg(feature = "unstable-testing")]
|
||||
#[cfg_attr(feature = "unstable-testing", derive(Serialize, Deserialize))]
|
||||
struct NonAsciiIdents {
|
||||
σ: f64
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct EmptyBraced {}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct EmptyBracedDenyUnknown {}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct BracedSkipAll {
|
||||
#[serde(skip_deserializing)]
|
||||
f: u8,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct BracedSkipAllDenyUnknown {
|
||||
#[serde(skip_deserializing)]
|
||||
f: u8,
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable-testing")]
|
||||
#[cfg_attr(feature = "unstable-testing", derive(Serialize, Deserialize))]
|
||||
struct EmptyTuple();
|
||||
|
||||
#[cfg(feature = "unstable-testing")]
|
||||
#[cfg_attr(feature = "unstable-testing", derive(Serialize, Deserialize))]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct EmptyTupleDenyUnknown();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TupleSkipAll(#[serde(skip_deserializing)] u8);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct TupleSkipAllDenyUnknown(#[serde(skip_deserializing)] u8);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum EmptyEnum {}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
enum EmptyEnumDenyUnknown {}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum EnumSkipAll {
|
||||
#[serde(skip_deserializing)]
|
||||
#[allow(dead_code)]
|
||||
Variant,
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable-testing")]
|
||||
#[cfg_attr(feature = "unstable-testing", derive(Serialize, Deserialize))]
|
||||
enum EmptyVariants {
|
||||
Braced {},
|
||||
Tuple(),
|
||||
BracedSkip {
|
||||
#[serde(skip_deserializing)]
|
||||
f: u8,
|
||||
},
|
||||
TupleSkip(#[serde(skip_deserializing)] u8),
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable-testing")]
|
||||
#[cfg_attr(feature = "unstable-testing", derive(Serialize, Deserialize))]
|
||||
#[serde(deny_unknown_fields)]
|
||||
enum EmptyVariantsDenyUnknown {
|
||||
Braced {},
|
||||
Tuple(),
|
||||
BracedSkip {
|
||||
#[serde(skip_deserializing)]
|
||||
f: u8,
|
||||
},
|
||||
TupleSkip(#[serde(skip_deserializing)] u8),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct UnitDenyUnknown;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
fn assert<T: Serialize + Deserialize>() {}
|
||||
fn assert_ser<T: Serialize>() {}
|
||||
|
||||
trait SerializeWith {
|
||||
fn serialize_with<S: Serializer>(_: &Self, _: S) -> StdResult<S::Ok, S::Error>;
|
||||
}
|
||||
|
||||
trait DeserializeWith: Sized {
|
||||
fn deserialize_with<D: Deserializer>(_: D) -> StdResult<Self, D::Error>;
|
||||
}
|
||||
|
||||
// Implements neither Serialize nor Deserialize
|
||||
struct X;
|
||||
|
||||
fn ser_x<S: Serializer>(_: &X, _: S) -> StdResult<S::Ok, S::Error> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn de_x<D: Deserializer>(_: D) -> StdResult<X, D::Error> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
impl SerializeWith for X {
|
||||
fn serialize_with<S: Serializer>(_: &Self, _: S) -> StdResult<S::Ok, S::Error> {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
impl DeserializeWith for X {
|
||||
fn deserialize_with<D: Deserializer>(_: D) -> StdResult<Self, D::Error> {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,883 @@
|
||||
extern crate serde_test;
|
||||
use self::serde_test::{
|
||||
Error,
|
||||
Token,
|
||||
assert_tokens,
|
||||
assert_ser_tokens,
|
||||
assert_de_tokens,
|
||||
assert_de_tokens_error,
|
||||
};
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
// That tests that the derived Serialize implementation doesn't trigger
|
||||
// any warning about `serializer` not being used, in case of empty enums.
|
||||
#[derive(Serialize)]
|
||||
#[allow(dead_code)]
|
||||
#[deny(unused_variables)]
|
||||
enum Void {}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct NamedUnit;
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize)]
|
||||
struct SerNamedTuple<'a, 'b, A: 'a, B: 'b, C>(&'a A, &'b mut B, C);
|
||||
|
||||
#[derive(Debug, PartialEq, Deserialize)]
|
||||
struct DeNamedTuple<A, B, C>(A, B, C);
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize)]
|
||||
struct SerNamedMap<'a, 'b, A: 'a, B: 'b, C> {
|
||||
a: &'a A,
|
||||
b: &'b mut B,
|
||||
c: C,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Deserialize)]
|
||||
struct DeNamedMap<A, B, C> {
|
||||
a: A,
|
||||
b: B,
|
||||
c: C,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize)]
|
||||
enum SerEnum<'a, B: 'a, C: 'a, D> where D: 'a {
|
||||
Unit,
|
||||
Seq(
|
||||
i8,
|
||||
B,
|
||||
&'a C,
|
||||
&'a mut D,
|
||||
),
|
||||
Map {
|
||||
a: i8,
|
||||
b: B,
|
||||
c: &'a C,
|
||||
d: &'a mut D,
|
||||
},
|
||||
|
||||
// Make sure we can support more than one variant.
|
||||
_Unit2,
|
||||
_Seq2(
|
||||
i8,
|
||||
B,
|
||||
&'a C,
|
||||
&'a mut D,
|
||||
),
|
||||
_Map2 {
|
||||
a: i8,
|
||||
b: B,
|
||||
c: &'a C,
|
||||
d: &'a mut D,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
enum DeEnum<B, C, D> {
|
||||
Unit,
|
||||
Seq(
|
||||
i8,
|
||||
B,
|
||||
C,
|
||||
D,
|
||||
),
|
||||
Map {
|
||||
a: i8,
|
||||
b: B,
|
||||
c: C,
|
||||
d: D,
|
||||
},
|
||||
|
||||
// Make sure we can support more than one variant.
|
||||
_Unit2,
|
||||
_Seq2(
|
||||
i8,
|
||||
B,
|
||||
C,
|
||||
D,
|
||||
),
|
||||
_Map2 {
|
||||
a: i8,
|
||||
b: B,
|
||||
c: C,
|
||||
d: D,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
enum Lifetimes<'a> {
|
||||
LifetimeSeq(&'a i32),
|
||||
NoLifetimeSeq(i32),
|
||||
LifetimeMap { a: &'a i32 },
|
||||
NoLifetimeMap { a: i32 },
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct GenericStruct<T> {
|
||||
x: T,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct GenericNewTypeStruct<T>(T);
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct GenericTupleStruct<T, U>(T, U);
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum GenericEnum<T, U> {
|
||||
Unit,
|
||||
NewType(T),
|
||||
Seq(T, U),
|
||||
Map { x: T, y: U },
|
||||
}
|
||||
|
||||
trait AssociatedType {
|
||||
type X;
|
||||
}
|
||||
|
||||
impl AssociatedType for i32 {
|
||||
type X = i32;
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct DefaultTyParam<T: AssociatedType<X=i32> = i32> {
|
||||
phantom: PhantomData<T>
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_named_unit() {
|
||||
assert_tokens(
|
||||
&NamedUnit,
|
||||
&[Token::UnitStruct("NamedUnit")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ser_named_tuple() {
|
||||
let a = 5;
|
||||
let mut b = 6;
|
||||
let c = 7;
|
||||
assert_ser_tokens(
|
||||
&SerNamedTuple(&a, &mut b, c),
|
||||
&[
|
||||
Token::TupleStructStart("SerNamedTuple", 3),
|
||||
Token::TupleStructSep,
|
||||
Token::I32(5),
|
||||
|
||||
Token::TupleStructSep,
|
||||
Token::I32(6),
|
||||
|
||||
Token::TupleStructSep,
|
||||
Token::I32(7),
|
||||
|
||||
Token::TupleStructEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_de_named_tuple() {
|
||||
assert_de_tokens(
|
||||
&DeNamedTuple(5, 6, 7),
|
||||
&[
|
||||
Token::SeqStart(Some(3)),
|
||||
Token::SeqSep,
|
||||
Token::I32(5),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(6),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(7),
|
||||
|
||||
Token::SeqEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_de_tokens(
|
||||
&DeNamedTuple(5, 6, 7),
|
||||
&[
|
||||
Token::TupleStructStart("DeNamedTuple", 3),
|
||||
Token::TupleStructSep,
|
||||
Token::I32(5),
|
||||
|
||||
Token::TupleStructSep,
|
||||
Token::I32(6),
|
||||
|
||||
Token::TupleStructSep,
|
||||
Token::I32(7),
|
||||
|
||||
Token::TupleStructEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ser_named_map() {
|
||||
let a = 5;
|
||||
let mut b = 6;
|
||||
let c = 7;
|
||||
|
||||
assert_ser_tokens(
|
||||
&SerNamedMap {
|
||||
a: &a,
|
||||
b: &mut b,
|
||||
c: c,
|
||||
},
|
||||
&[
|
||||
Token::StructStart("SerNamedMap", 3),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
Token::I32(5),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("b"),
|
||||
Token::I32(6),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("c"),
|
||||
Token::I32(7),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_de_named_map() {
|
||||
assert_de_tokens(
|
||||
&DeNamedMap {
|
||||
a: 5,
|
||||
b: 6,
|
||||
c: 7,
|
||||
},
|
||||
&[
|
||||
Token::StructStart("DeNamedMap", 3),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
Token::I32(5),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("b"),
|
||||
Token::I32(6),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("c"),
|
||||
Token::I32(7),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ser_enum_unit() {
|
||||
assert_ser_tokens(
|
||||
&SerEnum::Unit::<u32, u32, u32>,
|
||||
&[
|
||||
Token::EnumUnit("SerEnum", "Unit"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ser_enum_seq() {
|
||||
let a = 1;
|
||||
let b = 2;
|
||||
let c = 3;
|
||||
let mut d = 4;
|
||||
|
||||
assert_ser_tokens(
|
||||
&SerEnum::Seq(
|
||||
a,
|
||||
b,
|
||||
&c,
|
||||
&mut d,
|
||||
),
|
||||
&[
|
||||
Token::EnumSeqStart("SerEnum", "Seq", 4),
|
||||
|
||||
Token::EnumSeqSep,
|
||||
Token::I8(1),
|
||||
|
||||
Token::EnumSeqSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::EnumSeqSep,
|
||||
Token::I32(3),
|
||||
|
||||
Token::EnumSeqSep,
|
||||
Token::I32(4),
|
||||
|
||||
Token::EnumSeqEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ser_enum_map() {
|
||||
let a = 1;
|
||||
let b = 2;
|
||||
let c = 3;
|
||||
let mut d = 4;
|
||||
|
||||
assert_ser_tokens(
|
||||
&SerEnum::Map {
|
||||
a: a,
|
||||
b: b,
|
||||
c: &c,
|
||||
d: &mut d,
|
||||
},
|
||||
&[
|
||||
Token::EnumMapStart("SerEnum", "Map", 4),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a"),
|
||||
Token::I8(1),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("b"),
|
||||
Token::I32(2),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("c"),
|
||||
Token::I32(3),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("d"),
|
||||
Token::I32(4),
|
||||
|
||||
Token::EnumMapEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_de_enum_unit() {
|
||||
assert_tokens(
|
||||
&DeEnum::Unit::<u32, u32, u32>,
|
||||
&[
|
||||
Token::EnumUnit("DeEnum", "Unit"),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_de_enum_seq() {
|
||||
let a = 1;
|
||||
let b = 2;
|
||||
let c = 3;
|
||||
let d = 4;
|
||||
|
||||
assert_tokens(
|
||||
&DeEnum::Seq(
|
||||
a,
|
||||
b,
|
||||
c,
|
||||
d,
|
||||
),
|
||||
&[
|
||||
Token::EnumSeqStart("DeEnum", "Seq", 4),
|
||||
|
||||
Token::EnumSeqSep,
|
||||
Token::I8(1),
|
||||
|
||||
Token::EnumSeqSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::EnumSeqSep,
|
||||
Token::I32(3),
|
||||
|
||||
Token::EnumSeqSep,
|
||||
Token::I32(4),
|
||||
|
||||
Token::EnumSeqEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_de_enum_map() {
|
||||
let a = 1;
|
||||
let b = 2;
|
||||
let c = 3;
|
||||
let d = 4;
|
||||
|
||||
assert_tokens(
|
||||
&DeEnum::Map {
|
||||
a: a,
|
||||
b: b,
|
||||
c: c,
|
||||
d: d,
|
||||
},
|
||||
&[
|
||||
Token::EnumMapStart("DeEnum", "Map", 4),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a"),
|
||||
Token::I8(1),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("b"),
|
||||
Token::I32(2),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("c"),
|
||||
Token::I32(3),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("d"),
|
||||
Token::I32(4),
|
||||
|
||||
Token::EnumMapEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lifetimes() {
|
||||
let value = 5;
|
||||
|
||||
assert_ser_tokens(
|
||||
&Lifetimes::LifetimeSeq(&value),
|
||||
&[
|
||||
Token::EnumNewType("Lifetimes", "LifetimeSeq"),
|
||||
Token::I32(5),
|
||||
]
|
||||
);
|
||||
|
||||
assert_ser_tokens(
|
||||
&Lifetimes::NoLifetimeSeq(5),
|
||||
&[
|
||||
Token::EnumNewType("Lifetimes", "NoLifetimeSeq"),
|
||||
Token::I32(5),
|
||||
]
|
||||
);
|
||||
|
||||
assert_ser_tokens(
|
||||
&Lifetimes::LifetimeMap { a: &value },
|
||||
&[
|
||||
Token::EnumMapStart("Lifetimes", "LifetimeMap", 1),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a"),
|
||||
Token::I32(5),
|
||||
|
||||
Token::EnumMapEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_ser_tokens(
|
||||
&Lifetimes::NoLifetimeMap { a: 5 },
|
||||
&[
|
||||
Token::EnumMapStart("Lifetimes", "NoLifetimeMap", 1),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a"),
|
||||
Token::I32(5),
|
||||
|
||||
Token::EnumMapEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generic_struct() {
|
||||
assert_tokens(
|
||||
&GenericStruct { x: 5u32 },
|
||||
&[
|
||||
Token::StructStart("GenericStruct", 1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("x"),
|
||||
Token::U32(5),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generic_newtype_struct() {
|
||||
assert_tokens(
|
||||
&GenericNewTypeStruct(5u32),
|
||||
&[
|
||||
Token::StructNewType("GenericNewTypeStruct"),
|
||||
Token::U32(5),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generic_tuple_struct() {
|
||||
assert_tokens(
|
||||
&GenericTupleStruct(5u32, 6u32),
|
||||
&[
|
||||
Token::TupleStructStart("GenericTupleStruct", 2),
|
||||
|
||||
Token::TupleStructSep,
|
||||
Token::U32(5),
|
||||
|
||||
Token::TupleStructSep,
|
||||
Token::U32(6),
|
||||
|
||||
Token::TupleStructEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generic_enum_unit() {
|
||||
assert_tokens(
|
||||
&GenericEnum::Unit::<u32, u32>,
|
||||
&[
|
||||
Token::EnumUnit("GenericEnum", "Unit"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generic_enum_newtype() {
|
||||
assert_tokens(
|
||||
&GenericEnum::NewType::<u32, u32>(5),
|
||||
&[
|
||||
Token::EnumNewType("GenericEnum", "NewType"),
|
||||
Token::U32(5),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generic_enum_seq() {
|
||||
assert_tokens(
|
||||
&GenericEnum::Seq::<u32, u32>(5, 6),
|
||||
&[
|
||||
Token::EnumSeqStart("GenericEnum", "Seq", 2),
|
||||
|
||||
Token::EnumSeqSep,
|
||||
Token::U32(5),
|
||||
|
||||
Token::EnumSeqSep,
|
||||
Token::U32(6),
|
||||
|
||||
Token::EnumSeqEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generic_enum_map() {
|
||||
assert_tokens(
|
||||
&GenericEnum::Map::<u32, u32> { x: 5, y: 6 },
|
||||
&[
|
||||
Token::EnumMapStart("GenericEnum", "Map", 2),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("x"),
|
||||
Token::U32(5),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("y"),
|
||||
Token::U32(6),
|
||||
|
||||
Token::EnumMapEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_ty_param() {
|
||||
assert_tokens(
|
||||
&DefaultTyParam::<i32> { phantom: PhantomData },
|
||||
&[
|
||||
Token::StructStart("DefaultTyParam", 1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("phantom"),
|
||||
Token::UnitStruct("PhantomData"),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_enum_state_field() {
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
enum SomeEnum {
|
||||
Key { key: char, state: bool },
|
||||
}
|
||||
|
||||
assert_tokens(
|
||||
&SomeEnum::Key { key: 'a', state: true },
|
||||
&[
|
||||
Token::EnumMapStart("SomeEnum", "Key", 2),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("key"),
|
||||
Token::Char('a'),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("state"),
|
||||
Token::Bool(true),
|
||||
|
||||
Token::EnumMapEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_untagged_enum() {
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Untagged {
|
||||
A {
|
||||
a: u8,
|
||||
},
|
||||
B {
|
||||
b: u8,
|
||||
},
|
||||
C,
|
||||
D(u8),
|
||||
E(String),
|
||||
F(u8, u8),
|
||||
}
|
||||
|
||||
assert_tokens(
|
||||
&Untagged::A { a: 1 },
|
||||
&[
|
||||
Token::StructStart("Untagged", 1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
Token::U8(1),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&Untagged::B { b: 2 },
|
||||
&[
|
||||
Token::StructStart("Untagged", 1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("b"),
|
||||
Token::U8(2),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&Untagged::C,
|
||||
&[
|
||||
Token::Unit,
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&Untagged::D(4),
|
||||
&[
|
||||
Token::U8(4),
|
||||
]
|
||||
);
|
||||
assert_tokens(
|
||||
&Untagged::E("e".to_owned()),
|
||||
&[
|
||||
Token::Str("e"),
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&Untagged::F(1, 2),
|
||||
&[
|
||||
Token::TupleStart(2),
|
||||
|
||||
Token::TupleSep,
|
||||
Token::U8(1),
|
||||
|
||||
Token::TupleSep,
|
||||
Token::U8(2),
|
||||
|
||||
Token::TupleEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_de_tokens_error::<Untagged>(
|
||||
&[
|
||||
Token::Option(false),
|
||||
],
|
||||
Error::Message("data did not match any variant of untagged enum Untagged".to_owned()),
|
||||
);
|
||||
|
||||
assert_de_tokens_error::<Untagged>(
|
||||
&[
|
||||
Token::TupleStart(1),
|
||||
|
||||
Token::TupleSep,
|
||||
Token::U8(1),
|
||||
|
||||
Token::TupleEnd,
|
||||
],
|
||||
Error::Message("data did not match any variant of untagged enum Untagged".to_owned()),
|
||||
);
|
||||
|
||||
assert_de_tokens_error::<Untagged>(
|
||||
&[
|
||||
Token::TupleStart(3),
|
||||
|
||||
Token::TupleSep,
|
||||
Token::U8(1),
|
||||
|
||||
Token::TupleSep,
|
||||
Token::U8(2),
|
||||
|
||||
Token::TupleSep,
|
||||
Token::U8(3),
|
||||
|
||||
Token::TupleEnd,
|
||||
],
|
||||
Error::Message("data did not match any variant of untagged enum Untagged".to_owned()),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_internally_tagged_enum() {
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct Newtype(BTreeMap<String, String>);
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct Struct {
|
||||
f: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type")]
|
||||
enum InternallyTagged {
|
||||
A {
|
||||
a: u8,
|
||||
},
|
||||
B {
|
||||
b: u8,
|
||||
},
|
||||
C,
|
||||
D(BTreeMap<String, String>),
|
||||
E(Newtype),
|
||||
F(Struct),
|
||||
}
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::A { a: 1 },
|
||||
&[
|
||||
Token::StructStart("InternallyTagged", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("type"),
|
||||
Token::Str("A"),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
Token::U8(1),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::B { b: 2 },
|
||||
&[
|
||||
Token::StructStart("InternallyTagged", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("type"),
|
||||
Token::Str("B"),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("b"),
|
||||
Token::U8(2),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::C,
|
||||
&[
|
||||
Token::StructStart("InternallyTagged", 1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("type"),
|
||||
Token::Str("C"),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::D(BTreeMap::new()),
|
||||
&[
|
||||
Token::MapStart(Some(1)),
|
||||
|
||||
Token::MapSep,
|
||||
Token::Str("type"),
|
||||
Token::Str("D"),
|
||||
|
||||
Token::MapEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::E(Newtype(BTreeMap::new())),
|
||||
&[
|
||||
Token::MapStart(Some(1)),
|
||||
|
||||
Token::MapSep,
|
||||
Token::Str("type"),
|
||||
Token::Str("E"),
|
||||
|
||||
Token::MapEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::F(Struct { f: 6 }),
|
||||
&[
|
||||
Token::StructStart("Struct", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("type"),
|
||||
Token::Str("F"),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("f"),
|
||||
Token::U8(6),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_de_tokens_error::<InternallyTagged>(
|
||||
&[
|
||||
Token::MapStart(Some(0)),
|
||||
Token::MapEnd,
|
||||
],
|
||||
Error::Message("missing field `type`".to_owned()),
|
||||
);
|
||||
|
||||
assert_de_tokens_error::<InternallyTagged>(
|
||||
&[
|
||||
Token::MapStart(Some(1)),
|
||||
|
||||
Token::MapSep,
|
||||
Token::Str("type"),
|
||||
Token::Str("Z"),
|
||||
|
||||
Token::MapEnd,
|
||||
],
|
||||
Error::Message("unknown variant `Z`, expected one of `A`, `B`, `C`, `D`, `E`, `F`".to_owned()),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::net;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::str;
|
||||
use std::time::Duration;
|
||||
|
||||
extern crate serde_test;
|
||||
use self::serde_test::{
|
||||
Error,
|
||||
Token,
|
||||
assert_ser_tokens,
|
||||
assert_ser_tokens_error,
|
||||
};
|
||||
|
||||
extern crate fnv;
|
||||
use self::fnv::FnvHasher;
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
use serde::ser::iterator;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct UnitStruct;
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct TupleStruct(i32, i32, i32);
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Struct {
|
||||
a: i32,
|
||||
b: i32,
|
||||
c: i32,
|
||||
}
|
||||
|
||||
#[derive(Serialize, PartialEq, Debug)]
|
||||
enum Enum {
|
||||
Unit,
|
||||
One(i32),
|
||||
Seq(i32, i32),
|
||||
Map { a: i32, b: i32 },
|
||||
#[serde(skip_serializing)]
|
||||
SkippedUnit,
|
||||
#[serde(skip_serializing)]
|
||||
SkippedOne(i32),
|
||||
#[serde(skip_serializing)]
|
||||
SkippedSeq(i32, i32),
|
||||
#[serde(skip_serializing)]
|
||||
SkippedMap { _a: i32, _b: i32 },
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! declare_tests {
|
||||
($($name:ident { $($value:expr => $tokens:expr,)+ })+) => {
|
||||
$(
|
||||
#[test]
|
||||
fn $name() {
|
||||
$(
|
||||
assert_ser_tokens(&$value, $tokens);
|
||||
)+
|
||||
}
|
||||
)+
|
||||
}
|
||||
}
|
||||
|
||||
declare_tests! {
|
||||
test_unit {
|
||||
() => &[Token::Unit],
|
||||
}
|
||||
test_bool {
|
||||
true => &[Token::Bool(true)],
|
||||
false => &[Token::Bool(false)],
|
||||
}
|
||||
test_isizes {
|
||||
0i8 => &[Token::I8(0)],
|
||||
0i16 => &[Token::I16(0)],
|
||||
0i32 => &[Token::I32(0)],
|
||||
0i64 => &[Token::I64(0)],
|
||||
}
|
||||
test_usizes {
|
||||
0u8 => &[Token::U8(0)],
|
||||
0u16 => &[Token::U16(0)],
|
||||
0u32 => &[Token::U32(0)],
|
||||
0u64 => &[Token::U64(0)],
|
||||
}
|
||||
test_floats {
|
||||
0f32 => &[Token::F32(0.)],
|
||||
0f64 => &[Token::F64(0.)],
|
||||
}
|
||||
test_char {
|
||||
'a' => &[Token::Char('a')],
|
||||
}
|
||||
test_str {
|
||||
"abc" => &[Token::Str("abc")],
|
||||
"abc".to_owned() => &[Token::Str("abc")],
|
||||
}
|
||||
test_option {
|
||||
None::<i32> => &[Token::Option(false)],
|
||||
Some(1) => &[
|
||||
Token::Option(true),
|
||||
Token::I32(1),
|
||||
],
|
||||
}
|
||||
test_result {
|
||||
Ok::<i32, i32>(0) => &[
|
||||
Token::EnumNewType("Result", "Ok"),
|
||||
Token::I32(0),
|
||||
],
|
||||
Err::<i32, i32>(1) => &[
|
||||
Token::EnumNewType("Result", "Err"),
|
||||
Token::I32(1),
|
||||
],
|
||||
}
|
||||
test_slice {
|
||||
&[0][..0] => &[
|
||||
Token::SeqStart(Some(0)),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
&[1, 2, 3][..] => &[
|
||||
Token::SeqStart(Some(3)),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_array {
|
||||
[0; 0] => &[
|
||||
Token::SeqArrayStart(0),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
[1, 2, 3] => &[
|
||||
Token::SeqArrayStart(3),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_vec {
|
||||
Vec::<isize>::new() => &[
|
||||
Token::SeqStart(Some(0)),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
vec![vec![], vec![1], vec![2, 3]] => &[
|
||||
Token::SeqStart(Some(3)),
|
||||
Token::SeqSep,
|
||||
Token::SeqStart(Some(0)),
|
||||
Token::SeqEnd,
|
||||
|
||||
Token::SeqSep,
|
||||
Token::SeqStart(Some(1)),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
Token::SeqEnd,
|
||||
|
||||
Token::SeqSep,
|
||||
Token::SeqStart(Some(2)),
|
||||
Token::SeqSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_hashset {
|
||||
HashSet::<isize>::new() => &[
|
||||
Token::SeqStart(Some(0)),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
hashset![1] => &[
|
||||
Token::SeqStart(Some(1)),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
hashset![FnvHasher @ 1] => &[
|
||||
Token::SeqStart(Some(1)),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_tuple {
|
||||
(1,) => &[
|
||||
Token::TupleStart(1),
|
||||
Token::TupleSep,
|
||||
Token::I32(1),
|
||||
Token::TupleEnd,
|
||||
],
|
||||
(1, 2, 3) => &[
|
||||
Token::TupleStart(3),
|
||||
Token::TupleSep,
|
||||
Token::I32(1),
|
||||
|
||||
Token::TupleSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::TupleSep,
|
||||
Token::I32(3),
|
||||
Token::TupleEnd,
|
||||
],
|
||||
}
|
||||
test_btreemap {
|
||||
btreemap![1 => 2] => &[
|
||||
Token::MapStart(Some(1)),
|
||||
Token::MapSep,
|
||||
Token::I32(1),
|
||||
Token::I32(2),
|
||||
Token::MapEnd,
|
||||
],
|
||||
btreemap![1 => 2, 3 => 4] => &[
|
||||
Token::MapStart(Some(2)),
|
||||
Token::MapSep,
|
||||
Token::I32(1),
|
||||
Token::I32(2),
|
||||
|
||||
Token::MapSep,
|
||||
Token::I32(3),
|
||||
Token::I32(4),
|
||||
Token::MapEnd,
|
||||
],
|
||||
btreemap![1 => btreemap![], 2 => btreemap![3 => 4, 5 => 6]] => &[
|
||||
Token::MapStart(Some(2)),
|
||||
Token::MapSep,
|
||||
Token::I32(1),
|
||||
Token::MapStart(Some(0)),
|
||||
Token::MapEnd,
|
||||
|
||||
Token::MapSep,
|
||||
Token::I32(2),
|
||||
Token::MapStart(Some(2)),
|
||||
Token::MapSep,
|
||||
Token::I32(3),
|
||||
Token::I32(4),
|
||||
|
||||
Token::MapSep,
|
||||
Token::I32(5),
|
||||
Token::I32(6),
|
||||
Token::MapEnd,
|
||||
Token::MapEnd,
|
||||
],
|
||||
}
|
||||
test_hashmap {
|
||||
HashMap::<isize, isize>::new() => &[
|
||||
Token::MapStart(Some(0)),
|
||||
Token::MapEnd,
|
||||
],
|
||||
hashmap![1 => 2] => &[
|
||||
Token::MapStart(Some(1)),
|
||||
Token::MapSep,
|
||||
Token::I32(1),
|
||||
Token::I32(2),
|
||||
Token::MapEnd,
|
||||
],
|
||||
hashmap![FnvHasher @ 1 => 2] => &[
|
||||
Token::MapStart(Some(1)),
|
||||
Token::MapSep,
|
||||
Token::I32(1),
|
||||
Token::I32(2),
|
||||
Token::MapEnd,
|
||||
],
|
||||
}
|
||||
test_unit_struct {
|
||||
UnitStruct => &[Token::UnitStruct("UnitStruct")],
|
||||
}
|
||||
test_tuple_struct {
|
||||
TupleStruct(1, 2, 3) => &[
|
||||
Token::TupleStructStart("TupleStruct", 3),
|
||||
Token::TupleStructSep,
|
||||
Token::I32(1),
|
||||
|
||||
Token::TupleStructSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::TupleStructSep,
|
||||
Token::I32(3),
|
||||
Token::TupleStructEnd,
|
||||
],
|
||||
}
|
||||
test_struct {
|
||||
Struct { a: 1, b: 2, c: 3 } => &[
|
||||
Token::StructStart("Struct", 3),
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("b"),
|
||||
Token::I32(2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("c"),
|
||||
Token::I32(3),
|
||||
Token::StructEnd,
|
||||
],
|
||||
}
|
||||
test_enum {
|
||||
Enum::Unit => &[Token::EnumUnit("Enum", "Unit")],
|
||||
Enum::One(42) => &[Token::EnumNewType("Enum", "One"), Token::I32(42)],
|
||||
Enum::Seq(1, 2) => &[
|
||||
Token::EnumSeqStart("Enum", "Seq", 2),
|
||||
Token::EnumSeqSep,
|
||||
Token::I32(1),
|
||||
|
||||
Token::EnumSeqSep,
|
||||
Token::I32(2),
|
||||
Token::EnumSeqEnd,
|
||||
],
|
||||
Enum::Map { a: 1, b: 2 } => &[
|
||||
Token::EnumMapStart("Enum", "Map", 2),
|
||||
Token::EnumMapSep,
|
||||
Token::Str("a"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("b"),
|
||||
Token::I32(2),
|
||||
Token::EnumMapEnd,
|
||||
],
|
||||
}
|
||||
test_box {
|
||||
Box::new(0i32) => &[Token::I32(0)],
|
||||
}
|
||||
test_boxed_slice {
|
||||
Box::new([0, 1, 2]) => &[
|
||||
Token::SeqArrayStart(3),
|
||||
Token::SeqSep,
|
||||
Token::I32(0),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
Token::SeqSep,
|
||||
Token::I32(2),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_duration {
|
||||
Duration::new(1, 2) => &[
|
||||
Token::StructStart("Duration", 2),
|
||||
Token::StructSep,
|
||||
Token::Str("secs"),
|
||||
Token::U64(1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("nanos"),
|
||||
Token::U32(2),
|
||||
Token::StructEnd,
|
||||
],
|
||||
}
|
||||
test_net_ipv4addr {
|
||||
"1.2.3.4".parse::<net::Ipv4Addr>().unwrap() => &[Token::Str("1.2.3.4")],
|
||||
}
|
||||
test_net_ipv6addr {
|
||||
"::1".parse::<net::Ipv6Addr>().unwrap() => &[Token::Str("::1")],
|
||||
}
|
||||
test_net_socketaddr {
|
||||
"1.2.3.4:1234".parse::<net::SocketAddr>().unwrap() => &[Token::Str("1.2.3.4:1234")],
|
||||
"1.2.3.4:1234".parse::<net::SocketAddrV4>().unwrap() => &[Token::Str("1.2.3.4:1234")],
|
||||
"[::1]:1234".parse::<net::SocketAddrV6>().unwrap() => &[Token::Str("[::1]:1234")],
|
||||
}
|
||||
test_path {
|
||||
Path::new("/usr/local/lib") => &[
|
||||
Token::Str("/usr/local/lib"),
|
||||
],
|
||||
}
|
||||
test_path_buf {
|
||||
PathBuf::from("/usr/local/lib") => &[
|
||||
Token::Str("/usr/local/lib"),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[test]
|
||||
fn test_iterator() {
|
||||
assert_ser_tokens(iterator([0; 0].iter()), &[
|
||||
Token::SeqStart(Some(0)),
|
||||
Token::SeqEnd,
|
||||
]);
|
||||
assert_ser_tokens(iterator([1, 2, 3].iter()), &[
|
||||
Token::SeqStart(Some(3)),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
]);
|
||||
assert_ser_tokens(iterator([1, 2, 3].iter().map(|x| x * 2)), &[
|
||||
Token::SeqStart(Some(3)),
|
||||
Token::SeqSep,
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(4),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(6),
|
||||
Token::SeqEnd,
|
||||
]);
|
||||
assert_ser_tokens(iterator([1, 2, 3].iter().filter(|&x| x % 2 != 0)), &[
|
||||
Token::SeqStart(None),
|
||||
Token::SeqSep,
|
||||
Token::I32(1),
|
||||
|
||||
Token::SeqSep,
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
]);
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[test]
|
||||
fn test_net_ipaddr() {
|
||||
assert_ser_tokens(
|
||||
"1.2.3.4".parse::<net::IpAddr>().unwrap(),
|
||||
&[Token::Str("1.2.3.4")],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cannot_serialize_paths() {
|
||||
let path = unsafe {
|
||||
str::from_utf8_unchecked(b"Hello \xF0\x90\x80World")
|
||||
};
|
||||
assert_ser_tokens_error(
|
||||
&Path::new(path),
|
||||
&[],
|
||||
Error::Message("path contains invalid UTF-8 characters".to_owned()));
|
||||
|
||||
let mut path_buf = PathBuf::new();
|
||||
path_buf.push(path);
|
||||
|
||||
assert_ser_tokens_error(
|
||||
&path_buf,
|
||||
&[],
|
||||
Error::Message("path contains invalid UTF-8 characters".to_owned()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_enum_skipped() {
|
||||
assert_ser_tokens_error(
|
||||
&Enum::SkippedUnit,
|
||||
&[],
|
||||
Error::Message("the enum variant Enum::SkippedUnit cannot be serialized".to_owned()));
|
||||
assert_ser_tokens_error(
|
||||
&Enum::SkippedOne(42),
|
||||
&[],
|
||||
Error::Message("the enum variant Enum::SkippedOne cannot be serialized".to_owned()));
|
||||
assert_ser_tokens_error(
|
||||
&Enum::SkippedSeq(1, 2),
|
||||
&[],
|
||||
Error::Message("the enum variant Enum::SkippedSeq cannot be serialized".to_owned()));
|
||||
assert_ser_tokens_error(
|
||||
&Enum::SkippedMap { _a: 1, _b: 2 },
|
||||
&[],
|
||||
Error::Message("the enum variant Enum::SkippedMap cannot be serialized".to_owned()));
|
||||
}
|
||||
@@ -1,651 +0,0 @@
|
||||
#![feature(custom_derive, plugin, test)]
|
||||
#![plugin(serde_macros)]
|
||||
|
||||
extern crate test;
|
||||
extern crate serde;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::iter;
|
||||
use std::vec;
|
||||
|
||||
use serde::de::{self, Deserialize, Deserializer, Visitor};
|
||||
|
||||
#[derive(Debug)]
|
||||
enum Token<'a> {
|
||||
Bool(bool),
|
||||
Isize(isize),
|
||||
I8(i8),
|
||||
I16(i16),
|
||||
I32(i32),
|
||||
I64(i64),
|
||||
Usize(usize),
|
||||
U8(u8),
|
||||
U16(u16),
|
||||
U32(u32),
|
||||
U64(u64),
|
||||
F32(f32),
|
||||
F64(f64),
|
||||
Char(char),
|
||||
Str(&'a str),
|
||||
String(String),
|
||||
|
||||
Option(bool),
|
||||
|
||||
Unit,
|
||||
NamedUnit(&'a str),
|
||||
|
||||
SeqStart(usize),
|
||||
NamedSeqStart(&'a str, usize),
|
||||
SeqSep(bool),
|
||||
SeqEnd,
|
||||
|
||||
MapStart(usize),
|
||||
NamedMapStart(&'a str, usize),
|
||||
MapSep(bool),
|
||||
MapEnd,
|
||||
|
||||
EnumStart(&'a str, &'a str),
|
||||
EnumEnd,
|
||||
}
|
||||
|
||||
struct TokenDeserializer<'a> {
|
||||
tokens: iter::Peekable<vec::IntoIter<Token<'a>>>,
|
||||
}
|
||||
|
||||
impl<'a> TokenDeserializer<'a> {
|
||||
fn new(tokens: Vec<Token<'a>>) -> TokenDeserializer<'a> {
|
||||
TokenDeserializer {
|
||||
tokens: tokens.into_iter().peekable(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, PartialEq, Debug)]
|
||||
enum Error {
|
||||
SyntaxError,
|
||||
EndOfStreamError,
|
||||
MissingFieldError(&'static str),
|
||||
}
|
||||
|
||||
impl de::Error for Error {
|
||||
fn syntax_error() -> Error { Error::SyntaxError }
|
||||
|
||||
fn end_of_stream_error() -> Error { Error::EndOfStreamError }
|
||||
|
||||
fn missing_field_error(field: &'static str) -> Error {
|
||||
Error::MissingFieldError(field)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Deserializer for TokenDeserializer<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
match self.tokens.next() {
|
||||
Some(Token::Bool(v)) => visitor.visit_bool(v),
|
||||
Some(Token::Isize(v)) => visitor.visit_isize(v),
|
||||
Some(Token::I8(v)) => visitor.visit_i8(v),
|
||||
Some(Token::I16(v)) => visitor.visit_i16(v),
|
||||
Some(Token::I32(v)) => visitor.visit_i32(v),
|
||||
Some(Token::I64(v)) => visitor.visit_i64(v),
|
||||
Some(Token::Usize(v)) => visitor.visit_usize(v),
|
||||
Some(Token::U8(v)) => visitor.visit_u8(v),
|
||||
Some(Token::U16(v)) => visitor.visit_u16(v),
|
||||
Some(Token::U32(v)) => visitor.visit_u32(v),
|
||||
Some(Token::U64(v)) => visitor.visit_u64(v),
|
||||
Some(Token::F32(v)) => visitor.visit_f32(v),
|
||||
Some(Token::F64(v)) => visitor.visit_f64(v),
|
||||
Some(Token::Char(v)) => visitor.visit_char(v),
|
||||
Some(Token::Str(v)) => visitor.visit_str(v),
|
||||
Some(Token::String(v)) => visitor.visit_string(v),
|
||||
Some(Token::Option(false)) => visitor.visit_none(),
|
||||
Some(Token::Option(true)) => visitor.visit_some(self),
|
||||
Some(Token::Unit) => visitor.visit_unit(),
|
||||
Some(Token::NamedUnit(name)) => visitor.visit_named_unit(name),
|
||||
Some(Token::SeqStart(len)) => {
|
||||
visitor.visit_seq(TokenDeserializerSeqVisitor {
|
||||
de: self,
|
||||
len: len,
|
||||
first: true,
|
||||
})
|
||||
}
|
||||
Some(Token::NamedSeqStart(name, len)) => {
|
||||
visitor.visit_named_seq(name, TokenDeserializerSeqVisitor {
|
||||
de: self,
|
||||
len: len,
|
||||
first: true,
|
||||
})
|
||||
}
|
||||
Some(Token::MapStart(len)) => {
|
||||
visitor.visit_map(TokenDeserializerMapVisitor {
|
||||
de: self,
|
||||
len: len,
|
||||
first: true,
|
||||
})
|
||||
}
|
||||
Some(Token::NamedMapStart(name, len)) => {
|
||||
visitor.visit_named_map(name, TokenDeserializerMapVisitor {
|
||||
de: self,
|
||||
len: len,
|
||||
first: true,
|
||||
})
|
||||
}
|
||||
Some(Token::EnumStart(name, variant)) => {
|
||||
visitor.visit_enum(name, variant, TokenDeserializerEnumVisitor {
|
||||
de: self,
|
||||
})
|
||||
}
|
||||
Some(_) => Err(Error::SyntaxError),
|
||||
None => Err(Error::EndOfStreamError),
|
||||
}
|
||||
}
|
||||
|
||||
/// Hook into `Option` deserializing so we can treat `Unit` as a
|
||||
/// `None`, or a regular value as `Some(value)`.
|
||||
#[inline]
|
||||
fn visit_option<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
match self.tokens.peek() {
|
||||
Some(&Token::Option(false)) => {
|
||||
self.tokens.next();
|
||||
visitor.visit_none()
|
||||
}
|
||||
Some(&Token::Option(true)) => {
|
||||
self.tokens.next();
|
||||
visitor.visit_some(self)
|
||||
}
|
||||
Some(&Token::Unit) => {
|
||||
self.tokens.next();
|
||||
visitor.visit_none()
|
||||
}
|
||||
Some(_) => visitor.visit_some(self),
|
||||
None => Err(Error::EndOfStreamError),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct TokenDeserializerSeqVisitor<'a, 'b: 'a> {
|
||||
de: &'a mut TokenDeserializer<'b>,
|
||||
len: usize,
|
||||
first: bool,
|
||||
}
|
||||
|
||||
impl<'a, 'b> de::SeqVisitor for TokenDeserializerSeqVisitor<'a, 'b> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit<T>(&mut self) -> Result<Option<T>, Error>
|
||||
where T: Deserialize,
|
||||
{
|
||||
let first = self.first;
|
||||
self.first = false;
|
||||
|
||||
match self.de.tokens.next() {
|
||||
Some(Token::SeqSep(first_)) if first_ == first => {
|
||||
self.len -= 1;
|
||||
Ok(Some(try!(Deserialize::deserialize(self.de))))
|
||||
}
|
||||
Some(Token::SeqEnd) => Ok(None),
|
||||
Some(_) => {
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
None => Err(Error::EndOfStreamError),
|
||||
}
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
match self.de.tokens.next() {
|
||||
Some(Token::SeqEnd) => Ok(()),
|
||||
Some(_) => Err(Error::SyntaxError),
|
||||
None => Err(Error::EndOfStreamError),
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(self.len, Some(self.len))
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct TokenDeserializerMapVisitor<'a, 'b: 'a> {
|
||||
de: &'a mut TokenDeserializer<'b>,
|
||||
len: usize,
|
||||
first: bool,
|
||||
}
|
||||
|
||||
impl<'a, 'b> de::MapVisitor for TokenDeserializerMapVisitor<'a, 'b> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
|
||||
where K: Deserialize,
|
||||
{
|
||||
let first = self.first;
|
||||
self.first = false;
|
||||
|
||||
match self.de.tokens.next() {
|
||||
Some(Token::MapSep(first_)) if first_ == first => {
|
||||
Ok(Some(try!(Deserialize::deserialize(self.de))))
|
||||
}
|
||||
Some(Token::MapEnd) => Ok(None),
|
||||
Some(_) => Err(Error::SyntaxError),
|
||||
None => Err(Error::EndOfStreamError),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_value<V>(&mut self) -> Result<V, Error>
|
||||
where V: Deserialize,
|
||||
{
|
||||
Ok(try!(Deserialize::deserialize(self.de)))
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
match self.de.tokens.next() {
|
||||
Some(Token::MapEnd) => Ok(()),
|
||||
Some(_) => Err(Error::SyntaxError),
|
||||
None => Err(Error::EndOfStreamError),
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(self.len, Some(self.len))
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct TokenDeserializerEnumVisitor<'a, 'b: 'a> {
|
||||
de: &'a mut TokenDeserializer<'b>,
|
||||
}
|
||||
|
||||
impl<'a, 'b> de::EnumVisitor for TokenDeserializerEnumVisitor<'a, 'b> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_unit(&mut self) -> Result<(), Error> {
|
||||
let value = try!(Deserialize::deserialize(self.de));
|
||||
|
||||
match self.de.tokens.next() {
|
||||
Some(Token::EnumEnd) => Ok(value),
|
||||
Some(_) => Err(Error::SyntaxError),
|
||||
None => Err(Error::EndOfStreamError),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_seq<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::EnumSeqVisitor,
|
||||
{
|
||||
let token = self.de.tokens.next();
|
||||
match token {
|
||||
Some(Token::SeqStart(len)) => {
|
||||
let value = try!(visitor.visit(TokenDeserializerSeqVisitor {
|
||||
de: self.de,
|
||||
len: len,
|
||||
first: true,
|
||||
}));
|
||||
|
||||
match self.de.tokens.next() {
|
||||
Some(Token::EnumEnd) => Ok(value),
|
||||
Some(_) => Err(Error::SyntaxError),
|
||||
None => Err(Error::EndOfStreamError),
|
||||
}
|
||||
}
|
||||
Some(_) => Err(Error::SyntaxError),
|
||||
None => Err(Error::EndOfStreamError),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_map<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::EnumMapVisitor,
|
||||
{
|
||||
match self.de.tokens.next() {
|
||||
Some(Token::MapStart(len)) => {
|
||||
let value = try!(visitor.visit(TokenDeserializerMapVisitor {
|
||||
de: self.de,
|
||||
len: len,
|
||||
first: true,
|
||||
}));
|
||||
|
||||
match self.de.tokens.next() {
|
||||
Some(Token::EnumEnd) => Ok(value),
|
||||
Some(_) => Err(Error::SyntaxError),
|
||||
None => Err(Error::EndOfStreamError),
|
||||
}
|
||||
}
|
||||
Some(_) => Err(Error::SyntaxError),
|
||||
None => Err(Error::EndOfStreamError),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(Copy, PartialEq, Debug)]
|
||||
#[derive_deserialize]
|
||||
struct NamedUnit;
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
#[derive_deserialize]
|
||||
struct NamedSeq(i32, i32, i32);
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
#[derive_deserialize]
|
||||
struct NamedMap {
|
||||
a: i32,
|
||||
b: i32,
|
||||
c: i32,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
#[derive_deserialize]
|
||||
enum Enum {
|
||||
Unit,
|
||||
Seq(i32, i32, i32),
|
||||
Map { a: i32, b: i32, c: i32 }
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! btreemap {
|
||||
() => {
|
||||
BTreeMap::new()
|
||||
};
|
||||
($($key:expr => $value:expr),+) => {
|
||||
{
|
||||
let mut map = BTreeMap::new();
|
||||
$(map.insert($key, $value);)+
|
||||
map
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! declare_test {
|
||||
($name:ident { $($value:expr => $tokens:expr,)+ }) => {
|
||||
#[test]
|
||||
fn $name() {
|
||||
$(
|
||||
let mut de = TokenDeserializer::new($tokens);
|
||||
let value: Result<_, Error> = Deserialize::deserialize(&mut de);
|
||||
assert_eq!(value, Ok($value));
|
||||
)+
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! declare_tests {
|
||||
($($name:ident { $($value:expr => $tokens:expr,)+ })+) => {
|
||||
$(
|
||||
declare_test!($name { $($value => $tokens,)+ });
|
||||
)+
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
declare_tests! {
|
||||
test_bool {
|
||||
true => vec![Token::Bool(true)],
|
||||
false => vec![Token::Bool(false)],
|
||||
}
|
||||
test_isize {
|
||||
0isize => vec![Token::Isize(0)],
|
||||
0isize => vec![Token::I8(0)],
|
||||
0isize => vec![Token::I16(0)],
|
||||
0isize => vec![Token::I32(0)],
|
||||
0isize => vec![Token::I64(0)],
|
||||
0isize => vec![Token::Usize(0)],
|
||||
0isize => vec![Token::U8(0)],
|
||||
0isize => vec![Token::U16(0)],
|
||||
0isize => vec![Token::U32(0)],
|
||||
0isize => vec![Token::U64(0)],
|
||||
0isize => vec![Token::F32(0.)],
|
||||
0isize => vec![Token::F64(0.)],
|
||||
}
|
||||
test_ints {
|
||||
0isize => vec![Token::Isize(0)],
|
||||
0i8 => vec![Token::I8(0)],
|
||||
0i16 => vec![Token::I16(0)],
|
||||
0i32 => vec![Token::I32(0)],
|
||||
0i64 => vec![Token::I64(0)],
|
||||
}
|
||||
test_uints {
|
||||
0usize => vec![Token::Usize(0)],
|
||||
0u8 => vec![Token::U8(0)],
|
||||
0u16 => vec![Token::U16(0)],
|
||||
0u32 => vec![Token::U32(0)],
|
||||
0u64 => vec![Token::U64(0)],
|
||||
}
|
||||
test_floats {
|
||||
0f32 => vec![Token::F32(0.)],
|
||||
0f64 => vec![Token::F64(0.)],
|
||||
}
|
||||
test_char {
|
||||
'a' => vec![Token::Char('a')],
|
||||
'a' => vec![Token::Str("a")],
|
||||
'a' => vec![Token::String("a".to_string())],
|
||||
}
|
||||
test_string {
|
||||
"abc".to_string() => vec![Token::Str("abc")],
|
||||
"abc".to_string() => vec![Token::String("abc".to_string())],
|
||||
"a".to_string() => vec![Token::Char('a')],
|
||||
}
|
||||
test_option {
|
||||
None::<i32> => vec![Token::Unit],
|
||||
None::<i32> => vec![Token::Option(false)],
|
||||
Some(1) => vec![Token::I32(1)],
|
||||
Some(1) => vec![
|
||||
Token::Option(true),
|
||||
Token::I32(1),
|
||||
],
|
||||
}
|
||||
test_unit {
|
||||
() => vec![Token::Unit],
|
||||
() => vec![
|
||||
Token::SeqStart(0),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
() => vec![
|
||||
Token::NamedSeqStart("Anything", 0),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_named_unit {
|
||||
NamedUnit => vec![Token::Unit],
|
||||
NamedUnit => vec![Token::NamedUnit("NamedUnit")],
|
||||
NamedUnit => vec![
|
||||
Token::SeqStart(0),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_named_seq {
|
||||
NamedSeq(1, 2, 3) => vec![
|
||||
Token::SeqStart(3),
|
||||
Token::SeqSep(true),
|
||||
Token::I32(1),
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
NamedSeq(1, 2, 3) => vec![
|
||||
Token::NamedSeqStart("NamedSeq", 3),
|
||||
Token::SeqSep(true),
|
||||
Token::I32(1),
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_vec {
|
||||
Vec::<isize>::new() => vec![
|
||||
Token::SeqStart(0),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
vec![vec![], vec![1], vec![2, 3]] => vec![
|
||||
Token::SeqStart(3),
|
||||
Token::SeqSep(true),
|
||||
Token::SeqStart(0),
|
||||
Token::SeqEnd,
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::SeqStart(1),
|
||||
Token::SeqSep(true),
|
||||
Token::I32(1),
|
||||
Token::SeqEnd,
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::SeqStart(2),
|
||||
Token::SeqSep(true),
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_tuple {
|
||||
(1,) => vec![
|
||||
Token::SeqStart(1),
|
||||
Token::SeqSep(true),
|
||||
Token::I32(1),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
(1, 2, 3) => vec![
|
||||
Token::SeqStart(3),
|
||||
Token::SeqSep(true),
|
||||
Token::I32(1),
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_btreemap {
|
||||
btreemap![1 => 2] => vec![
|
||||
Token::MapStart(1),
|
||||
Token::MapSep(true),
|
||||
Token::I32(1),
|
||||
Token::I32(2),
|
||||
Token::MapEnd,
|
||||
],
|
||||
btreemap![1 => 2, 3 => 4] => vec![
|
||||
Token::MapStart(2),
|
||||
Token::MapSep(true),
|
||||
Token::I32(1),
|
||||
Token::I32(2),
|
||||
|
||||
Token::MapSep(false),
|
||||
Token::I32(3),
|
||||
Token::I32(4),
|
||||
Token::MapEnd,
|
||||
],
|
||||
btreemap![1 => btreemap![], 2 => btreemap![3 => 4, 5 => 6]] => vec![
|
||||
Token::MapStart(2),
|
||||
Token::MapSep(true),
|
||||
Token::I32(1),
|
||||
Token::MapStart(0),
|
||||
Token::MapEnd,
|
||||
|
||||
Token::MapSep(false),
|
||||
Token::I32(2),
|
||||
Token::MapStart(2),
|
||||
Token::MapSep(true),
|
||||
Token::I32(3),
|
||||
Token::I32(4),
|
||||
|
||||
Token::MapSep(false),
|
||||
Token::I32(5),
|
||||
Token::I32(6),
|
||||
Token::MapEnd,
|
||||
Token::MapEnd,
|
||||
],
|
||||
}
|
||||
test_named_map {
|
||||
NamedMap { a: 1, b: 2, c: 3 } => vec![
|
||||
Token::MapStart(3),
|
||||
Token::MapSep(true),
|
||||
Token::Str("a"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::MapSep(false),
|
||||
Token::Str("b"),
|
||||
Token::I32(2),
|
||||
|
||||
Token::MapSep(false),
|
||||
Token::Str("c"),
|
||||
Token::I32(3),
|
||||
Token::MapEnd,
|
||||
],
|
||||
NamedMap { a: 1, b: 2, c: 3 } => vec![
|
||||
Token::NamedMapStart("NamedMap", 3),
|
||||
Token::MapSep(true),
|
||||
Token::Str("a"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::MapSep(false),
|
||||
Token::Str("b"),
|
||||
Token::I32(2),
|
||||
|
||||
Token::MapSep(false),
|
||||
Token::Str("c"),
|
||||
Token::I32(3),
|
||||
Token::MapEnd,
|
||||
],
|
||||
}
|
||||
test_enum {
|
||||
Enum::Unit => vec![
|
||||
Token::EnumStart("Enum", "Unit"),
|
||||
Token::Unit,
|
||||
Token::EnumEnd,
|
||||
],
|
||||
}
|
||||
test_enum_seq {
|
||||
Enum::Seq(1, 2, 3) => vec![
|
||||
Token::EnumStart("Enum", "Seq"),
|
||||
Token::SeqStart(3),
|
||||
Token::SeqSep(true),
|
||||
Token::I32(1),
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
Token::EnumEnd,
|
||||
],
|
||||
}
|
||||
test_enum_map {
|
||||
Enum::Map { a: 1, b: 2, c: 3 } => vec![
|
||||
Token::EnumStart("Enum", "Map"),
|
||||
Token::MapStart(3),
|
||||
Token::MapSep(true),
|
||||
Token::Str("a"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::MapSep(false),
|
||||
Token::Str("b"),
|
||||
Token::I32(2),
|
||||
|
||||
Token::MapSep(false),
|
||||
Token::Str("c"),
|
||||
Token::I32(3),
|
||||
Token::MapEnd,
|
||||
Token::EnumEnd,
|
||||
],
|
||||
}
|
||||
}
|
||||
@@ -1,761 +0,0 @@
|
||||
#![feature(custom_derive, plugin, test)]
|
||||
#![plugin(serde_macros)]
|
||||
|
||||
extern crate test;
|
||||
extern crate serde;
|
||||
|
||||
use std::fmt::Debug;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::de;
|
||||
use serde::ser;
|
||||
|
||||
use serde::json::{
|
||||
self,
|
||||
Value,
|
||||
from_str,
|
||||
from_value,
|
||||
to_value,
|
||||
};
|
||||
|
||||
use serde::json::error::{Error, ErrorCode};
|
||||
|
||||
macro_rules! treemap {
|
||||
($($k:expr => $v:expr),*) => ({
|
||||
let mut _m = BTreeMap::new();
|
||||
$(_m.insert($k, $v);)*
|
||||
_m
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
#[derive_serialize]
|
||||
#[derive_deserialize]
|
||||
enum Animal {
|
||||
Dog,
|
||||
Frog(String, Vec<isize>),
|
||||
Cat { age: usize, name: String },
|
||||
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
#[derive_serialize]
|
||||
#[derive_deserialize]
|
||||
struct Inner {
|
||||
a: (),
|
||||
b: usize,
|
||||
c: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
#[derive_serialize]
|
||||
#[derive_deserialize]
|
||||
struct Outer {
|
||||
inner: Vec<Inner>,
|
||||
}
|
||||
|
||||
fn test_encode_ok<T>(errors: &[(T, &str)])
|
||||
where T: PartialEq + Debug + ser::Serialize,
|
||||
{
|
||||
for &(ref value, out) in errors {
|
||||
let out = out.to_string();
|
||||
|
||||
let s = json::to_string(value).unwrap();
|
||||
assert_eq!(s, out);
|
||||
|
||||
let v = to_value(&value);
|
||||
let s = json::to_string(&v).unwrap();
|
||||
assert_eq!(s, out);
|
||||
}
|
||||
}
|
||||
|
||||
fn test_pretty_encode_ok<T>(errors: &[(T, &str)])
|
||||
where T: PartialEq + Debug + ser::Serialize,
|
||||
{
|
||||
for &(ref value, out) in errors {
|
||||
let out = out.to_string();
|
||||
|
||||
let s = json::to_string_pretty(value).unwrap();
|
||||
assert_eq!(s, out);
|
||||
|
||||
let v = to_value(&value);
|
||||
let s = json::to_string_pretty(&v).unwrap();
|
||||
assert_eq!(s, out);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_write_null() {
|
||||
let tests = &[
|
||||
((), "null"),
|
||||
];
|
||||
test_encode_ok(tests);
|
||||
test_pretty_encode_ok(tests);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_write_i64() {
|
||||
let tests = &[
|
||||
(3i64, "3"),
|
||||
(-2i64, "-2"),
|
||||
(-1234i64, "-1234"),
|
||||
];
|
||||
test_encode_ok(tests);
|
||||
test_pretty_encode_ok(tests);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_write_f64() {
|
||||
let tests = &[
|
||||
(3.0, "3"),
|
||||
(3.1, "3.1"),
|
||||
(-1.5, "-1.5"),
|
||||
(0.5, "0.5"),
|
||||
];
|
||||
test_encode_ok(tests);
|
||||
test_pretty_encode_ok(tests);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_write_str() {
|
||||
let tests = &[
|
||||
("", "\"\""),
|
||||
("foo", "\"foo\""),
|
||||
];
|
||||
test_encode_ok(tests);
|
||||
test_pretty_encode_ok(tests);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_write_bool() {
|
||||
let tests = &[
|
||||
(true, "true"),
|
||||
(false, "false"),
|
||||
];
|
||||
test_encode_ok(tests);
|
||||
test_pretty_encode_ok(tests);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_write_list() {
|
||||
test_encode_ok(&[
|
||||
(vec![], "[]"),
|
||||
(vec![true], "[true]"),
|
||||
(vec![true, false], "[true,false]"),
|
||||
]);
|
||||
|
||||
test_pretty_encode_ok(&[
|
||||
(vec![], "[]"),
|
||||
(
|
||||
vec![true],
|
||||
concat!(
|
||||
"[\n",
|
||||
" true\n",
|
||||
"]"
|
||||
),
|
||||
),
|
||||
(
|
||||
vec![true, false],
|
||||
concat!(
|
||||
"[\n",
|
||||
" true,\n",
|
||||
" false\n",
|
||||
"]"
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
let long_test_list = Value::Array(vec![
|
||||
Value::Bool(false),
|
||||
Value::Null,
|
||||
Value::Array(vec![Value::String("foo\nbar".to_string()), Value::F64(3.5)])]);
|
||||
|
||||
test_encode_ok(&[
|
||||
(
|
||||
long_test_list.clone(),
|
||||
"[false,null,[\"foo\\nbar\",3.5]]",
|
||||
),
|
||||
]);
|
||||
|
||||
test_pretty_encode_ok(&[
|
||||
(
|
||||
long_test_list,
|
||||
concat!(
|
||||
"[\n",
|
||||
" false,\n",
|
||||
" null,\n",
|
||||
" [\n",
|
||||
" \"foo\\nbar\",\n",
|
||||
" 3.5\n",
|
||||
" ]\n",
|
||||
"]"
|
||||
),
|
||||
)
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_write_object() {
|
||||
test_encode_ok(&[
|
||||
(treemap!(), "{}"),
|
||||
(treemap!("a".to_string() => true), "{\"a\":true}"),
|
||||
(
|
||||
treemap!(
|
||||
"a".to_string() => true,
|
||||
"b".to_string() => false
|
||||
),
|
||||
"{\"a\":true,\"b\":false}"),
|
||||
]);
|
||||
|
||||
test_pretty_encode_ok(&[
|
||||
(treemap!(), "{}"),
|
||||
(
|
||||
treemap!("a".to_string() => true),
|
||||
concat!(
|
||||
"{\n",
|
||||
" \"a\": true\n",
|
||||
"}"
|
||||
),
|
||||
),
|
||||
(
|
||||
treemap!(
|
||||
"a".to_string() => true,
|
||||
"b".to_string() => false
|
||||
),
|
||||
concat!(
|
||||
"{\n",
|
||||
" \"a\": true,\n",
|
||||
" \"b\": false\n",
|
||||
"}"
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
let complex_obj = Value::Object(treemap!(
|
||||
"b".to_string() => Value::Array(vec![
|
||||
Value::Object(treemap!("c".to_string() => Value::String("\x0c\r".to_string()))),
|
||||
Value::Object(treemap!("d".to_string() => Value::String("".to_string())))
|
||||
])
|
||||
));
|
||||
|
||||
test_encode_ok(&[
|
||||
(
|
||||
complex_obj.clone(),
|
||||
"{\
|
||||
\"b\":[\
|
||||
{\"c\":\"\\f\\r\"},\
|
||||
{\"d\":\"\"}\
|
||||
]\
|
||||
}"
|
||||
),
|
||||
]);
|
||||
|
||||
test_pretty_encode_ok(&[
|
||||
(
|
||||
complex_obj.clone(),
|
||||
concat!(
|
||||
"{\n",
|
||||
" \"b\": [\n",
|
||||
" {\n",
|
||||
" \"c\": \"\\f\\r\"\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"d\": \"\"\n",
|
||||
" }\n",
|
||||
" ]\n",
|
||||
"}"
|
||||
),
|
||||
)
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_write_tuple() {
|
||||
test_encode_ok(&[
|
||||
(
|
||||
(5,),
|
||||
"[5]",
|
||||
),
|
||||
]);
|
||||
|
||||
test_pretty_encode_ok(&[
|
||||
(
|
||||
(5,),
|
||||
concat!(
|
||||
"[\n",
|
||||
" 5\n",
|
||||
"]"
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
test_encode_ok(&[
|
||||
(
|
||||
(5, (6, "abc")),
|
||||
"[5,[6,\"abc\"]]",
|
||||
),
|
||||
]);
|
||||
|
||||
test_pretty_encode_ok(&[
|
||||
(
|
||||
(5, (6, "abc")),
|
||||
concat!(
|
||||
"[\n",
|
||||
" 5,\n",
|
||||
" [\n",
|
||||
" 6,\n",
|
||||
" \"abc\"\n",
|
||||
" ]\n",
|
||||
"]"
|
||||
),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_write_enum() {
|
||||
test_encode_ok(&[
|
||||
(
|
||||
Animal::Dog,
|
||||
"{\"Dog\":[]}",
|
||||
),
|
||||
(
|
||||
Animal::Frog("Henry".to_string(), vec![]),
|
||||
"{\"Frog\":[\"Henry\",[]]}",
|
||||
),
|
||||
(
|
||||
Animal::Frog("Henry".to_string(), vec![349]),
|
||||
"{\"Frog\":[\"Henry\",[349]]}",
|
||||
),
|
||||
(
|
||||
Animal::Frog("Henry".to_string(), vec![349, 102]),
|
||||
"{\"Frog\":[\"Henry\",[349,102]]}",
|
||||
),
|
||||
(
|
||||
Animal::Cat { age: 5, name: "Kate".to_string() },
|
||||
"{\"Cat\":{\"age\":5,\"name\":\"Kate\"}}"
|
||||
),
|
||||
]);
|
||||
|
||||
test_pretty_encode_ok(&[
|
||||
(
|
||||
Animal::Dog,
|
||||
concat!(
|
||||
"{\n",
|
||||
" \"Dog\": []\n",
|
||||
"}"
|
||||
),
|
||||
),
|
||||
(
|
||||
Animal::Frog("Henry".to_string(), vec![]),
|
||||
concat!(
|
||||
"{\n",
|
||||
" \"Frog\": [\n",
|
||||
" \"Henry\",\n",
|
||||
" []\n",
|
||||
" ]\n",
|
||||
"}"
|
||||
),
|
||||
),
|
||||
(
|
||||
Animal::Frog("Henry".to_string(), vec![349]),
|
||||
concat!(
|
||||
"{\n",
|
||||
" \"Frog\": [\n",
|
||||
" \"Henry\",\n",
|
||||
" [\n",
|
||||
" 349\n",
|
||||
" ]\n",
|
||||
" ]\n",
|
||||
"}"
|
||||
),
|
||||
),
|
||||
(
|
||||
Animal::Frog("Henry".to_string(), vec![349, 102]),
|
||||
concat!(
|
||||
"{\n",
|
||||
" \"Frog\": [\n",
|
||||
" \"Henry\",\n",
|
||||
" [\n",
|
||||
" 349,\n",
|
||||
" 102\n",
|
||||
" ]\n",
|
||||
" ]\n",
|
||||
"}"
|
||||
),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_write_option() {
|
||||
test_encode_ok(&[
|
||||
(None, "null"),
|
||||
(Some("jodhpurs"), "\"jodhpurs\""),
|
||||
]);
|
||||
|
||||
test_encode_ok(&[
|
||||
(None, "null"),
|
||||
(Some(vec!["foo", "bar"]), "[\"foo\",\"bar\"]"),
|
||||
]);
|
||||
|
||||
test_pretty_encode_ok(&[
|
||||
(None, "null"),
|
||||
(Some("jodhpurs"), "\"jodhpurs\""),
|
||||
]);
|
||||
|
||||
test_pretty_encode_ok(&[
|
||||
(None, "null"),
|
||||
(
|
||||
Some(vec!["foo", "bar"]),
|
||||
concat!(
|
||||
"[\n",
|
||||
" \"foo\",\n",
|
||||
" \"bar\"\n",
|
||||
"]"
|
||||
),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
fn test_parse_ok<'a, T>(errors: &[(&'a str, T)])
|
||||
where T: PartialEq + Debug + ser::Serialize + de::Deserialize,
|
||||
{
|
||||
for &(s, ref value) in errors {
|
||||
let v: T = from_str(s).unwrap();
|
||||
assert_eq!(v, *value);
|
||||
|
||||
// Make sure we can deserialize into a `Value`.
|
||||
let json_value: Value = from_str(s).unwrap();
|
||||
assert_eq!(json_value, to_value(&value));
|
||||
|
||||
// Make sure we can deserialize from a `Value`.
|
||||
let v: T = from_value(json_value.clone()).unwrap();
|
||||
assert_eq!(v, *value);
|
||||
|
||||
// Make sure we can round trip back to `Value`.
|
||||
let json_value2: Value = from_value(json_value.clone()).unwrap();
|
||||
assert_eq!(json_value, json_value2);
|
||||
}
|
||||
}
|
||||
|
||||
// FIXME (#5527): these could be merged once UFCS is finished.
|
||||
fn test_parse_err<'a, T>(errors: &[(&'a str, Error)])
|
||||
where T: Debug + de::Deserialize,
|
||||
{
|
||||
for &(s, ref err) in errors {
|
||||
let v: Result<T, Error> = from_str(s);
|
||||
assert_eq!(v.unwrap_err(), *err);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_null() {
|
||||
test_parse_err::<()>(&[
|
||||
("n", Error::SyntaxError(ErrorCode::ExpectedSomeIdent, 1, 2)),
|
||||
("nul", Error::SyntaxError(ErrorCode::ExpectedSomeIdent, 1, 4)),
|
||||
("nulla", Error::SyntaxError(ErrorCode::TrailingCharacters, 1, 5)),
|
||||
]);
|
||||
|
||||
test_parse_ok(&[
|
||||
("null", ()),
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_bool() {
|
||||
test_parse_err::<bool>(&[
|
||||
("t", Error::SyntaxError(ErrorCode::ExpectedSomeIdent, 1, 2)),
|
||||
("truz", Error::SyntaxError(ErrorCode::ExpectedSomeIdent, 1, 4)),
|
||||
("f", Error::SyntaxError(ErrorCode::ExpectedSomeIdent, 1, 2)),
|
||||
("faz", Error::SyntaxError(ErrorCode::ExpectedSomeIdent, 1, 3)),
|
||||
("truea", Error::SyntaxError(ErrorCode::TrailingCharacters, 1, 5)),
|
||||
("falsea", Error::SyntaxError(ErrorCode::TrailingCharacters, 1, 6)),
|
||||
]);
|
||||
|
||||
test_parse_ok(&[
|
||||
("true", true),
|
||||
(" true ", true),
|
||||
("false", false),
|
||||
(" false ", false),
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_number_errors() {
|
||||
test_parse_err::<f64>(&[
|
||||
("+", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 1)),
|
||||
(".", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 1)),
|
||||
("-", Error::SyntaxError(ErrorCode::InvalidNumber, 1, 2)),
|
||||
("00", Error::SyntaxError(ErrorCode::InvalidNumber, 1, 2)),
|
||||
("1.", Error::SyntaxError(ErrorCode::InvalidNumber, 1, 3)),
|
||||
("1e", Error::SyntaxError(ErrorCode::InvalidNumber, 1, 3)),
|
||||
("1e+", Error::SyntaxError(ErrorCode::InvalidNumber, 1, 4)),
|
||||
("1a", Error::SyntaxError(ErrorCode::TrailingCharacters, 1, 2)),
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_i64() {
|
||||
test_parse_ok(&[
|
||||
("3", 3),
|
||||
("-2", -2),
|
||||
("-1234", -1234),
|
||||
(" -1234 ", -1234),
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_f64() {
|
||||
test_parse_ok(&[
|
||||
("3.0", 3.0f64),
|
||||
("3.1", 3.1),
|
||||
("-1.2", -1.2),
|
||||
("0.4", 0.4),
|
||||
("0.4e5", 0.4e5),
|
||||
("0.4e15", 0.4e15),
|
||||
("0.4e-01", 0.4e-01),
|
||||
(" 0.4e-01 ", 0.4e-01),
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_string() {
|
||||
test_parse_err::<String>(&[
|
||||
("\"", Error::SyntaxError(ErrorCode::EOFWhileParsingString, 1, 2)),
|
||||
("\"lol", Error::SyntaxError(ErrorCode::EOFWhileParsingString, 1, 5)),
|
||||
("\"lol\"a", Error::SyntaxError(ErrorCode::TrailingCharacters, 1, 6)),
|
||||
]);
|
||||
|
||||
test_parse_ok(&[
|
||||
("\"\"", "".to_string()),
|
||||
("\"foo\"", "foo".to_string()),
|
||||
(" \"foo\" ", "foo".to_string()),
|
||||
("\"\\\"\"", "\"".to_string()),
|
||||
("\"\\b\"", "\x08".to_string()),
|
||||
("\"\\n\"", "\n".to_string()),
|
||||
("\"\\r\"", "\r".to_string()),
|
||||
("\"\\t\"", "\t".to_string()),
|
||||
("\"\\u12ab\"", "\u{12ab}".to_string()),
|
||||
("\"\\uAB12\"", "\u{AB12}".to_string()),
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_list() {
|
||||
test_parse_err::<Vec<f64>>(&[
|
||||
("[", Error::SyntaxError(ErrorCode::EOFWhileParsingValue, 1, 2)),
|
||||
("[ ", Error::SyntaxError(ErrorCode::EOFWhileParsingValue, 1, 3)),
|
||||
("[1", Error::SyntaxError(ErrorCode::EOFWhileParsingList, 1, 3)),
|
||||
("[1,", Error::SyntaxError(ErrorCode::EOFWhileParsingValue, 1, 4)),
|
||||
("[1,]", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 4)),
|
||||
("[1 2]", Error::SyntaxError(ErrorCode::ExpectedListCommaOrEnd, 1, 4)),
|
||||
("[]a", Error::SyntaxError(ErrorCode::TrailingCharacters, 1, 3)),
|
||||
]);
|
||||
|
||||
test_parse_ok(&[
|
||||
("[]", vec![]),
|
||||
("[ ]", vec![]),
|
||||
("[null]", vec![()]),
|
||||
(" [ null ] ", vec![()]),
|
||||
]);
|
||||
|
||||
test_parse_ok(&[
|
||||
("[true]", vec![true]),
|
||||
]);
|
||||
|
||||
test_parse_ok(&[
|
||||
("[3,1]", vec![3, 1]),
|
||||
(" [ 3 , 1 ] ", vec![3, 1]),
|
||||
]);
|
||||
|
||||
test_parse_ok(&[
|
||||
("[[3], [1, 2]]", vec![vec![3], vec![1, 2]]),
|
||||
]);
|
||||
|
||||
test_parse_ok(&[
|
||||
("[1]", (1,)),
|
||||
]);
|
||||
|
||||
test_parse_ok(&[
|
||||
("[1, 2]", (1, 2)),
|
||||
]);
|
||||
|
||||
test_parse_ok(&[
|
||||
("[1, 2, 3]", (1, 2, 3)),
|
||||
]);
|
||||
|
||||
test_parse_ok(&[
|
||||
("[1, [2, 3]]", (1, (2, 3))),
|
||||
]);
|
||||
|
||||
let v: () = from_str("[]").unwrap();
|
||||
assert_eq!(v, ());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_object() {
|
||||
test_parse_err::<BTreeMap<String, u32>>(&[
|
||||
("{", Error::SyntaxError(ErrorCode::EOFWhileParsingValue, 1, 2)),
|
||||
("{ ", Error::SyntaxError(ErrorCode::EOFWhileParsingValue, 1, 3)),
|
||||
("{1", Error::SyntaxError(ErrorCode::KeyMustBeAString, 1, 2)),
|
||||
("{ \"a\"", Error::SyntaxError(ErrorCode::EOFWhileParsingObject, 1, 6)),
|
||||
("{\"a\"", Error::SyntaxError(ErrorCode::EOFWhileParsingObject, 1, 5)),
|
||||
("{\"a\" ", Error::SyntaxError(ErrorCode::EOFWhileParsingObject, 1, 6)),
|
||||
("{\"a\" 1", Error::SyntaxError(ErrorCode::ExpectedColon, 1, 6)),
|
||||
("{\"a\":", Error::SyntaxError(ErrorCode::EOFWhileParsingValue, 1, 6)),
|
||||
("{\"a\":1", Error::SyntaxError(ErrorCode::EOFWhileParsingObject, 1, 7)),
|
||||
("{\"a\":1 1", Error::SyntaxError(ErrorCode::ExpectedObjectCommaOrEnd, 1, 8)),
|
||||
("{\"a\":1,", Error::SyntaxError(ErrorCode::EOFWhileParsingValue, 1, 8)),
|
||||
("{}a", Error::SyntaxError(ErrorCode::TrailingCharacters, 1, 3)),
|
||||
]);
|
||||
|
||||
test_parse_ok(&[
|
||||
("{}", treemap!()),
|
||||
("{ }", treemap!()),
|
||||
(
|
||||
"{\"a\":3}",
|
||||
treemap!("a".to_string() => 3)
|
||||
),
|
||||
(
|
||||
"{ \"a\" : 3 }",
|
||||
treemap!("a".to_string() => 3)
|
||||
),
|
||||
(
|
||||
"{\"a\":3,\"b\":4}",
|
||||
treemap!("a".to_string() => 3, "b".to_string() => 4)
|
||||
),
|
||||
(
|
||||
" { \"a\" : 3 , \"b\" : 4 } ",
|
||||
treemap!("a".to_string() => 3, "b".to_string() => 4),
|
||||
),
|
||||
]);
|
||||
|
||||
test_parse_ok(&[
|
||||
(
|
||||
"{\"a\": {\"b\": 3, \"c\": 4}}",
|
||||
treemap!("a".to_string() => treemap!("b".to_string() => 3, "c".to_string() => 4)),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_struct() {
|
||||
test_parse_err::<Outer>(&[
|
||||
("[]", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 0, 0)),
|
||||
("{}", Error::MissingFieldError("inner")),
|
||||
("{\"inner\": true}", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 0, 0)),
|
||||
]);
|
||||
|
||||
test_parse_ok(&[
|
||||
(
|
||||
"{
|
||||
\"inner\": []
|
||||
}",
|
||||
Outer {
|
||||
inner: vec![]
|
||||
},
|
||||
),
|
||||
(
|
||||
"{
|
||||
\"inner\": [
|
||||
{ \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
|
||||
]
|
||||
}",
|
||||
Outer {
|
||||
inner: vec![
|
||||
Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }
|
||||
]
|
||||
},
|
||||
)
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_option() {
|
||||
test_parse_ok(&[
|
||||
("null", None::<String>),
|
||||
("\"jodhpurs\"", Some("jodhpurs".to_string())),
|
||||
]);
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
#[derive_serialize]
|
||||
#[derive_deserialize]
|
||||
struct Foo {
|
||||
x: Option<isize>,
|
||||
}
|
||||
|
||||
/*
|
||||
let value: Foo = from_str("{}").unwrap();
|
||||
assert_eq!(value, Foo { x: None });
|
||||
*/
|
||||
|
||||
test_parse_ok(&[
|
||||
("{\"x\": null}", Foo { x: None }),
|
||||
("{\"x\": 5}", Foo { x: Some(5) }),
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_enum() {
|
||||
test_parse_err::<Animal>(&[
|
||||
("{}", Error::SyntaxError(ErrorCode::EOFWhileParsingString, 1, 3)),
|
||||
("{\"unknown\":[]}", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 0, 0)),
|
||||
("{\"Dog\":{}}", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 0, 0)),
|
||||
("{\"Frog\":{}}", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 9)),
|
||||
("{\"Cat\":[]}", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 8)),
|
||||
]);
|
||||
|
||||
test_parse_ok(&[
|
||||
("{\"Dog\":[]}", Animal::Dog),
|
||||
(" { \"Dog\" : [ ] } ", Animal::Dog),
|
||||
(
|
||||
"{\"Frog\":[\"Henry\",[]]}",
|
||||
Animal::Frog("Henry".to_string(), vec![]),
|
||||
),
|
||||
(
|
||||
" { \"Frog\": [ \"Henry\" , [ 349, 102 ] ] } ",
|
||||
Animal::Frog("Henry".to_string(), vec![349, 102]),
|
||||
),
|
||||
(
|
||||
"{\"Cat\": {\"age\": 5, \"name\": \"Kate\"}}",
|
||||
Animal::Cat { age: 5, name: "Kate".to_string() },
|
||||
),
|
||||
(
|
||||
" { \"Cat\" : { \"age\" : 5 , \"name\" : \"Kate\" } } ",
|
||||
Animal::Cat { age: 5, name: "Kate".to_string() },
|
||||
),
|
||||
]);
|
||||
|
||||
test_parse_ok(&[
|
||||
(
|
||||
concat!(
|
||||
"{",
|
||||
" \"a\": {\"Dog\": []},",
|
||||
" \"b\": {\"Frog\":[\"Henry\", []]}",
|
||||
"}"
|
||||
),
|
||||
treemap!(
|
||||
"a".to_string() => Animal::Dog,
|
||||
"b".to_string() => Animal::Frog("Henry".to_string(), vec![])
|
||||
)
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_trailing_whitespace() {
|
||||
test_parse_ok(&[
|
||||
("[1, 2] ", vec![1, 2]),
|
||||
("[1, 2]\n", vec![1, 2]),
|
||||
("[1, 2]\t", vec![1, 2]),
|
||||
("[1, 2]\t \n", vec![1, 2]),
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multiline_errors() {
|
||||
test_parse_err::<BTreeMap<String, String>>(&[
|
||||
("{\n \"foo\":\n \"bar\"", Error::SyntaxError(ErrorCode::EOFWhileParsingObject, 3, 8)),
|
||||
]);
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
extern crate serde;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::json::value::Value;
|
||||
use serde::json::builder::{ArrayBuilder, ObjectBuilder};
|
||||
|
||||
#[test]
|
||||
fn test_array_builder() {
|
||||
let value = ArrayBuilder::new().unwrap();
|
||||
assert_eq!(value, Value::Array(Vec::new()));
|
||||
|
||||
let value = ArrayBuilder::new()
|
||||
.push(1)
|
||||
.push(2)
|
||||
.push(3)
|
||||
.unwrap();
|
||||
assert_eq!(value, Value::Array(vec!(Value::I64(1), Value::I64(2), Value::I64(3))));
|
||||
|
||||
let value = ArrayBuilder::new()
|
||||
.push_array(|bld| bld.push(1).push(2).push(3))
|
||||
.unwrap();
|
||||
assert_eq!(value, Value::Array(vec!(Value::Array(vec!(Value::I64(1), Value::I64(2), Value::I64(3))))));
|
||||
|
||||
let value = ArrayBuilder::new()
|
||||
.push_object(|bld|
|
||||
bld
|
||||
.insert("a".to_string(), 1)
|
||||
.insert("b".to_string(), 2))
|
||||
.unwrap();
|
||||
|
||||
let mut map = BTreeMap::new();
|
||||
map.insert("a".to_string(), Value::I64(1));
|
||||
map.insert("b".to_string(), Value::I64(2));
|
||||
assert_eq!(value, Value::Array(vec!(Value::Object(map))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_object_builder() {
|
||||
let value = ObjectBuilder::new().unwrap();
|
||||
assert_eq!(value, Value::Object(BTreeMap::new()));
|
||||
|
||||
let value = ObjectBuilder::new()
|
||||
.insert("a".to_string(), 1)
|
||||
.insert("b".to_string(), 2)
|
||||
.unwrap();
|
||||
|
||||
let mut map = BTreeMap::new();
|
||||
map.insert("a".to_string(), Value::I64(1));
|
||||
map.insert("b".to_string(), Value::I64(2));
|
||||
assert_eq!(value, Value::Object(map));
|
||||
}
|
||||
@@ -1,406 +0,0 @@
|
||||
#![feature(custom_derive, plugin)]
|
||||
#![plugin(serde_macros)]
|
||||
|
||||
extern crate serde;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use serde::json::{self, Value};
|
||||
|
||||
macro_rules! btreemap {
|
||||
() => {
|
||||
BTreeMap::new()
|
||||
};
|
||||
($($key:expr => $value:expr),+) => {
|
||||
{
|
||||
let mut map = BTreeMap::new();
|
||||
$(map.insert($key, $value);)+
|
||||
map
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
trait Trait {
|
||||
type Type;
|
||||
}
|
||||
*/
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
#[derive_serialize]
|
||||
#[derive_deserialize]
|
||||
struct NamedUnit;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
#[derive_serialize]
|
||||
enum SerEnum<'a, B: 'a, C: /* Trait + */ 'a, D> where D: /* Trait + */ 'a {
|
||||
Unit,
|
||||
Seq(
|
||||
i8,
|
||||
B,
|
||||
&'a C,
|
||||
//C::Type,
|
||||
&'a mut D,
|
||||
//<D as Trait>::Type,
|
||||
),
|
||||
Map {
|
||||
a: i8,
|
||||
b: B,
|
||||
c: &'a C,
|
||||
//d: C::Type,
|
||||
e: &'a mut D,
|
||||
//f: <D as Trait>::Type,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
#[derive_deserialize]
|
||||
enum DeEnum<B, C: /* Trait */, D> /* where D: Trait */ {
|
||||
Unit,
|
||||
Seq(
|
||||
i8,
|
||||
B,
|
||||
C,
|
||||
//C::Type,
|
||||
D,
|
||||
//<D as Trait>::Type,
|
||||
),
|
||||
Map {
|
||||
a: i8,
|
||||
b: B,
|
||||
c: C,
|
||||
//d: C::Type,
|
||||
e: D,
|
||||
//f: <D as Trait>::Type,
|
||||
},
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_named_unit() {
|
||||
let named_unit = NamedUnit;
|
||||
|
||||
assert_eq!(
|
||||
json::to_string(&named_unit).unwrap(),
|
||||
"null".to_string()
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
json::to_value(&named_unit),
|
||||
Value::Null
|
||||
);
|
||||
|
||||
let v = json::from_str("null").unwrap();
|
||||
assert_eq!(v, named_unit);
|
||||
|
||||
let v = json::from_value(Value::Null).unwrap();
|
||||
assert_eq!(v, named_unit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ser_named_tuple() {
|
||||
#[derive(Debug, PartialEq)]
|
||||
#[derive_serialize]
|
||||
struct NamedTuple<'a, 'b, A: 'a, B: 'b, C>(&'a A, &'b mut B, C);
|
||||
|
||||
let a = 5;
|
||||
let mut b = 6;
|
||||
let c = 7;
|
||||
let named_tuple = NamedTuple(&a, &mut b, c);
|
||||
|
||||
assert_eq!(
|
||||
json::to_string(&named_tuple).unwrap(),
|
||||
"[5,6,7]"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
json::to_value(&named_tuple),
|
||||
Value::Array(vec![Value::I64(5), Value::I64(6), Value::I64(7)])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_de_named_tuple() {
|
||||
#[derive(Debug, PartialEq)]
|
||||
#[derive_deserialize]
|
||||
struct NamedTuple<A, B, C>(A, B, C);
|
||||
|
||||
assert_eq!(
|
||||
json::from_str("[1,2,3]").unwrap(),
|
||||
NamedTuple(1, 2, 3)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
json::from_str("[1,2,3]").unwrap(),
|
||||
Value::Array(vec![
|
||||
Value::I64(1),
|
||||
Value::I64(2),
|
||||
Value::I64(3),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ser_named_map() {
|
||||
#[derive(Debug, PartialEq)]
|
||||
#[derive_serialize]
|
||||
struct NamedMap<'a, 'b, A: 'a, B: 'b, C> {
|
||||
a: &'a A,
|
||||
b: &'b mut B,
|
||||
c: C,
|
||||
}
|
||||
|
||||
let a = 5;
|
||||
let mut b = 6;
|
||||
let c = 7;
|
||||
let named_map = NamedMap {
|
||||
a: &a,
|
||||
b: &mut b,
|
||||
c: c,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
json::to_string(&named_map).unwrap(),
|
||||
"{\"a\":5,\"b\":6,\"c\":7}"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
json::to_value(&named_map),
|
||||
Value::Object(btreemap![
|
||||
"a".to_string() => Value::I64(5),
|
||||
"b".to_string() => Value::I64(6),
|
||||
"c".to_string() => Value::I64(7)
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_de_named_map() {
|
||||
#[derive(Debug, PartialEq)]
|
||||
#[derive_deserialize]
|
||||
struct NamedMap<A, B, C> {
|
||||
a: A,
|
||||
b: B,
|
||||
c: C,
|
||||
}
|
||||
|
||||
let v = NamedMap {
|
||||
a: 5,
|
||||
b: 6,
|
||||
c: 7,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
json::from_str("{\"a\":5,\"b\":6,\"c\":7}").unwrap(),
|
||||
v
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
json::from_value(Value::Object(btreemap![
|
||||
"a".to_string() => Value::I64(5),
|
||||
"b".to_string() => Value::I64(6),
|
||||
"c".to_string() => Value::I64(7)
|
||||
])).unwrap(),
|
||||
v
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ser_enum_unit() {
|
||||
assert_eq!(
|
||||
json::to_string(&SerEnum::Unit::<u32, u32, u32>).unwrap(),
|
||||
"{\"Unit\":[]}"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
json::to_value(&SerEnum::Unit::<u32, u32, u32>),
|
||||
Value::Object(btreemap!(
|
||||
"Unit".to_string() => Value::Array(vec![]))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ser_enum_seq() {
|
||||
let a = 1;
|
||||
let b = 2;
|
||||
let c = 3;
|
||||
//let d = 4;
|
||||
let mut e = 5;
|
||||
//let f = 6;
|
||||
|
||||
assert_eq!(
|
||||
json::to_string(&SerEnum::Seq(
|
||||
a,
|
||||
b,
|
||||
&c,
|
||||
//d,
|
||||
&mut e,
|
||||
//f,
|
||||
)).unwrap(),
|
||||
"{\"Seq\":[1,2,3,5]}".to_string()
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
json::to_value(&SerEnum::Seq(
|
||||
a,
|
||||
b,
|
||||
&c,
|
||||
//d,
|
||||
&mut e,
|
||||
//e,
|
||||
)),
|
||||
Value::Object(btreemap!(
|
||||
"Seq".to_string() => Value::Array(vec![
|
||||
Value::I64(1),
|
||||
Value::I64(2),
|
||||
Value::I64(3),
|
||||
//Value::I64(4),
|
||||
Value::I64(5),
|
||||
//Value::I64(6),
|
||||
])
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ser_enum_map() {
|
||||
let a = 1;
|
||||
let b = 2;
|
||||
let c = 3;
|
||||
//let d = 4;
|
||||
let mut e = 5;
|
||||
//let f = 6;
|
||||
|
||||
assert_eq!(
|
||||
json::to_string(&SerEnum::Map {
|
||||
a: a,
|
||||
b: b,
|
||||
c: &c,
|
||||
//d: d,
|
||||
e: &mut e,
|
||||
//f: f,
|
||||
}).unwrap(),
|
||||
"{\"Map\":{\"a\":1,\"b\":2,\"c\":3,\"e\":5}}".to_string()
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
json::to_value(&SerEnum::Map {
|
||||
a: a,
|
||||
b: b,
|
||||
c: &c,
|
||||
//d: d,
|
||||
e: &mut e,
|
||||
//f: f,
|
||||
}),
|
||||
Value::Object(btreemap!(
|
||||
"Map".to_string() => Value::Object(btreemap![
|
||||
"a".to_string() => Value::I64(1),
|
||||
"b".to_string() => Value::I64(2),
|
||||
"c".to_string() => Value::I64(3),
|
||||
//"d".to_string() => Value::I64(4)
|
||||
"e".to_string() => Value::I64(5)
|
||||
//"f".to_string() => Value::I64(6)
|
||||
])
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_de_enum_unit() {
|
||||
assert_eq!(
|
||||
json::from_str("{\"Unit\":[]}").unwrap(),
|
||||
DeEnum::Unit::<u32, u32, u32>
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
json::from_value(Value::Object(btreemap!(
|
||||
"Unit".to_string() => Value::Array(vec![]))
|
||||
)).unwrap(),
|
||||
DeEnum::Unit::<u32, u32, u32>
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_de_enum_seq() {
|
||||
let a = 1;
|
||||
let b = 2;
|
||||
let c = 3;
|
||||
//let d = 4;
|
||||
let e = 5;
|
||||
//let f = 6;
|
||||
|
||||
assert_eq!(
|
||||
json::from_str("{\"Seq\":[1,2,3,5]}").unwrap(),
|
||||
DeEnum::Seq(
|
||||
a,
|
||||
b,
|
||||
c,
|
||||
//d,
|
||||
e,
|
||||
//f,
|
||||
)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
json::from_value(Value::Object(btreemap!(
|
||||
"Seq".to_string() => Value::Array(vec![
|
||||
Value::I64(1),
|
||||
Value::I64(2),
|
||||
Value::I64(3),
|
||||
//Value::I64(4),
|
||||
Value::I64(5),
|
||||
//Value::I64(6),
|
||||
])
|
||||
))).unwrap(),
|
||||
DeEnum::Seq(
|
||||
a,
|
||||
b,
|
||||
c,
|
||||
//d,
|
||||
e,
|
||||
//e,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_de_enum_map() {
|
||||
let a = 1;
|
||||
let b = 2;
|
||||
let c = 3;
|
||||
//let d = 4;
|
||||
let e = 5;
|
||||
//let f = 6;
|
||||
|
||||
assert_eq!(
|
||||
json::from_str("{\"Map\":{\"a\":1,\"b\":2,\"c\":3,\"e\":5}}").unwrap(),
|
||||
DeEnum::Map {
|
||||
a: a,
|
||||
b: b,
|
||||
c: c,
|
||||
//d: d,
|
||||
e: e,
|
||||
//f: f,
|
||||
}
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
json::from_value(Value::Object(btreemap!(
|
||||
"Map".to_string() => Value::Object(btreemap![
|
||||
"a".to_string() => Value::I64(1),
|
||||
"b".to_string() => Value::I64(2),
|
||||
"c".to_string() => Value::I64(3),
|
||||
//"d".to_string() => Value::I64(4)
|
||||
"e".to_string() => Value::I64(5)
|
||||
//"f".to_string() => Value::I64(6)
|
||||
])
|
||||
))).unwrap(),
|
||||
DeEnum::Map {
|
||||
a: a,
|
||||
b: b,
|
||||
c: c,
|
||||
//d: d,
|
||||
e: e,
|
||||
//f: f,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -1,544 +0,0 @@
|
||||
#![feature(custom_derive, plugin, test)]
|
||||
#![plugin(serde_macros)]
|
||||
|
||||
extern crate test;
|
||||
extern crate serde;
|
||||
|
||||
use std::vec;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::ser::{Serialize, Serializer, Visitor, SeqVisitor, MapVisitor};
|
||||
|
||||
#[derive(Clone, PartialEq, Debug)]
|
||||
pub enum Token<'a> {
|
||||
Bool(bool),
|
||||
Isize(isize),
|
||||
I8(i8),
|
||||
I16(i16),
|
||||
I32(i32),
|
||||
I64(i64),
|
||||
Usize(usize),
|
||||
U8(u8),
|
||||
U16(u16),
|
||||
U32(u32),
|
||||
U64(u64),
|
||||
F32(f32),
|
||||
F64(f64),
|
||||
Char(char),
|
||||
Str(&'a str),
|
||||
|
||||
Option(bool),
|
||||
|
||||
Unit,
|
||||
NamedUnit(&'a str),
|
||||
EnumUnit(&'a str, &'a str),
|
||||
|
||||
SeqStart(usize),
|
||||
NamedSeqStart(&'a str, usize),
|
||||
EnumSeqStart(&'a str, &'a str, usize),
|
||||
SeqSep(bool),
|
||||
SeqEnd,
|
||||
|
||||
MapStart(usize),
|
||||
NamedMapStart(&'a str, usize),
|
||||
EnumMapStart(&'a str, &'a str, usize),
|
||||
MapSep(bool),
|
||||
MapEnd,
|
||||
}
|
||||
|
||||
struct AssertSerializer<'a> {
|
||||
iter: vec::IntoIter<Token<'a>>,
|
||||
}
|
||||
|
||||
impl<'a> AssertSerializer<'a> {
|
||||
fn new(values: Vec<Token<'a>>) -> AssertSerializer {
|
||||
AssertSerializer {
|
||||
iter: values.into_iter(),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_sequence<V>(&mut self, mut visitor: V) -> Result<(), ()>
|
||||
where V: SeqVisitor
|
||||
{
|
||||
while let Some(()) = try!(visitor.visit(self)) { }
|
||||
|
||||
assert_eq!(self.iter.next(), Some(Token::SeqEnd));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_mapping<V>(&mut self, mut visitor: V) -> Result<(), ()>
|
||||
where V: MapVisitor
|
||||
{
|
||||
while let Some(()) = try!(visitor.visit(self)) { }
|
||||
|
||||
assert_eq!(self.iter.next(), Some(Token::MapEnd));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Serializer for AssertSerializer<'a> {
|
||||
type Value = ();
|
||||
type Error = ();
|
||||
|
||||
fn visit<T: Serialize>(&mut self, value: &T) -> Result<(), ()> {
|
||||
value.visit(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Visitor for AssertSerializer<'a> {
|
||||
type Value = ();
|
||||
type Error = ();
|
||||
|
||||
fn visit_unit(&mut self) -> Result<(), ()> {
|
||||
assert_eq!(self.iter.next(), Some(Token::Unit));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_named_unit(&mut self, name: &str) -> Result<(), ()> {
|
||||
assert_eq!(self.iter.next().unwrap(), Token::NamedUnit(name));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_enum_unit(&mut self, name: &str, variant: &str) -> Result<(), ()> {
|
||||
assert_eq!(self.iter.next().unwrap(), Token::EnumUnit(name, variant));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_bool(&mut self, v: bool) -> Result<(), ()> {
|
||||
assert_eq!(self.iter.next(), Some(Token::Bool(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_isize(&mut self, v: isize) -> Result<(), ()> {
|
||||
assert_eq!(self.iter.next(), Some(Token::Isize(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_i8(&mut self, v: i8) -> Result<(), ()> {
|
||||
assert_eq!(self.iter.next(), Some(Token::I8(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_i16(&mut self, v: i16) -> Result<(), ()> {
|
||||
assert_eq!(self.iter.next(), Some(Token::I16(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_i32(&mut self, v: i32) -> Result<(), ()> {
|
||||
assert_eq!(self.iter.next(), Some(Token::I32(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_i64(&mut self, v: i64) -> Result<(), ()> {
|
||||
assert_eq!(self.iter.next(), Some(Token::I64(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_usize(&mut self, v: usize) -> Result<(), ()> {
|
||||
assert_eq!(self.iter.next(), Some(Token::Usize(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_u8(&mut self, v: u8) -> Result<(), ()> {
|
||||
assert_eq!(self.iter.next(), Some(Token::U8(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_u16(&mut self, v: u16) -> Result<(), ()> {
|
||||
assert_eq!(self.iter.next(), Some(Token::U16(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_u32(&mut self, v: u32) -> Result<(), ()> {
|
||||
assert_eq!(self.iter.next(), Some(Token::U32(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_u64(&mut self, v: u64) -> Result<(), ()> {
|
||||
assert_eq!(self.iter.next(), Some(Token::U64(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_f32(&mut self, v: f32) -> Result<(), ()> {
|
||||
assert_eq!(self.iter.next(), Some(Token::F32(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_f64(&mut self, v: f64) -> Result<(), ()> {
|
||||
assert_eq!(self.iter.next(), Some(Token::F64(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_char(&mut self, v: char) -> Result<(), ()> {
|
||||
assert_eq!(self.iter.next(), Some(Token::Char(v)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_str(&mut self, v: &str) -> Result<(), ()> {
|
||||
assert_eq!(self.iter.next().unwrap(), Token::Str(v));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_none(&mut self) -> Result<(), ()> {
|
||||
assert_eq!(self.iter.next(), Some(Token::Option(false)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_some<V>(&mut self, value: V) -> Result<(), ()>
|
||||
where V: Serialize,
|
||||
{
|
||||
assert_eq!(self.iter.next(), Some(Token::Option(true)));
|
||||
value.visit(self)
|
||||
}
|
||||
|
||||
|
||||
fn visit_seq<V>(&mut self, visitor: V) -> Result<(), ()>
|
||||
where V: SeqVisitor
|
||||
{
|
||||
let (len, _) = visitor.size_hint();
|
||||
|
||||
assert_eq!(self.iter.next(), Some(Token::SeqStart(len)));
|
||||
|
||||
self.visit_sequence(visitor)
|
||||
}
|
||||
|
||||
fn visit_named_seq<V>(&mut self, name: &str, visitor: V) -> Result<(), ()>
|
||||
where V: SeqVisitor
|
||||
{
|
||||
let (len, _) = visitor.size_hint();
|
||||
|
||||
assert_eq!(self.iter.next().unwrap(), Token::NamedSeqStart(name, len));
|
||||
|
||||
self.visit_sequence(visitor)
|
||||
}
|
||||
|
||||
fn visit_enum_seq<V>(&mut self,
|
||||
name: &str,
|
||||
variant: &str,
|
||||
visitor: V) -> Result<(), ()>
|
||||
where V: SeqVisitor
|
||||
{
|
||||
let (len, _) = visitor.size_hint();
|
||||
|
||||
assert_eq!(self.iter.next().unwrap(), Token::EnumSeqStart(name, variant, len));
|
||||
|
||||
self.visit_sequence(visitor)
|
||||
}
|
||||
|
||||
fn visit_seq_elt<T>(&mut self, first: bool, value: T) -> Result<(), ()>
|
||||
where T: Serialize
|
||||
{
|
||||
assert_eq!(self.iter.next(), Some(Token::SeqSep(first)));
|
||||
value.visit(self)
|
||||
}
|
||||
|
||||
fn visit_map<V>(&mut self, visitor: V) -> Result<(), ()>
|
||||
where V: MapVisitor
|
||||
{
|
||||
let (len, _) = visitor.size_hint();
|
||||
|
||||
assert_eq!(self.iter.next(), Some(Token::MapStart(len)));
|
||||
|
||||
self.visit_mapping(visitor)
|
||||
}
|
||||
|
||||
fn visit_named_map<V>(&mut self, name: &str, visitor: V) -> Result<(), ()>
|
||||
where V: MapVisitor
|
||||
{
|
||||
let (len, _) = visitor.size_hint();
|
||||
|
||||
assert_eq!(self.iter.next().unwrap(), Token::NamedMapStart(name, len));
|
||||
|
||||
self.visit_mapping(visitor)
|
||||
}
|
||||
|
||||
fn visit_enum_map<V>(&mut self,
|
||||
name: &str,
|
||||
variant: &str,
|
||||
visitor: V) -> Result<(), ()>
|
||||
where V: MapVisitor
|
||||
{
|
||||
let (len, _) = visitor.size_hint();
|
||||
|
||||
assert_eq!(self.iter.next().unwrap(), Token::EnumMapStart(name, variant, len));
|
||||
|
||||
self.visit_mapping(visitor)
|
||||
}
|
||||
|
||||
fn visit_map_elt<K, V>(&mut self,
|
||||
first: bool,
|
||||
key: K,
|
||||
value: V) -> Result<(), ()>
|
||||
where K: Serialize,
|
||||
V: Serialize,
|
||||
{
|
||||
assert_eq!(self.iter.next(), Some(Token::MapSep(first)));
|
||||
|
||||
try!(key.visit(self));
|
||||
value.visit(self)
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive_serialize]
|
||||
struct NamedUnit;
|
||||
|
||||
#[derive_serialize]
|
||||
struct NamedSeq(i32, i32, i32);
|
||||
|
||||
#[derive_serialize]
|
||||
struct NamedMap {
|
||||
a: i32,
|
||||
b: i32,
|
||||
c: i32,
|
||||
}
|
||||
|
||||
#[derive_serialize]
|
||||
enum Enum {
|
||||
Unit,
|
||||
Seq(i32, i32),
|
||||
Map { a: i32, b: i32 },
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! btreemap {
|
||||
() => {
|
||||
BTreeMap::new()
|
||||
};
|
||||
($($key:expr => $value:expr),+) => {
|
||||
{
|
||||
let mut map = BTreeMap::new();
|
||||
$(map.insert($key, $value);)+
|
||||
map
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! declare_test {
|
||||
($name:ident { $($value:expr => $tokens:expr,)+ }) => {
|
||||
#[test]
|
||||
fn $name() {
|
||||
$(
|
||||
let mut ser = AssertSerializer::new($tokens);
|
||||
assert_eq!(ser.visit(&$value), Ok(()));
|
||||
)+
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! declare_tests {
|
||||
($($name:ident { $($value:expr => $tokens:expr,)+ })+) => {
|
||||
$(
|
||||
declare_test!($name { $($value => $tokens,)+ });
|
||||
)+
|
||||
}
|
||||
}
|
||||
|
||||
declare_tests! {
|
||||
test_unit {
|
||||
() => vec![Token::Unit],
|
||||
}
|
||||
test_bool {
|
||||
true => vec![Token::Bool(true)],
|
||||
false => vec![Token::Bool(false)],
|
||||
}
|
||||
test_isizes {
|
||||
0isize => vec![Token::Isize(0)],
|
||||
0i8 => vec![Token::I8(0)],
|
||||
0i16 => vec![Token::I16(0)],
|
||||
0i32 => vec![Token::I32(0)],
|
||||
0i64 => vec![Token::I64(0)],
|
||||
}
|
||||
test_usizes {
|
||||
0usize => vec![Token::Usize(0)],
|
||||
0u8 => vec![Token::U8(0)],
|
||||
0u16 => vec![Token::U16(0)],
|
||||
0u32 => vec![Token::U32(0)],
|
||||
0u64 => vec![Token::U64(0)],
|
||||
}
|
||||
test_floats {
|
||||
0f32 => vec![Token::F32(0.)],
|
||||
0f64 => vec![Token::F64(0.)],
|
||||
}
|
||||
test_char {
|
||||
'a' => vec![Token::Char('a')],
|
||||
}
|
||||
test_str {
|
||||
"abc" => vec![Token::Str("abc")],
|
||||
"abc".to_string() => vec![Token::Str("abc")],
|
||||
}
|
||||
test_option {
|
||||
None::<i32> => vec![Token::Option(false)],
|
||||
Some(1) => vec![
|
||||
Token::Option(true),
|
||||
Token::I32(1),
|
||||
],
|
||||
}
|
||||
test_slice {
|
||||
&[0][..0] => vec![
|
||||
Token::SeqStart(0),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
&[1, 2, 3][..] => vec![
|
||||
Token::SeqStart(3),
|
||||
Token::SeqSep(true),
|
||||
Token::I32(1),
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_vec {
|
||||
Vec::<isize>::new() => vec![
|
||||
Token::SeqStart(0),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
vec![vec![], vec![1], vec![2, 3]] => vec![
|
||||
Token::SeqStart(3),
|
||||
Token::SeqSep(true),
|
||||
Token::SeqStart(0),
|
||||
Token::SeqEnd,
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::SeqStart(1),
|
||||
Token::SeqSep(true),
|
||||
Token::I32(1),
|
||||
Token::SeqEnd,
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::SeqStart(2),
|
||||
Token::SeqSep(true),
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_tuple {
|
||||
(1,) => vec![
|
||||
Token::SeqStart(1),
|
||||
Token::SeqSep(true),
|
||||
Token::I32(1),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
(1, 2, 3) => vec![
|
||||
Token::SeqStart(3),
|
||||
Token::SeqSep(true),
|
||||
Token::I32(1),
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_btreemap {
|
||||
btreemap![1 => 2] => vec![
|
||||
Token::MapStart(1),
|
||||
Token::MapSep(true),
|
||||
Token::I32(1),
|
||||
Token::I32(2),
|
||||
Token::MapEnd,
|
||||
],
|
||||
btreemap![1 => 2, 3 => 4] => vec![
|
||||
Token::MapStart(2),
|
||||
Token::MapSep(true),
|
||||
Token::I32(1),
|
||||
Token::I32(2),
|
||||
|
||||
Token::MapSep(false),
|
||||
Token::I32(3),
|
||||
Token::I32(4),
|
||||
Token::MapEnd,
|
||||
],
|
||||
btreemap![1 => btreemap![], 2 => btreemap![3 => 4, 5 => 6]] => vec![
|
||||
Token::MapStart(2),
|
||||
Token::MapSep(true),
|
||||
Token::I32(1),
|
||||
Token::MapStart(0),
|
||||
Token::MapEnd,
|
||||
|
||||
Token::MapSep(false),
|
||||
Token::I32(2),
|
||||
Token::MapStart(2),
|
||||
Token::MapSep(true),
|
||||
Token::I32(3),
|
||||
Token::I32(4),
|
||||
|
||||
Token::MapSep(false),
|
||||
Token::I32(5),
|
||||
Token::I32(6),
|
||||
Token::MapEnd,
|
||||
Token::MapEnd,
|
||||
],
|
||||
}
|
||||
test_named_unit {
|
||||
NamedUnit => vec![Token::NamedUnit("NamedUnit")],
|
||||
}
|
||||
test_named_seq {
|
||||
NamedSeq(1, 2, 3) => vec![
|
||||
Token::NamedSeqStart("NamedSeq", 3),
|
||||
Token::SeqSep(true),
|
||||
Token::I32(1),
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::I32(2),
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::I32(3),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_named_map {
|
||||
NamedMap { a: 1, b: 2, c: 3 } => vec![
|
||||
Token::NamedMapStart("NamedMap", 3),
|
||||
Token::MapSep(true),
|
||||
Token::Str("a"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::MapSep(false),
|
||||
Token::Str("b"),
|
||||
Token::I32(2),
|
||||
|
||||
Token::MapSep(false),
|
||||
Token::Str("c"),
|
||||
Token::I32(3),
|
||||
Token::MapEnd,
|
||||
],
|
||||
}
|
||||
test_enum {
|
||||
Enum::Unit => vec![Token::EnumUnit("Enum", "Unit")],
|
||||
Enum::Seq(1, 2) => vec![
|
||||
Token::EnumSeqStart("Enum", "Seq", 2),
|
||||
Token::SeqSep(true),
|
||||
Token::I32(1),
|
||||
|
||||
Token::SeqSep(false),
|
||||
Token::I32(2),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
Enum::Map { a: 1, b: 2 } => vec![
|
||||
Token::EnumMapStart("Enum", "Map", 2),
|
||||
Token::MapSep(true),
|
||||
Token::Str("a"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::MapSep(false),
|
||||
Token::Str("b"),
|
||||
Token::I32(2),
|
||||
Token::MapEnd,
|
||||
],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
channel() {
|
||||
if [ -n "${TRAVIS}" ]; then
|
||||
if [ "${TRAVIS_RUST_VERSION}" = "${CHANNEL}" ]; then
|
||||
pwd
|
||||
(set -x; cargo "$@")
|
||||
fi
|
||||
else
|
||||
pwd
|
||||
(set -x; cargo "+${CHANNEL}" "$@")
|
||||
fi
|
||||
}
|
||||
|
||||
if [ -n "${CLIPPY}" ]; then
|
||||
# cached installation will not work on a later nightly
|
||||
if [ -n "${TRAVIS}" ] && ! cargo install clippy --debug --force; then
|
||||
echo "COULD NOT COMPILE CLIPPY, IGNORING CLIPPY TESTS"
|
||||
exit
|
||||
fi
|
||||
|
||||
cd "$DIR/serde"
|
||||
cargo clippy --features unstable-testing -- -Dclippy
|
||||
|
||||
cd "$DIR/serde_derive"
|
||||
cargo clippy --features unstable-testing -- -Dclippy
|
||||
|
||||
cd "$DIR/test_suite"
|
||||
cargo clippy --features unstable-testing -- -Dclippy
|
||||
|
||||
cd "$DIR/test_suite/no_std"
|
||||
cargo clippy -- -Dclippy
|
||||
else
|
||||
CHANNEL=nightly
|
||||
cargo clean
|
||||
cd "$DIR/serde"
|
||||
channel build
|
||||
channel build --no-default-features
|
||||
channel build --no-default-features --features alloc
|
||||
channel build --no-default-features --features collections
|
||||
channel test --features unstable-testing
|
||||
cd "$DIR/test_suite/deps"
|
||||
channel build
|
||||
cd "$DIR/test_suite"
|
||||
channel test --features unstable-testing
|
||||
cd "$DIR/test_suite/no_std"
|
||||
channel build
|
||||
|
||||
CHANNEL=beta
|
||||
cargo clean
|
||||
cd "$DIR/serde"
|
||||
channel build
|
||||
cd "$DIR/test_suite"
|
||||
channel test
|
||||
|
||||
CHANNEL=stable
|
||||
cargo clean
|
||||
cd "$DIR/serde"
|
||||
channel build
|
||||
channel build --no-default-features
|
||||
|
||||
CHANNEL=1.13.0
|
||||
cargo clean
|
||||
cd "$DIR/serde"
|
||||
channel build
|
||||
channel build --no-default-features
|
||||
fi
|
||||
Reference in New Issue
Block a user